<script lang="ts">
  import { onMount } from 'svelte'
  import { goto } from '$app/navigation'
  import { stockApi } from '$lib/api/stock'
  import { formatRate, priceClass, sigClass, sigToArrow, formatVolume } from '$lib/utils'
  import SortableHeader from '$lib/components/SortableHeader.svelte'
  import type { Kospi200Stock } from '$lib/api/types'

  let stocks = $state<Kospi200Stock[]>([])
  let loading = $state(true)
  let sortCol = $state('fluRt')
  let sortDesc = $state(true)
  let filterQuery = $state('')

  onMount(async () => {
    try {
      stocks = await stockApi.getKospi200()
    } finally {
      loading = false
    }
  })

  function handleSort(e: CustomEvent<string>) {
    const col = e.detail
    if (sortCol === col) {
      sortDesc = !sortDesc
    } else {
      sortCol = col
      sortDesc = true
    }
  }

  let filtered = $derived(
    filterQuery
      ? stocks.filter(s =>
          s.name.includes(filterQuery) || s.code.includes(filterQuery)
        )
      : stocks
  )

  let sorted = $derived(
    [...filtered].sort((a, b) => {
      if (sortCol === 'name') {
        const cmp = a.name.localeCompare(b.name, 'ko')
        return sortDesc ? -cmp : cmp
      }
      const av = (a as unknown as Record<string, number>)[sortCol] ?? 0
      const bv = (b as unknown as Record<string, number>)[sortCol] ?? 0
      return sortDesc ? bv - av : av - bv
    })
  )
</script>

<svelte:head>
  <title>코스피200 - 주식 시세</title>
</svelte:head>

<div class="flex items-center justify-between mb-4">
  <h1 class="text-xl font-bold text-white">코스피200</h1>
  <input
    type="text"
    bind:value={filterQuery}
    placeholder="종목 검색..."
    class="bg-gray-700 border border-gray-600 text-white text-sm rounded-lg px-3 py-1.5 w-48 focus:outline-none focus:ring-1 focus:ring-blue-500"
  />
</div>

{#if loading}
  <div class="flex items-center justify-center h-64 text-gray-400">로딩 중...</div>
{:else}
  <div class="bg-gray-800 rounded-xl overflow-hidden">
    <div class="overflow-auto">
      <table>
        <thead>
          <tr>
            <SortableHeader col="name" label="종목" {sortCol} {sortDesc} align="left" class="sticky left-0 bg-gray-800" on:sort={handleSort} />
            <SortableHeader col="curPrc" label="현재가" {sortCol} {sortDesc} on:sort={handleSort} />
            <SortableHeader col="predPre" label="전일대비" {sortCol} {sortDesc} on:sort={handleSort} />
            <SortableHeader col="fluRt" label="등락률" {sortCol} {sortDesc} on:sort={handleSort} />
            <SortableHeader col="volume" label="거래량" {sortCol} {sortDesc} on:sort={handleSort} />
            <SortableHeader col="open" label="시가" {sortCol} {sortDesc} on:sort={handleSort} />
            <SortableHeader col="high" label="고가" {sortCol} {sortDesc} on:sort={handleSort} />
            <SortableHeader col="low" label="저가" {sortCol} {sortDesc} on:sort={handleSort} />
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-700">
          {#each sorted as stock (stock.code)}
            <tr
              class="cursor-pointer hover:bg-gray-700 transition-colors"
              onclick={() => goto(`/stock/${stock.code}`)}
            >
              <td class="px-4 py-3 sticky left-0 bg-gray-800">
                <div class="text-sm font-medium text-white">{stock.name}</div>
                <div class="text-xs text-gray-500">{stock.code}</div>
              </td>
              <td class="px-3 py-3 text-right font-mono text-sm {priceClass(stock.fluRt)}">
                {stock.curPrc.toLocaleString()}
              </td>
              <td class="px-3 py-3 text-right text-sm {sigClass(stock.predPreSig)}">
                {sigToArrow(stock.predPreSig)} {stock.predPre.toLocaleString()}
              </td>
              <td class="px-3 py-3 text-right text-sm {priceClass(stock.fluRt)}">
                {formatRate(stock.fluRt)}
              </td>
              <td class="px-3 py-3 text-right text-sm text-gray-300">
                {formatVolume(stock.volume)}
              </td>
              <td class="px-3 py-3 text-right text-sm text-gray-300">{stock.open.toLocaleString()}</td>
              <td class="px-3 py-3 text-right text-sm text-red-400">{stock.high.toLocaleString()}</td>
              <td class="px-3 py-3 text-right text-sm text-blue-400">{stock.low.toLocaleString()}</td>
            </tr>
          {/each}
        </tbody>
      </table>
    </div>
  </div>
{/if}
