<script lang="ts">
  import { onMount, onDestroy } from 'svelte'
  import { goto } from '$app/navigation'
  import { stockApi } from '$lib/api/stock'
  import { watchlist } from '$lib/stores/watchlist'
  import { priceMap, wsStore } from '$lib/stores/ws'
  import { formatPrice, formatRate, priceClass, formatVolume } from '$lib/utils'
  import CntrChart from '$lib/components/CntrChart.svelte'
  import SortableHeader from '$lib/components/SortableHeader.svelte'
  import Modal from '$lib/components/Modal.svelte'
  import type { IndexQuote, Signal, WatchlistItem, StockInfo } from '$lib/api/types'

  let indices = $state<IndexQuote[]>([])
  let signals = $state<Signal[]>([])
  let watchlistSignals = $state<Map<string, Signal>>(new Map())
  let scannerOn = $state(true)
  let updatedAt = $state('')
  let searchQuery = $state('')
  let searchResults = $state<StockInfo[]>([])
  let searchTimer: ReturnType<typeof setTimeout> | null = null
  let addingCode = $state('')
  let showGuide = $state(false)
  let pollTimer: ReturnType<typeof setInterval> | null = null
  let watchlistPollTimer: ReturnType<typeof setInterval> | null = null

  // 관심종목 테이블 정렬
  let wlSortCol = $state('')
  let wlSortDesc = $state(true)
  let wlSorted = $state<WatchlistItem[]>([])

  function handleWlSort(e: CustomEvent<string>) {
    const col = e.detail
    if (wlSortCol === col) wlSortDesc = !wlSortDesc
    else { wlSortCol = col; wlSortDesc = true }
    applyWlSort()
  }

  function applyWlSort() {
    const items = [...$watchlist]
    if (!wlSortCol) { wlSorted = []; return }
    const pm = $priceMap
    items.sort((a, b) => {
      if (wlSortCol === 'name') {
        const cmp = a.name.localeCompare(b.name, 'ko')
        return wlSortDesc ? -cmp : cmp
      }
      const pa = pm[a.code]
      const pb = pm[b.code]
      let av = 0, bv = 0
      if (wlSortCol === 'currentPrice') { av = pa?.currentPrice ?? 0; bv = pb?.currentPrice ?? 0 }
      else if (wlSortCol === 'changeRate') { av = pa?.changeRate ?? 0; bv = pb?.changeRate ?? 0 }
      else if (wlSortCol === 'cntrStr') { av = pa?.cntrStr ?? 0; bv = pb?.cntrStr ?? 0 }
      return wlSortDesc ? bv - av : av - bv
    })
    wlSorted = items
  }

  // 종목별 체결강도 히스토리 (canvas 미니차트용)
  const cntrHistoryMap = new Map<string, number[]>()
  // 히스토리 트리거용 (Svelte 반응성)
  let cntrTick = $state(0)

  const MAX_HISTORY = 60

  function recordCntr(code: string, val: number) {
    if (!val) return
    if (!cntrHistoryMap.has(code)) cntrHistoryMap.set(code, [])
    const arr = cntrHistoryMap.get(code)!
    arr.push(val)
    if (arr.length > MAX_HISTORY) arr.shift()
  }

  function getCntrHistory(code: string): number[] {
    return cntrHistoryMap.get(code) ?? []
  }

  onMount(async () => {
    await watchlist.load()
    wsStore.connect()
    loadIndices()
    loadScanner()
    fetchWatchlistSignals()
    watchlistPollTimer = setInterval(fetchWatchlistSignals, 10_000)
  })

  // 관심종목 변경 시 WebSocket 구독
  $effect(() => {
    const codes = $watchlist.map(i => i.code)
    if (codes.length > 0) wsStore.subscribeCodes(codes)
  })

  // WebSocket 가격 수신 → 체결강도 히스토리 업데이트 (시그널 + 관심종목)
  $effect(() => {
    const map = $priceMap  // 반응성 트리거
    signals.forEach(s => {
      const live = map[s.code]
      if (live?.cntrStr) {
        recordCntr(s.code, live.cntrStr)
        cntrTick++
      }
    })
    $watchlist.forEach(item => {
      const live = map[item.code]
      if (live?.cntrStr) {
        recordCntr(item.code, live.cntrStr)
        cntrTick++
      }
    })
  })

  async function fetchWatchlistSignals() {
    try {
      const data = await stockApi.getWatchlistSignals()
      const m = new Map<string, Signal>()
      data?.forEach(s => m.set(s.code, s))
      watchlistSignals = m
      // 관심종목 WS 구독 + 히스토리 초기값
      data?.forEach(s => recordCntr(s.code, s.cntrStr))
      cntrTick++
    } catch {}
  }

  async function loadIndices() {
    try { indices = await stockApi.getIndices() } catch {}
  }

  async function loadScanner() {
    try {
      const status = await stockApi.getScannerStatus()
      scannerOn = (status as { enabled?: boolean; running?: boolean }).enabled
        ?? (status as { running?: boolean }).running
        ?? true
    } catch {}
    if (scannerOn) startPolling()
  }

  async function fetchSignals() {
    try {
      const data = await stockApi.getSignals()
      signals = data ?? []
      const now = new Date()
      updatedAt = now.toTimeString().slice(0, 8) + ' 기준'
      // 새 신호 종목 WS 구독 + 히스토리 초기 기록
      const codes = signals.map(s => s.code)
      wsStore.subscribeCodes(codes)
      signals.forEach(s => recordCntr(s.code, s.cntrStr))
      cntrTick++
    } catch {}
  }

  function startPolling() {
    if (pollTimer) return
    fetchSignals()
    pollTimer = setInterval(fetchSignals, 10_000)
  }

  function stopPolling() {
    if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
    signals = []
  }

  async function toggleScanner() {
    try {
      await stockApi.toggleScanner()
      scannerOn = !scannerOn
      scannerOn ? startPolling() : stopPolling()
    } catch {}
  }

  function onSearchInput() {
    if (searchTimer) clearTimeout(searchTimer)
    if (!searchQuery.trim()) { searchResults = []; return }
    searchTimer = setTimeout(async () => {
      try { searchResults = await stockApi.search(searchQuery) } catch {}
    }, 300)
  }

  async function addToWatchlist(item: StockInfo) {
    addingCode = item.code
    try {
      await watchlist.add(item.code, item.name)
      wsStore.subscribeCode(item.code)
      searchQuery = ''
      searchResults = []
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : '추가 실패')
    } finally {
      addingCode = ''
    }
  }

  async function removeFromWatchlist(code: string) {
    await watchlist.remove(code)
  }

  onDestroy(() => {
    if (searchTimer) clearTimeout(searchTimer)
    if (pollTimer) clearInterval(pollTimer)
  })

  // ── 신호 카드 헬퍼 함수 ──

  function signalTypeCls(type: string): string {
    const m: Record<string, string> = {
      '강한매수': 'bg-red-600 text-white border-red-700',
      '매수우세': 'bg-orange-400 text-white border-orange-500',
      '물량소화': 'bg-yellow-100 text-yellow-700 border-yellow-300',
      '추격위험': 'bg-gray-800 text-white border-gray-900',
      '약한상승': 'bg-gray-100 text-gray-500 border-gray-300',
    }
    return m[type] ?? 'bg-gray-100 text-gray-500 border-gray-300'
  }

  function riseProbCls(label: string): string {
    return label === '매우 높음'
      ? 'bg-emerald-500 text-white border border-emerald-600'
      : 'bg-teal-100 text-teal-700 border border-teal-200'
  }

  function risingBadgeCls(n: number): string {
    if (n >= 4) return 'bg-red-500 text-white'
    if (n >= 2) return 'bg-orange-400 text-white'
    return 'bg-yellow-100 text-yellow-700'
  }

  function risingLabel(n: number): string {
    if (n >= 4) return `🔥${n}연속`
    if (n >= 2) return `▲${n}연속`
    return '↑상승'
  }

  function sentimentCls(s: string): string {
    const m: Record<string, string> = {
      '호재': 'bg-green-100 text-green-700 border border-green-200',
      '악재': 'bg-red-100 text-red-600 border border-red-200',
      '중립': 'bg-gray-100 text-gray-500',
    }
    return m[s] ?? ''
  }

  function rateBadgeCls(r: number): string {
    if (r > 0) return 'bg-red-50 text-red-500'
    if (r < 0) return 'bg-blue-50 text-blue-500'
    return 'bg-gray-100 text-gray-500'
  }

  function volRatioCls(r: number): string {
    if (r >= 10) return 'text-gray-400 line-through'
    if (r >= 5)  return 'text-orange-400'
    if (r >= 2)  return 'text-green-500 font-semibold'
    if (r >= 1)  return 'text-green-400'
    return 'text-gray-500'
  }

  function askBidCls(r: number): string {
    if (r <= 0.7) return 'text-green-500 font-semibold'
    if (r <= 1.0) return 'text-green-400'
    if (r <= 1.5) return 'text-gray-400'
    return 'text-blue-400'
  }

  function askBidLabel(r: number): string {
    if (r <= 0.7) return '매수 강세'
    if (r <= 1.0) return '매수 우세'
    if (r <= 1.5) return '균형'
    return '매도 우세'
  }

  function pricePosClass(p: number): string {
    if (p >= 80) return 'text-red-400 font-semibold'
    if (p >= 60) return 'text-orange-400'
    if (p <= 30) return 'text-blue-400'
    return 'text-gray-400'
  }

  function nextDayCls(trend: string): string {
    if (trend === '상승') return 'bg-red-50 text-red-500 border border-red-200'
    if (trend === '하락') return 'bg-blue-50 text-blue-500 border border-blue-200'
    return 'bg-gray-800 text-gray-400 border border-gray-700'
  }

  function nextDayIcon(trend: string): string {
    if (trend === '상승') return '▲'
    if (trend === '하락') return '▼'
    return '─'
  }
