<script lang="ts">
  import { onMount, onDestroy } from 'svelte'
  import { page } from '$app/state'
  import { goto } from '$app/navigation'
  import { stockApi } from '$lib/api/stock'
  import { accountApi } from '$lib/api/account'
  import { watchlist } from '$lib/stores/watchlist'
  import { priceMap, orderBookMap, wsStore } from '$lib/stores/ws'
  import { formatPrice, formatRate, priceClass } from '$lib/utils'
  import CandleChart from '$lib/components/CandleChart.svelte'
  import type { CandleData, StockPrice } from '$lib/api/types'

  const code = page.params.code!
  let stockInfo = $state<StockPrice | null>(null)
  let candles = $state<CandleData[]>([])
  let chartType = $state<'D' | 'W' | 'M'>('D')
  let buyQty = $state(1)
  let buyPrice = $state(0)
  let sellQty = $state(1)
  let orderMsg = $state('')
  let loading = $state(true)

  let livePrice = $derived($priceMap[code])
  let liveOrderBook = $derived($orderBookMap[code])

  onMount(async () => {
    await watchlist.load()
    wsStore.connect()
    wsStore.subscribeCode(code)
    await loadStock()
    loading = false
  })

  onDestroy(() => {
    wsStore.unsubscribeCode(code)
  })

  async function loadStock() {
    try {
      const [price, chart] = await Promise.all([
        stockApi.getPrice(code),
        stockApi.getChart(code, chartType),
      ])
      stockInfo = price
      candles = chart
      buyPrice = price.currentPrice
    } catch (e) {
      console.error(e)
    }
  }

  async function loadChart(type: 'D' | 'W' | 'M') {
    chartType = type
    try {
      candles = await stockApi.getChart(code, type)
    } catch {}
  }

  async function handleBuy() {
    try {
      await accountApi.buy({ code, qty: buyQty, price: buyPrice })
      orderMsg = '매수 주문 완료'
    } catch (e: unknown) {
      orderMsg = e instanceof Error ? e.message : '주문 실패'
    }
    setTimeout(() => { orderMsg = '' }, 3000)
  }

  async function handleSell() {
    const curPrice = livePrice?.currentPrice ?? stockInfo?.currentPrice ?? 0
    try {
      await accountApi.sell({ code, qty: sellQty, price: curPrice })
      orderMsg = '매도 주문 완료'
    } catch (e: unknown) {
      orderMsg = e instanceof Error ? e.message : '주문 실패'
    }
    setTimeout(() => { orderMsg = '' }, 3000)
  }

  let isWatched = $derived($watchlist.some(i => i.code === code))

  async function toggleWatchlist() {
    if (isWatched) {
      await watchlist.remove(code)
    } else {
      const name = livePrice?.name ?? stockInfo?.name ?? code
      await watchlist.add(code, name)
    }
  }

  const displayPrice = $derived(livePrice ?? stockInfo)
</script>

<svelte:head>
  <title>{displayPrice?.name ?? code} - 주식 시세</title>
</svelte:head>

