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

  let themes = $state<ThemeGroup[]>([])
  let selectedTheme = $state<ThemeGroup | null>(null)
  let detail = $state<ThemeDetail | null>(null)
  let loading = $state(true)
  let detailLoading = $state(false)

  // 테마 목록 정렬
  let sortCol = $state('fluRt')
  let sortDesc = $state(true)

  // 테마 검색 필터
  let filterQuery = $state('')

  // 구성종목 정렬
  let detailSortCol = $state('fluRt')
  let detailSortDesc = $state(true)

  onMount(async () => {
    try {
      themes = await stockApi.getThemes()
    } finally {
      loading = false
    }
  })

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

  function handleDetailSort(e: CustomEvent<string>) {
    const col = e.detail
    if (detailSortCol === col) detailSortDesc = !detailSortDesc
    else { detailSortCol = col; detailSortDesc = true }
  }

  let filtered = $derived(
    filterQuery
      ? themes.filter(t => t.name.toLowerCase().includes(filterQuery.toLowerCase()) || t.mainStock.toLowerCase().includes(filterQuery.toLowerCase()))
      : themes
  )

  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
    })
  )

  let sortedStocks = $derived(
    detail
      ? [...detail.stocks].sort((a, b) => {
          if (detailSortCol === 'name') {
            const cmp = a.name.localeCompare(b.name, 'ko')
            return detailSortDesc ? -cmp : cmp
          }
          const av = (a as unknown as Record<string, number>)[detailSortCol] ?? 0
          const bv = (b as unknown as Record<string, number>)[detailSortCol] ?? 0
          return detailSortDesc ? bv - av : av - bv
        })
      : []
  )

  async function selectTheme(theme: ThemeGroup) {
    selectedTheme = theme
    detailLoading = true
    detail = null
    detailSortCol = 'fluRt'
    detailSortDesc = true
    try {
      detail = await stockApi.getThemeStocks(theme.code)
    } finally {
      detailLoading = false
    }
  }
</script>

<svelte:head>
  <title>테마 분석 - 주식 시세</title>
</svelte:head>

<h1 class="text-xl font-bold text-white mb-4">테마 분석</h1>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

  <!-- 테마 목록 -->
  <div class="bg-gray-800 rounded-xl overflow-hidden">
    {#if loading}
      <div class="p-8 text-center text-gray-400">로딩 중...</div>
    {:else}
      <div class="px-4 py-3 border-b border-gray-700">
        <input
          type="text"
          bind:value={filterQuery}
          placeholder="테마명 또는 대장주 검색..."
          class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-blue-500"
        />
      </div>
      <div class="overflow-auto max-h-[75vh]">
        <table>
          <thead>
            <tr>
              <SortableHeader col="name" label="테마명" {sortCol} {sortDesc} align="left" class="w-full" on:sort={handleSort} />
              <SortableHeader col="fluRt"      label="등락률"  {sortCol} {sortDesc} on:sort={handleSort} />
              <SortableHeader col="periodRt"   label="기간수익" {sortCol} {sortDesc} on:sort={handleSort} />
              <SortableHeader col="risingCount" label="상승" {sortCol} {sortDesc} on:sort={handleSort} />
              <SortableHeader col="stockCount" label="종목수" {sortCol} {sortDesc} on:sort={handleSort} />
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-700">
            {#each sorted as theme (theme.code)}
              <tr
                class="cursor-pointer hover:bg-gray-700 transition-colors {selectedTheme?.code === theme.code ? 'bg-gray-700' : ''}"
                onclick={() => selectTheme(theme)}
              >
                <td class="px-4 py-3">
                  <div class="text-sm font-medium text-white">{theme.name}</div>
                  <div class="text-xs text-gray-500">{theme.mainStock}</div>
                </td>
                <td class="px-3 py-3 text-right text-sm {priceClass(theme.fluRt)}">
                  {formatRate(theme.fluRt)}
                </td>
                <td class="px-3 py-3 text-right text-sm {priceClass(theme.periodRt)}">
                  {formatRate(theme.periodRt)}
                </td>
                <td class="px-3 py-3 text-right text-sm text-red-400">
                  {theme.risingCount}
                </td>
                <td class="px-3 py-3 text-right text-sm text-gray-300">
                  {theme.stockCount}
                </td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>
    {/if}
  </div>

  <!-- 테마 구성종목 -->
  <div class="bg-gray-800 rounded-xl overflow-hidden">
    {#if !selectedTheme}
      <div class="p-8 text-center text-gray-500">테마를 선택하면 구성종목이 표시됩니다</div>
    {:else if detailLoading}
      <div class="p-8 text-center text-gray-400">로딩 중...</div>
    {:else if detail}
      <div class="px-4 py-3 border-b border-gray-700 flex items-center justify-between">
        <h2 class="text-sm font-semibold text-white">{selectedTheme.name}</h2>
        <div class="flex items-center gap-3 text-xs text-gray-400">
          <span>등락률 <span class="{priceClass(detail.fluRt)}">{formatRate(detail.fluRt)}</span></span>
          <span>기간수익 <span class="{priceClass(detail.periodRt)}">{formatRate(detail.periodRt)}</span></span>
          <span class="text-gray-500">{detail.stocks.length}종목</span>
        </div>
      </div>
      <div class="overflow-auto max-h-[68vh]">
        <table>
          <thead>
            <tr>
              <SortableHeader col="name" label="종목" sortCol={detailSortCol} sortDesc={detailSortDesc} align="left" class="w-full" on:sort={handleDetailSort} />
              <SortableHeader col="curPrc"  label="현재가" sortCol={detailSortCol} sortDesc={detailSortDesc} on:sort={handleDetailSort} />
              <SortableHeader col="predPre" label="전일대비" sortCol={detailSortCol} sortDesc={detailSortDesc} on:sort={handleDetailSort} />
              <SortableHeader col="fluRt"   label="등락률" sortCol={detailSortCol} sortDesc={detailSortDesc} on:sort={handleDetailSort} />
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-700">
            {#each sortedStocks 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">
                  <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 text-sm font-mono {priceClass(stock.fluRt)}">
                  {stock.curPrc.toLocaleString()}
                </td>
                <td class="px-3 py-3 text-right text-sm {priceClass(stock.fluRt)}">
                  {sigToArrow(stock.fluSig)}{stock.predPre.toLocaleString()}
                </td>
                <td class="px-3 py-3 text-right text-sm {priceClass(stock.fluRt)}">
                  {formatRate(stock.fluRt)}
                </td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>
    {/if}
  </div>

</div>