</script>

<svelte:head>
  <title>주식 시세</title>
</svelte:head>

<!-- 지수 현황 -->
{#if indices.length > 0}
  <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
    {#each indices as idx}
      <div class="bg-gray-800 rounded-lg px-4 py-3">
        <div class="text-xs text-gray-400 mb-1">{idx.name}</div>
        <div class="text-lg font-bold text-white">{idx.value.toLocaleString('ko-KR', { maximumFractionDigits: 2 })}</div>
        <div class="text-sm {priceClass(idx.changeRate)}">{formatRate(idx.changeRate)}</div>
      </div>
    {/each}
  </div>
{/if}

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

  <!-- 왼쪽: 관심종목 -->
  <div class="lg:col-span-1">
    <div class="flex items-center justify-between mb-3">
      <h2 class="text-base font-semibold text-white flex items-center gap-2">
        <span class="text-yellow-400">★</span> 관심종목
      </h2>
      <!-- 종목 검색 -->
      <div class="relative">
        <input
          type="text"
          bind:value={searchQuery}
          oninput={onSearchInput}
          placeholder="종목 검색..."
          class="bg-gray-700 border border-gray-600 text-white text-sm rounded-lg px-3 py-1.5 w-44 focus:outline-none focus:ring-1 focus:ring-blue-500"
        />
        {#if searchResults.length > 0}
          <div class="absolute right-0 top-full mt-1 w-64 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-20 overflow-hidden">
            {#each searchResults.slice(0, 8) as result}
              <button
                class="w-full text-left px-3 py-2 hover:bg-gray-700 flex items-center justify-between text-sm"
                onclick={() => addToWatchlist(result)}
                disabled={addingCode === result.code}
              >
                <span>
                  <span class="text-white font-medium">{result.name}</span>
                  <span class="text-gray-400 ml-2 text-xs">{result.code}</span>
                </span>
                <span class="text-xs text-gray-500">{result.market}</span>
              </button>
            {/each}
          </div>
        {/if}
      </div>
    </div>

    {#if $watchlist.length === 0}
      <div class="bg-gray-800 rounded-xl p-8 text-center text-gray-500 text-sm border border-dashed border-gray-700">
        종목을 검색해 관심종목을 추가하세요
      </div>
    {:else}
      <div class="bg-gray-800 rounded-xl overflow-hidden">
        <table>
          <thead>
            <tr>
              <SortableHeader col="name" label="종목" sortCol={wlSortCol} sortDesc={wlSortDesc} align="left" on:sort={handleWlSort} />
              <SortableHeader col="currentPrice" label="현재가" sortCol={wlSortCol} sortDesc={wlSortDesc} on:sort={handleWlSort} />
              <SortableHeader col="changeRate" label="등락" sortCol={wlSortCol} sortDesc={wlSortDesc} on:sort={handleWlSort} />
              <SortableHeader col="cntrStr" label="강도" sortCol={wlSortCol} sortDesc={wlSortDesc} on:sort={handleWlSort} />
              <th class="w-8"></th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-700/50">
            {#each (wlSorted.length > 0 ? wlSorted : $watchlist) as item (item.code)}
              {@const price = $priceMap[item.code]}
              <tr
                class="hover:bg-gray-750 cursor-pointer transition-colors"
                onclick={() => goto(`/stock/${item.code}`)}
              >
                <td class="px-4 py-2.5">
                  <div class="font-medium text-white text-sm">{item.name}</div>
                  <div class="text-xs text-gray-500">{item.code}</div>
                </td>
                <td class="px-3 py-2.5 text-right font-mono text-sm font-medium {price ? priceClass(price.changeRate) : 'text-gray-400'}">
                  {price ? formatPrice(price.currentPrice) : '-'}
                </td>
                <td class="px-3 py-2.5 text-right text-xs {price ? priceClass(price.changeRate) : 'text-gray-400'}">
                  {price ? formatRate(price.changeRate) : '-'}
                </td>
                <td class="px-3 py-2.5 text-right text-xs {price ? (price.cntrStr > 100 ? 'text-red-400' : price.cntrStr > 0 ? 'text-blue-400' : 'text-gray-400') : 'text-gray-400'}">
                  {price ? price.cntrStr.toFixed(1) : '-'}
                </td>
                <td class="pr-3 py-2.5 text-center">
                  <!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
                  <span
                    class="text-gray-600 hover:text-red-400 cursor-pointer text-base transition-colors"
                    onclick={(e) => { e.stopPropagation(); removeFromWatchlist(item.code) }}
                  >×</span>
                </td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>
    {/if}
  </div>

  <!-- 오른쪽: 체결강도 상승 감지 -->
  <div class="lg:col-span-2">
    <div class="flex items-center gap-3 mb-3 flex-wrap">
      <h2 class="text-base font-semibold text-white flex items-center gap-2">
        <span class="text-orange-400">⚡</span> 체결강도 상승 감지
        <span class="text-xs font-normal text-gray-500">(거래량 상위 20 · 10초 갱신)</span>
      </h2>

      <!-- 기준 안내 -->
      <button
        onclick={() => { showGuide = true }}
        class="w-5 h-5 rounded-full bg-gray-700 text-gray-400 text-xs font-bold hover:bg-orange-900/50 hover:text-orange-400 transition-colors flex items-center justify-center shrink-0"
      >?</button>

      <!-- 스캐너 ON/OFF -->
      <button
        onclick={toggleScanner}
        class="text-xs px-2.5 py-1 rounded-full font-semibold border transition-colors shrink-0
          {scannerOn ? 'bg-green-900/50 text-green-400 border-green-700' : 'bg-gray-700 text-gray-400 border-gray-600'}"
      >
        {scannerOn ? '● ON' : '○ OFF'}
      </button>

      {#if updatedAt}
        <span class="text-xs text-gray-500 ml-auto">{updatedAt}</span>
      {/if}
    </div>

    {#if !scannerOn}
      <div class="bg-gray-800 rounded-xl p-8 text-center text-gray-500 text-sm">
        스캐너가 꺼져 있습니다. 버튼을 눌러 켜주세요.
      </div>
    {:else if signals.length === 0}
      <div class="bg-gray-800 rounded-xl p-8 text-center text-gray-500 text-sm">
        08:00 이후 거래량 상위 종목에서 체결강도 100 이상 + 상승 종목을 표시합니다.
      </div>
    {:else}
      <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
        {#each signals as sig (sig.code)}
          {@const live = $priceMap[sig.code]}
          {@const displayPrice = live ?? sig}
          {@const history = getCntrHistory(sig.code)}
          <!-- svelte-ignore a11y_no_static_element_interactions a11y_click_events_have_key_events -->
          <div
            class="bg-gray-800 rounded-xl p-4 border border-orange-900/30 hover:border-orange-700/50 cursor-pointer transition-all hover:shadow-lg hover:shadow-orange-900/10"
            onclick={() => goto(`/stock/${sig.code}`)}
          >
            <!-- 상단: 종목코드 + 뱃지들 -->
            <div class="flex items-start justify-between mb-2 gap-1 flex-wrap">
              <span class="text-xs text-gray-500 font-mono">{sig.code}</span>
              <div class="flex items-center gap-1 flex-wrap justify-end">
                {#if sig.signalType}
                  <span class="border {signalTypeCls(sig.signalType)} text-xs px-1.5 py-0.5 rounded font-bold">{sig.signalType}</span>
                {/if}
                {#if sig.riseLabel}
                  <span class="{riseProbCls(sig.riseLabel)} text-xs px-1.5 py-0.5 rounded font-bold" title="상승확률점수: {sig.riseScore}점">
                    {sig.riseLabel === '매우 높음' ? '🚀' : '📈'} {sig.riseLabel}
                  </span>
                {/if}
                {#if sig.risingCount >= 1}
                  <span class="{risingBadgeCls(sig.risingCount)} text-xs px-1.5 py-0.5 rounded font-bold">{risingLabel(sig.risingCount)}</span>
                {/if}
                {#if sig.sentiment && sig.sentiment !== '정보없음'}
                  <span class="{sentimentCls(sig.sentiment)} text-xs px-1.5 py-0.5 rounded font-semibold" title={sig.sentimentReason}>{sig.sentiment}</span>
                {/if}
              </div>
            </div>

            <!-- 종목명 + 현재가 -->
            <p class="font-bold text-white text-sm truncate mb-0.5">{sig.name}</p>
            <p class="text-2xl font-bold {priceClass(displayPrice.changeRate)} mb-2">
              {formatPrice(displayPrice.currentPrice)}원
            </p>

            <!-- 지표 -->
            <div class="border-t border-gray-700 pt-2 space-y-1.5 text-xs">
              <div class="flex justify-between">
                <span class="text-gray-400">체결강도</span>
                <span class="font-bold text-orange-400">{(live?.cntrStr ?? sig.cntrStr).toFixed(2)}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-400">직전 대비</span>
                <span class="text-gray-400">
                  {sig.prevCntrStr.toFixed(2)} →
                  <span class="text-green-400 font-semibold">+{(sig.cntrStr - sig.prevCntrStr).toFixed(2)}</span>
                </span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-400">등락률</span>
                <span class="{rateBadgeCls(displayPrice.changeRate)} px-1.5 py-0.5 rounded-full font-semibold">
                  {formatRate(displayPrice.changeRate)}
                </span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-400">거래량</span>
                <span class="text-gray-300">{formatVolume(live?.volume ?? sig.volume)}</span>
              </div>

              <!-- 복합 지표 -->
              {#if sig.volRatio > 0}
                <div class="flex justify-between pt-1.5 border-t border-gray-700">
                  <span class="text-gray-400">거래량 증가</span>
                  <span class="{volRatioCls(sig.volRatio)}">
                    {sig.volRatio.toFixed(1)}배{sig.volRatio >= 10 ? ' ⚠과열' : ''}
                  </span>
                </div>
              {/if}
              {#if sig.totalAskVol > 0 && sig.totalBidVol > 0}
                <div class="flex justify-between">
                  <span class="text-gray-400">매도/매수 잔량</span>
                  <span class="{askBidCls(sig.askBidRatio)}">
                    {sig.askBidRatio.toFixed(2)} ({askBidLabel(sig.askBidRatio)})
                  </span>
                </div>
              {/if}
              {#if sig.pricePos !== undefined}
                <div class="flex justify-between">
                  <span class="text-gray-400">가격 위치</span>
                  <span class="{pricePosClass(sig.pricePos)}">{sig.pricePos.toFixed(0)}%</span>
                </div>
              {/if}

              <!-- AI 목표가 -->
              {#if sig.targetPrice && sig.targetPrice > 0}
                {@const diff = sig.targetPrice - displayPrice.currentPrice}
                {@const pct = ((diff / displayPrice.currentPrice) * 100).toFixed(1)}
                <div class="flex justify-between pt-1.5 border-t border-purple-900/30">
                  <span class="text-gray-400">AI 목표가</span>
                  <span
                    class="bg-purple-900/40 text-purple-300 border border-purple-700/50 px-1.5 py-0.5 rounded font-semibold"
                    title={sig.targetReason}
                  >
                    {formatPrice(sig.targetPrice)}원
                    <span class="opacity-70 text-xs">({diff >= 0 ? '+' : ''}{pct}%)</span>
                  </span>
                </div>
              {/if}

              <!-- 익일 추세 -->
              {#if sig.nextDayTrend}
                <div class="flex items-start justify-between pt-1.5 border-t border-gray-700">
                  <span class="text-gray-400 shrink-0">익일 추세</span>
                  <div class="text-right">
                    <span
                      class="{nextDayCls(sig.nextDayTrend)} text-xs px-2 py-0.5 rounded font-bold"
                      title={sig.nextDayReason}
                    >
                      {nextDayIcon(sig.nextDayTrend)} {sig.nextDayTrend}
                      {#if sig.nextDayConf}
                        <span class="opacity-60 font-normal ml-0.5">({sig.nextDayConf})</span>
                      {/if}
                    </span>
                    {#if sig.nextDayReason}
                      <p class="text-gray-500 text-xs mt-0.5 truncate max-w-[160px]" title={sig.nextDayReason}>{sig.nextDayReason}</p>
                    {/if}
                  </div>
                </div>
              {:else}
                <div class="flex justify-between pt-1.5 border-t border-gray-700">
                  <span class="text-gray-400">익일 추세</span>
                  <span class="text-gray-500 animate-pulse">분석 중...</span>
                </div>
              {/if}
            </div>

            <!-- 체결강도 미니 라인차트 -->
            {#key cntrTick}
              {#if history.length >= 2}
                <div class="mt-3">
                  <CntrChart {history} height={44} />
                </div>
              {/if}
            {/key}
          </div>
        {/each}
      </div>
    {/if}
  </div>
</div>

<!-- 시그널 판단 기준 모달 -->
<Modal title="⚡ 시그널 판단 기준" open={showGuide} on:close={() => { showGuide = false }}>
  <div class="space-y-5 text-sm text-gray-300 max-h-[70vh] overflow-y-auto pr-1">

    <!-- 스코어 -->
    <div>
      <p class="font-semibold text-white mb-2">📊 상승 확률 스코어 (0~100점)</p>
      <p class="text-xs text-gray-500 mb-3">4가지 복합 요소를 동시에 만족해야 진짜 상승 확률이 높습니다.</p>
      <div class="overflow-auto rounded-lg border border-gray-700">
        <table class="w-full text-xs">
          <thead>
            <tr class="bg-gray-700/50">
              <th class="text-left px-3 py-2 font-semibold text-gray-300">요소</th>
              <th class="text-center px-3 py-2 font-semibold text-gray-300 w-16">배점</th>
              <th class="text-left px-3 py-2 font-semibold text-gray-300">핵심 로직</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-700">
            {#each [
              ['A. 체결강도 레벨', '0~30', '150+: 30점 · 130+: 22점 · 110+: 14점'],
              ['B. 연속 상승 횟수', '0~25', '5회+: 25점 · 3회+: 14점 · 1회: 3점'],
              ['C. 가격 위치/캔들', '0~20', '윗꼬리 10% 미만: +10점 · 60% 이상: −8점'],
              ['D. 거래량 건전성', '0~15', '2~5배 증가: +15점 · 10배 이상: −5점'],
              ['E. 매도잔량 소화', '0~10', '매수잔량 압도적: +10점 · 매도 우세: −3점'],
            ] as [name, score, desc]}
              <tr class="hover:bg-gray-700/30">
                <td class="px-3 py-2 font-medium text-gray-200">{name}</td>
                <td class="px-3 py-2 text-center text-gray-400">{score}</td>
                <td class="px-3 py-2 text-gray-400">{desc}</td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>
    </div>

    <!-- 신호 유형 -->
    <div>
      <p class="font-semibold text-white mb-2">🏷️ 신호 유형 분류</p>
      <div class="space-y-2">
        {#each [
          ['강한매수', 'bg-red-600 text-white border-red-700', '체결강도 130+ · 3회 이상 연속 상승 · 윗꼬리 없음 · 매도잔량 소화 중'],
          ['매수우세', 'bg-orange-400 text-white border-orange-500', '기본 상승 패턴. 강한매수 조건 미충족이나 전반적으로 매수세가 우위'],
          ['물량소화', 'bg-yellow-100 text-yellow-700 border-yellow-300', '체결강도는 높은데 가격이 제자리 + 긴 윗꼬리 → 위에서 파는 물량을 받아내는 중'],
          ['추격위험', 'bg-gray-800 text-white border-gray-700', '체결강도 170+ · 거래량 7배 이상 · 긴 윗꼬리 → 고점 물량털기 가능성 경계'],
          ['약한상승', 'bg-gray-700 text-gray-300 border-gray-600', '거래량 증가 없음 · 체결강도 120 미만 → 얇은 호가에서 뜬 상승'],
        ] as [label, cls, desc]}
          <div class="flex items-start gap-3 p-2.5 rounded-lg bg-gray-700/30">
            <span class="border {cls} text-xs px-1.5 py-0.5 rounded font-bold shrink-0 mt-0.5">{label}</span>
            <span class="text-gray-400 text-xs">{desc}</span>
          </div>
        {/each}
      </div>
    </div>

    <!-- 지표 상세 -->
    <div>
      <p class="font-semibold text-white mb-2">🔍 지표 상세</p>
      <div class="space-y-2 text-xs text-gray-400">
        <div class="rounded-lg border border-gray-700 p-3">
          <p class="font-semibold text-gray-200 mb-1">체결강도</p>
          <p>100 = 균형 / 100 초과 = 매수 우위 / 100 미만 = 매도 우위. 10초마다 연속 상승 종목만 표시.</p>
          <div class="flex flex-wrap gap-1.5 mt-1.5">
            <span class="bg-red-900/30 text-red-400 px-2 py-0.5 rounded">150+ 강한 매수세</span>
            <span class="bg-orange-900/30 text-orange-400 px-2 py-0.5 rounded">130~150 매수 우세</span>
            <span class="bg-blue-900/30 text-blue-400 px-2 py-0.5 rounded">100 미만 매도 경향</span>
          </div>
        </div>
        <div class="rounded-lg border border-gray-700 p-3">
          <p class="font-semibold text-gray-200 mb-1">거래량 증가</p>
          <p>직전 6회(1분) 평균 대비 현재 10초 구간 배수. 2~5배가 최적, 10배 이상은 고점 물량털기 가능성.</p>
        </div>
        <div class="rounded-lg border border-gray-700 p-3">
          <p class="font-semibold text-gray-200 mb-1">매도/매수 잔량</p>
          <p>10단계 호가 총잔량 비율. 1 미만 = 매수 우위, 클수록 위에 팔 물량이 많음.</p>
        </div>
        <div class="rounded-lg border border-gray-700 p-3">
          <p class="font-semibold text-gray-200 mb-1">가격 위치</p>
          <p>장중 저가~고가 내 현재가 위치(%). 80%+ = 고가권 강한 매수, 30% 미만 = 저가권.</p>
        </div>
        <div class="rounded-lg border border-gray-700 p-3">
          <p class="font-semibold text-gray-200 mb-1">AI 목표가 / 익일 추세</p>
          <p>현재가·기술 지표·AI 감성을 종합한 추론. 참고용이며 투자 권유가 아닙니다.</p>
        </div>
      </div>
    </div>

    <div class="bg-orange-950/40 rounded-xl p-3 border border-orange-800/40 text-xs text-orange-300">
      💡 <strong>진짜 상승 한 줄 기준</strong><br/>
      가격이 오르면서 · 거래량이 받쳐주고 · 체결강도가 유지되고 · 위 매도물량이 실제로 소화되는 흐름
    </div>

    <div class="bg-gray-700/40 rounded-xl p-3 border border-gray-700 text-xs text-gray-500">
      ⚠️ 모든 지표와 AI 분석은 참고용이며 투자 권유가 아닙니다. 모든 투자 손실의 책임은 투자자 본인에게 있습니다.
    </div>
  </div>
</Modal>