{#if loading}
  <div class="flex items-center justify-center h-64 text-gray-400">로딩 중...</div>
{:else if displayPrice}
  <!-- 종목 헤더 -->
  <div class="flex items-start justify-between mb-6 flex-wrap gap-4">
    <div>
      <div class="flex items-center gap-3">
        <button onclick={() => goto('/')} class="text-gray-400 hover:text-white">←</button>
        <h1 class="text-2xl font-bold text-white">{displayPrice.name}</h1>
        <span class="text-gray-400 text-sm">{code}</span>
        <span class="text-xs bg-gray-700 text-gray-300 px-2 py-0.5 rounded">{displayPrice.market}</span>
        <button
          onclick={toggleWatchlist}
          class="text-xl transition-colors {isWatched ? 'text-yellow-400' : 'text-gray-600 hover:text-yellow-400'}"
          title={isWatched ? '관심종목 해제' : '관심종목 추가'}
        >★</button>
      </div>

      <div class="flex items-end gap-4 mt-3">
        <span class="text-4xl font-bold {priceClass(displayPrice.changeRate)}">
          {formatPrice(displayPrice.currentPrice)}
        </span>
        <div class="{priceClass(displayPrice.changeRate)} text-lg">
          {displayPrice.changePrice >= 0 ? '+' : ''}{formatPrice(displayPrice.changePrice)}
          ({formatRate(displayPrice.changeRate)})
        </div>
      </div>

      <div class="flex gap-4 mt-2 text-sm text-gray-400">
        <span>시가 {formatPrice(displayPrice.open)}</span>
        <span>고가 <span class="text-red-400">{formatPrice(displayPrice.high)}</span></span>
        <span>저가 <span class="text-blue-400">{formatPrice(displayPrice.low)}</span></span>
        <span>거래량 {displayPrice.volume.toLocaleString()}</span>
        <span>체결강도 <span class="{displayPrice.cntrStr > 100 ? 'text-red-400' : 'text-blue-400'}">{displayPrice.cntrStr.toFixed(1)}</span></span>
      </div>
    </div>
  </div>

  <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
    <!-- 차트 -->
    <div class="xl:col-span-2">
      <div class="bg-gray-800 rounded-xl p-4">
        <div class="flex items-center justify-between mb-3">
          <h2 class="text-sm font-medium text-gray-300">캔들 차트</h2>
          <div class="flex gap-1">
            {#each [['D','일봉'], ['W','주봉'], ['M','월봉']] as [type, label]}
              <button
                onclick={() => loadChart(type as 'D'|'W'|'M')}
                class="px-3 py-1 text-xs rounded {chartType === type ? 'bg-blue-600 text-white' : 'bg-gray-700 text-gray-300 hover:bg-gray-600'}"
              >{label}</button>
            {/each}
          </div>
        </div>
        <CandleChart data={candles} height={350} livePrice={livePrice} {chartType} />
      </div>
    </div>

    <!-- 사이드: 호가창 + 주문 -->
    <div class="space-y-4">
      <!-- 호가창 -->
      {#if liveOrderBook}
        <div class="bg-gray-800 rounded-xl p-4">
          <h2 class="text-sm font-medium text-gray-300 mb-3">호가창</h2>
          <div class="text-xs space-y-0.5">
            <!-- 매도 호가 (역순: 10→1) -->
            {#each [...liveOrderBook.asks].reverse() as ask}
              <div class="flex justify-between py-0.5 hover:bg-gray-700 rounded px-1">
                <span class="text-blue-400 font-mono">{ask.volume.toLocaleString()}</span>
                <span class="text-blue-300 font-mono">{formatPrice(ask.price)}</span>
              </div>
            {/each}
            <!-- 현재가 구분선 -->
            <div class="border-t border-gray-600 my-1 text-center text-yellow-400 font-bold text-sm py-1">
              {formatPrice(displayPrice.currentPrice)}
            </div>
            <!-- 매수 호가 -->
            {#each liveOrderBook.bids as bid}
              <div class="flex justify-between py-0.5 hover:bg-gray-700 rounded px-1">
                <span class="text-red-300 font-mono">{formatPrice(bid.price)}</span>
                <span class="text-red-400 font-mono">{bid.volume.toLocaleString()}</span>
              </div>
            {/each}
          </div>
        </div>
      {/if}

      <!-- 주문 패널 -->
      <div class="bg-gray-800 rounded-xl p-4">
        <h2 class="text-sm font-medium text-gray-300 mb-3">주문</h2>
        {#if orderMsg}
          <div class="text-sm text-center py-2 mb-3 rounded bg-gray-700 text-green-400">
            {orderMsg}
          </div>
        {/if}
        <div class="space-y-3">
          <!-- 매수 -->
          <div class="space-y-2">
            <div class="flex gap-2">
              <div class="flex-1">
                <label class="text-xs text-gray-400 mb-1 block" for="buy-price">가격</label>
                <input
                  id="buy-price"
                  type="number"
                  bind:value={buyPrice}
                  class="w-full bg-gray-700 border border-gray-600 rounded px-2 py-1.5 text-sm text-white"
                />
              </div>
              <div class="w-20">
                <label class="text-xs text-gray-400 mb-1 block" for="buy-qty">수량</label>
                <input
                  id="buy-qty"
                  type="number"
                  bind:value={buyQty}
                  min="1"
                  class="w-full bg-gray-700 border border-gray-600 rounded px-2 py-1.5 text-sm text-white"
                />
              </div>
            </div>
            <button
              onclick={handleBuy}
              class="w-full bg-red-600 hover:bg-red-500 text-white text-sm font-medium rounded py-2 transition-colors"
            >
              매수 ({(buyPrice * buyQty).toLocaleString()}원)
            </button>
          </div>

          <hr class="border-gray-700" />

          <!-- 매도 -->
          <div class="flex items-end gap-2">
            <div class="flex-1">
              <label class="text-xs text-gray-400 mb-1 block" for="sell-qty">수량</label>
              <input
                id="sell-qty"
                type="number"
                bind:value={sellQty}
                min="1"
                class="w-full bg-gray-700 border border-gray-600 rounded px-2 py-1.5 text-sm text-white"
              />
            </div>
            <button
              onclick={handleSell}
              class="flex-1 bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium rounded py-2 transition-colors"
            >
              시장가 매도
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
{:else}
  <div class="flex items-center justify-center h-64">
    <div class="text-center">
      <div class="text-gray-400 mb-3">종목 정보를 불러올 수 없습니다</div>
      <button onclick={() => goto('/')} class="text-blue-400 hover:underline">← 돌아가기</button>
    </div>
  </div>
{/if}
