'use client'

import { useEffect, useMemo, useState } from 'react'
import { createPortal } from 'react-dom'
import { useLocale } from 'next-intl'
import type {
  KolPostSummary, KolPostDetail, KolTicker,
  KolDigest, KolDigestTicker, KolHoldingChange, KolDivergence,
} from '@/types'
import { getKolPosts, getKolPost, getKolDigest, getKolChanges, getKolDivergence } from '@/lib/api'
import { swrFetch } from '@/lib/cache'
import PageHint from '@/components/ui/PageHint'
import Pagination from '@/components/ui/Pagination'

/**
 * KOL feed — independent module. Lists analyzed posts from tracked KOLs
 * (Substack today, Twitter later). Click a row to open the full post body
 * + structured ticker calls inline.
 */

const ACTION_COLOR: Record<KolTicker['action'], string> = {
  buy:      '#16a34a',
  bullish:  '#16a34a',
  sell:     '#dc2626',
  bearish:  '#dc2626',
  reduce:   '#f59e0b',
  mention:  '#9ca3af',
}

const WINDOW_OPTIONS = [1, 7, 30, 90] as const

function actionLabel(action: KolTicker['action'], isZh: boolean) {
  const labels: Record<KolTicker['action'], string> = {
    buy: 'BUY',
    sell: 'SELL',
    reduce: 'Reduce',
    bullish: 'Bullish',
    bearish: 'Bearish',
    mention: 'Mention',
  }
  return labels[action]
}

function windowLabel(days: number, isZh: boolean) {
  if (days === 1) return isZh ? '今日' : 'Today'
  return isZh ? `近 ${days} 日` : `Last ${days}d`
}

function changeLabel(changeType: KolHoldingChange['change_type'], isZh: boolean) {
  const labels: Record<KolHoldingChange['change_type'], string> = {
    new_position: 'New',
    increased: 'Added',
    decreased: 'Reduced',
    closed: 'Closed',
  }
  return labels[changeType]
}

function divergenceMeta(signalType: KolDivergence['signal_type'], isZh: boolean) {
  return signalType === 'divergence'
    ? {
        label: '⚠️ Divergence',
        color: '#f59e0b',
        bg: '#f59e0b22',
        tip: 'Public stance and wallet action disagree. Follow the wallet, not the words.',
      }
    : {
        label: '✅ Alignment',
        color: '#22c55e',
        bg: '#22c55e22',
        tip: 'Public stance and wallet action align, which increases confidence.',
      }
}

function directionLabel(direction: KolDivergence['direction'], isZh: boolean) {
  if (direction === 'long') return 'Long ▲'
  return 'Short ▼'
}

function postActionLabel(action: string, isZh: boolean) {
  const labels: Record<string, string> = {
    buy: 'BUY',
    sell: 'SELL',
    reduce: 'Reducing',
    bullish: 'Bullish post',
    bearish: 'Bearish post',
  }
  return labels[action] ?? action
}

function chainActionLabel(action: string, isZh: boolean) {
  const labels: Record<string, string> = {
    new_position: 'Opened on-chain',
    increased: 'Added on-chain',
    decreased: 'Reduced on-chain',
    closed: 'Closed on-chain',
  }
  return labels[action] ?? action
}

function sourceLabel(source: string, isZh: boolean) {
  if (source === 'substack') return 'Substack'
  if (source === 'podcast') return 'Podcast'
  if (source === 'twitter') return 'X'
  return source
}

function formatShortUsd(value: number) {
  if (value >= 1e6) return `$${(value / 1e6).toFixed(2)}M`
  return `$${(value / 1e3).toFixed(0)}K`
}

function digestSideCopy(side: KolDigestTicker['side']) {
  if (side === 'long') return 'Bullish flow'
  if (side === 'short') return 'Bearish flow'
  return 'Mention flow'
}

function compactChangeCopy(change: KolHoldingChange) {
  const verb = change.change_type === 'new_position'
    ? 'opened'
    : change.change_type === 'increased'
      ? 'added'
      : change.change_type === 'decreased'
        ? 'reduced'
        : 'closed'
  const size = change.usd_after != null && change.usd_after > 0
    ? ` ${formatShortUsd(change.usd_after)}`
    : ''
  const pct = change.pct_change != null
    ? ` (${change.pct_change > 0 ? '+' : ''}${change.pct_change.toFixed(0)}%)`
    : ''
  return `@${change.handle} ${verb}${size}${pct}`
}

function DigestWidget({
  onTickerClick,
  activeTicker,
  isZh,
  initialDigest = null,
}: {
  onTickerClick: (ticker: string) => void
  activeTicker?: string | null
  isZh: boolean
  initialDigest?: KolDigest | null
}) {
  const [days, setDays]   = useState<number>(7)
  const [data, setData]   = useState<KolDigest | null>(initialDigest)
  const [loading, setLoading] = useState(initialDigest === null)
  const [err, setErr]     = useState('')

  useEffect(() => {
    if (initialDigest === null || days !== (initialDigest?.window_days ?? 7)) {
      setLoading(true)
    }
    swrFetch(
      `kol-digest-${days}`,
      15 * 60_000,
      () => getKolDigest(days),
      fresh => setData(fresh),
    )
      .then(d => { setData(d); setErr('') })
      .catch(e => setErr(e instanceof Error ? e.message : (isZh ? '加载失败' : 'Failed to load digest')))
      .finally(() => setLoading(false))
  }, [days, initialDigest, isZh])

  return (
    <div style={{
      marginBottom: 16, padding: 'clamp(12px, 3vw, 18px)',
      borderRadius: 12, background: 'var(--surface)',
      border: '1px solid var(--line)',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between',
        alignItems: 'center', flexWrap: 'wrap', gap: 8, marginBottom: 12,
      }}>
        <div>
          <div style={{ fontSize: 10, color: 'var(--ink-3)',
                        letterSpacing: 1, textTransform: 'uppercase',
                        marginBottom: 2 }}>
            What KOLs are pushing now
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>
            {data
              ? `${data.post_count} posts analysed · ${data.ticker_count} assets with repeat mentions`
              : 'Loading…'}
          </div>
        </div>
        <div className="nav-tabs" style={{ background: 'var(--bg-sunk)' }}>
          {WINDOW_OPTIONS.map(daysOption => (
            <button
              key={daysOption}
              onClick={() => setDays(daysOption)}
              className={`nav-tab ${days === daysOption ? 'active' : ''}`}
              style={{ border: 'none', cursor: 'pointer', fontSize: 12 }}
            >
              {windowLabel(daysOption, isZh)}
            </button>
          ))}
        </div>
      </div>

      {loading && (
        <div style={{ padding: 16, textAlign: 'center', color: 'var(--ink-3)',
                      fontSize: 12 }}>Loading…</div>
      )}
      {err && (
        <div style={{ padding: 12, color: '#dc2626', fontSize: 12 }}>{err}</div>
      )}
      {!loading && !err && data && data.tickers.length === 0 && (
        <div style={{ padding: 16, textAlign: 'center', color: 'var(--ink-3)',
                      fontSize: 13 }}>
          No actionable calls in this window. Try a longer range.
        </div>
      )}
      {!loading && !err && data && data.tickers.length > 0 && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))',
          gap: 10,
        }}>
          {data.tickers.map(t => <DigestTickerChip
            key={t.ticker}
            t={t}
            isZh={isZh}
            active={activeTicker === t.ticker}
            hasActive={!!activeTicker}
            onClick={() => onTickerClick(t.ticker)}
          />)}
        </div>
      )}
    </div>
  )
}

function DigestTickerChip({
  t, onClick, isZh, active, hasActive,
}: { t: KolDigestTicker; onClick: () => void; isZh: boolean; active: boolean; hasActive: boolean }) {
  const sideColor = t.side === 'long' ? '#16a34a'
                  : t.side === 'short' ? '#dc2626' : '#9ca3af'
  const sideLabel = t.side === 'long'
    ? 'Long'
    : t.side === 'short'
      ? 'Short'
      : 'Mention'
  const actionLabel = t.dominant_action === 'buy'  ? 'BUY'
                    : t.dominant_action === 'sell' ? 'SELL'
                    : sideLabel
  return (
    <button
      onClick={onClick}
      title={`${t.kols.map(k => '@' + k).join(', ')} · ${t.post_count} signals`}
      style={{
        display: 'inline-flex', flexDirection: 'column',
        alignItems: 'flex-start', gap: 4,
        padding: '12px 14px', borderRadius: 12,
        background: active ? `${sideColor}12` : hasActive ? 'color-mix(in oklab, var(--bg-sunk) 92%, transparent)' : 'var(--bg-sunk)',
        border: active ? `2px solid ${sideColor}` : `1px solid ${sideColor}55`,
        boxShadow: active ? `0 10px 24px ${sideColor}22` : 'none',
        cursor: 'pointer', textAlign: 'left',
        minHeight: 108,
        width: '100%',
        transform: active ? 'translateY(-2px)' : 'none',
        opacity: hasActive && !active ? 0.6 : 1,
        transition: 'background 120ms, border-color 120ms, box-shadow 120ms, transform 120ms, opacity 120ms',
      }}
      aria-pressed={active}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
        <strong style={{ fontSize: 18, color: 'var(--ink-1)' }}>
          {t.ticker}
        </strong>
        {active && (
          <span style={{
            width: 18,
            height: 18,
            borderRadius: 999,
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            background: sideColor,
            color: '#fff',
            fontSize: 11,
            fontWeight: 800,
          }}>
            ✓
          </span>
        )}
        <span style={{
          fontSize: 10, fontWeight: 700, color: sideColor,
          padding: '2px 6px', borderRadius: 999,
          background: `${sideColor}22`,
        }}>
          {actionLabel}
        </span>
      </div>
      <div style={{ fontSize: 12, color: 'var(--ink-2)', fontWeight: 600 }}>
        {digestSideCopy(t.side)}
      </div>
      <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
        {t.kol_count} KOL · {(t.max_conviction * 100).toFixed(0)}% max conviction
      </div>
      <div style={{
        fontSize: 11, color: 'var(--ink-3)',
        maxWidth: '100%', whiteSpace: 'nowrap',
        overflow: 'hidden', textOverflow: 'ellipsis',
      }}>
        {t.kols.map(k => '@' + k).join(', ')}
      </div>
      {active && (
        <div style={{ fontSize: 11, fontWeight: 700, color: sideColor, marginTop: 2 }}>
          Filtering the page by {t.ticker}
        </div>
      )}
    </button>
  )
}

const CHANGE_COLOR: Record<KolHoldingChange['change_type'], string> = {
  new_position: '#16a34a',
  increased:    '#22c55e',
  decreased:    '#f59e0b',
  closed:       '#dc2626',
}

function WalletCheckWidget({
  isZh,
  dateLocale,
  initialDigest = null,
  initialChanges = null,
  initialItems = null,
  tickerFilter = null,
}: {
  isZh: boolean
  dateLocale: string
  initialDigest?: KolDigest | null
  initialChanges?: KolHoldingChange[] | null
  initialItems?: KolDivergence[] | null
  tickerFilter?: string | null
}) {
  const [digest, setDigest] = useState<KolDigest | null>(initialDigest)
  const [changes, setChanges] = useState<KolHoldingChange[]>(initialChanges ?? [])
  const [items, setItems] = useState<KolDivergence[]>(initialItems ?? [])
  const [loading, setLoading] = useState(
    initialDigest === null || initialChanges === null || initialItems === null,
  )
  const [days, setDays] = useState(7)

  useEffect(() => {
    setLoading(true)
    Promise.all([
      swrFetch(
        `kol-digest-${days}`,
        15 * 60_000,
        () => getKolDigest(days),
        fresh => setDigest(fresh),
      ),
      swrFetch(
        `kol-changes-${days}`,
        30 * 60_000,
        () => getKolChanges({ days }),
        fresh => setChanges(fresh.changes),
      ),
      swrFetch(
        `kol-divergence-all-${days}`,
        30 * 60_000,
        () => getKolDivergence({ days }),
        fresh => setItems(fresh.items),
      ),
    ])
      .then(([nextDigest, nextChanges, nextItems]) => {
        setDigest(nextDigest)
        setChanges(nextChanges.changes)
        setItems(nextItems.items)
      })
      .catch(() => {
        setDigest(null)
        setChanges([])
        setItems([])
      })
      .finally(() => setLoading(false))
  }, [days])

  const rows = useMemo(() => {
    const sourceTickers = digest?.tickers ?? []
    const filteredTickers = tickerFilter
      ? sourceTickers.filter(t => t.ticker === tickerFilter)
      : sourceTickers

    return filteredTickers.map(t => {
      const relatedChanges = changes
        .filter(c => c.ticker === t.ticker)
        .sort((a, b) => +new Date(b.detected_at) - +new Date(a.detected_at))
      const relatedItems = items
        .filter(i => i.ticker === t.ticker)
        .sort((a, b) => +new Date(b.onchain_at) - +new Date(a.onchain_at))
      const divergenceCount = relatedItems.filter(i => i.signal_type === 'divergence').length
      const alignmentCount = relatedItems.filter(i => i.signal_type === 'alignment').length
      const latestChange = relatedChanges[0] ?? null
      const latestMatch = relatedItems[0] ?? null

      const verdict =
        divergenceCount > 0 && alignmentCount === 0
          ? {
              label: 'Mismatch',
              color: '#f59e0b',
              bg: '#f59e0b22',
              note: 'Wallet action disagrees with the public pitch.',
            }
          : alignmentCount > 0 && divergenceCount === 0
            ? {
                label: 'Aligned',
                color: '#22c55e',
                bg: '#22c55e22',
                note: 'Wallet action supports the public pitch.',
              }
            : alignmentCount > 0 && divergenceCount > 0
              ? {
                  label: 'Mixed',
                  color: '#a855f7',
                  bg: '#a855f722',
                  note: 'Different KOLs or time windows point in both directions.',
                }
              : latestChange
                ? {
                    label: 'Watch',
                    color: CHANGE_COLOR[latestChange.change_type],
                    bg: `${CHANGE_COLOR[latestChange.change_type]}22`,
                    note: 'Wallet movement exists, but no clean talk-vs-wallet match yet.',
                  }
                : {
                    label: 'No wallet proof',
                    color: '#9ca3af',
                    bg: '#9ca3af22',
                    note: 'No tracked wallet move linked to this asset in the selected window.',
                  }

      return {
        ticker: t.ticker,
        talkLine: `${t.kol_count} KOLs pushing ${t.side === 'short' ? 'bearish' : t.side === 'long' ? 'bullish' : 'mixed'} flow`,
        speakers: t.kols.map(k => '@' + k).join(', '),
        conviction: `${(t.max_conviction * 100).toFixed(0)}% max conviction`,
        verdict,
        divergenceCount,
        alignmentCount,
        latestChange,
        latestMatch,
      }
    })
  }, [changes, digest, items, tickerFilter])

  const totalMismatch = rows.filter(r => r.verdict.label === 'Mismatch').length
  const totalAligned = rows.filter(r => r.verdict.label === 'Aligned').length

  return (
    <div style={{
      marginBottom: 16, padding: 'clamp(12px, 3vw, 18px)',
      borderRadius: 12, background: 'var(--surface)',
      border: '1px solid var(--line)',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between',
        alignItems: 'flex-start', flexWrap: 'wrap', gap: 8, marginBottom: 12,
      }}>
        <div>
          <div style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: 1,
                        textTransform: 'uppercase', marginBottom: 2 }}>
            Talks vs wallets
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>
            {loading
              ? 'Loading…'
              : rows.length === 0
                ? 'No overlapping talk and wallet evidence in this window.'
                : `${totalAligned} aligned · ${totalMismatch} mismatched across the assets KOLs are pushing`}
          </div>
        </div>
        <div className="nav-tabs" style={{ background: 'var(--bg-sunk)' }}>
          {([1, 7, 30] as const).map(d => (
            <button
              key={d}
              onClick={() => setDays(d)}
              className={`nav-tab ${days === d ? 'active' : ''}`}
              style={{ border: 'none', cursor: 'pointer', fontSize: 12 }}
            >
              {windowLabel(d, isZh)}
            </button>
          ))}
        </div>
      </div>

      {!loading && rows.length === 0 && (
        <div style={{
          padding: '12px 16px', borderRadius: 8, background: 'var(--bg-sunk)',
          fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.6,
        }}>
          This panel only answers one question: when KOLs talk about an asset, do tracked wallets confirm it?
          If there is no match yet, the asset stays in watch mode until wallet evidence appears.
        </div>
      )}

      {!loading && rows.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {rows.map(row => (
            <div key={row.ticker} style={{
              display: 'grid',
              gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1.4fr) auto',
              gap: 12,
              alignItems: 'start',
              padding: '14px 16px',
              borderRadius: 12,
              background: 'var(--bg-sunk)',
              border: '1px solid var(--line)',
            }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
                  <strong style={{ fontSize: 18 }}>{row.ticker}</strong>
                  <span style={{
                    fontSize: 10, fontWeight: 700, color: row.verdict.color,
                    padding: '3px 8px', borderRadius: 999, background: row.verdict.bg,
                  }}>
                    {row.verdict.label}
                  </span>
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-1)', fontWeight: 600, marginBottom: 4 }}>
                  {row.talkLine}
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {row.speakers}
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>
                  {row.conviction}
                </div>
              </div>

              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 5 }}>
                  Wallet evidence
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-1)', fontWeight: 600, marginBottom: 4 }}>
                  {row.latestMatch
                    ? `@${row.latestMatch.handle} ${chainActionLabel(row.latestMatch.onchain_action, isZh).toLowerCase()}`
                    : row.latestChange
                      ? compactChangeCopy(row.latestChange)
                      : 'No tracked move yet'}
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>
                  {row.latestMatch
                    ? `${row.verdict.note} ${row.latestMatch.usd_after ? `Size ${formatShortUsd(row.latestMatch.usd_after)}.` : ''}`
                    : row.verdict.note}
                </div>
                {(row.divergenceCount > 0 || row.alignmentCount > 0) && (
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 6 }}>
                    {row.alignmentCount > 0 && (
                      <span style={{ fontSize: 11, color: '#22c55e' }}>
                        {row.alignmentCount} alignment
                      </span>
                    )}
                    {row.divergenceCount > 0 && (
                      <span style={{ fontSize: 11, color: '#f59e0b' }}>
                        {row.divergenceCount} divergence
                      </span>
                    )}
                  </div>
                )}
              </div>

              <div style={{ fontSize: 11, color: 'var(--ink-3)', textAlign: 'right', whiteSpace: 'nowrap' }}>
                {row.latestMatch
                  ? new Date(row.latestMatch.onchain_at).toLocaleDateString(dateLocale)
                  : row.latestChange
                    ? new Date(row.latestChange.detected_at).toLocaleDateString(dateLocale)
                    : 'No date'}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

function TickerChips({ tickers, isZh }: { tickers: KolTicker[]; isZh: boolean }) {
  if (!tickers.length) {
    return <span style={{ color: 'var(--ink-3)', fontSize: 12 }}>—</span>
  }
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
      {tickers.map((t, i) => (
        <span
          key={`${t.ticker}-${i}`}
          title={t.quote}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            padding: '2px 8px', borderRadius: 999,
            fontSize: 11, fontWeight: 600,
            background: 'var(--bg-sunk)',
            border: `1px solid ${ACTION_COLOR[t.action]}33`,
            color: ACTION_COLOR[t.action],
          }}
        >
          {t.ticker}
          <span style={{ opacity: 0.7, fontWeight: 500 }}>
            {actionLabel(t.action, isZh)}
          </span>
          <span style={{ opacity: 0.55, fontWeight: 500 }}>
            {(t.conviction * 100).toFixed(0)}
          </span>
        </span>
      ))}
    </div>
  )
}

function PostDetail({
  post, onClose, isZh, dateLocale,
}: { post: KolPostDetail; onClose: () => void; isZh: boolean; dateLocale: string }) {
  // Lock body scroll while open
  useEffect(() => {
    const prev = document.body.style.overflow
    document.body.style.overflow = 'hidden'
    return () => { document.body.style.overflow = prev }
  }, [])

  const postSourceLabel = sourceLabel(post.source, isZh)

  const node = (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0,
        background: 'rgba(0,0,0,0.82)',
        backdropFilter: 'blur(4px)',
        WebkitBackdropFilter: 'blur(4px)',
        zIndex: 9999, display: 'flex', alignItems: 'flex-start',
        justifyContent: 'center',
        padding: 'clamp(8px, 4vw, 40px) clamp(8px, 3vw, 20px)',
        overflowY: 'auto',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          background: 'var(--bg)', borderRadius: 14,
          maxWidth: 820, width: '100%',
          padding: 'clamp(16px, 4vw, 28px)',
          border: '1px solid var(--line)',
          boxShadow: '0 24px 80px rgba(0,0,0,0.6)',
        }}
      >
        {/* ── Header: 标题 + 关闭 + 查看原帖 ── */}
        <div style={{
          display: 'flex', justifyContent: 'space-between',
          alignItems: 'flex-start', gap: 12, marginBottom: 12,
        }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 6 }}>
              @{post.kol_handle} · {postSourceLabel} · {new Date(post.published_at).toLocaleString(dateLocale)}
            </div>
            <h2 style={{
              margin: 0, fontSize: 'clamp(16px, 4.5vw, 22px)',
              lineHeight: 1.3, wordBreak: 'break-word',
            }}>
              {post.title || (isZh ? '(无标题)' : '(Untitled)')}
            </h2>
          </div>

          {/* 右上角按钮组 */}
          <div style={{ display: 'flex', gap: 8, flexShrink: 0, alignItems: 'center' }}>
            {post.url && (
              <a
                href={post.url}
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  padding: '5px 12px', borderRadius: 6,
                  background: 'var(--amber)', color: '#000',
                  fontSize: 12, fontWeight: 700, textDecoration: 'none',
                  whiteSpace: 'nowrap',
                }}
              >
                {isZh ? `查看原帖 ${postSourceLabel}` : `Open original ${postSourceLabel}`} ↗
              </a>
            )}
            <button
              onClick={onClose}
              aria-label="Close"
              style={{
                background: 'var(--bg-sunk)', border: '1px solid var(--line)',
                borderRadius: 6, padding: '5px 10px', cursor: 'pointer',
                color: 'var(--ink-2)', fontSize: 14, lineHeight: 1,
              }}
            >✕</button>
          </div>
        </div>

        {/* ── AI 摘要 ── */}
        {post.summary && (
          <div style={{
            margin: '12px 0', padding: 12, borderRadius: 8,
            background: 'var(--bg-sunk)', borderLeft: '3px solid var(--amber)',
            fontSize: 14, lineHeight: 1.6,
          }}>
            <div style={{ fontSize: 10, color: 'var(--ink-3)', marginBottom: 4,
                          letterSpacing: 1, textTransform: 'uppercase' }}>
              {isZh ? 'AI 摘要' : 'AI summary'}
            </div>
            {post.summary}
          </div>
        )}

        {/* ── 喊单标的 ── */}
        {post.tickers.length > 0 && (
          <div style={{ margin: '12px 0' }}>
            <div style={{ fontSize: 10, color: 'var(--ink-3)', marginBottom: 6,
                          letterSpacing: 1, textTransform: 'uppercase' }}>
              {isZh ? '提取标的' : 'Extracted assets'}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {post.tickers.map((t, i) => (
                <div key={i} style={{
                  padding: 10, borderRadius: 8,
                  background: 'var(--bg-sunk)',
                  borderLeft: `3px solid ${ACTION_COLOR[t.action]}`,
                }}>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
                    <strong style={{ fontSize: 14 }}>{t.ticker}</strong>
                    <span style={{ color: ACTION_COLOR[t.action], fontSize: 12, fontWeight: 600 }}>
                      {actionLabel(t.action, isZh)}
                    </span>
                    <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                      {isZh ? '信心分' : 'Conviction'} {(t.conviction * 100).toFixed(0)}%
                    </span>
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-2)',
                                fontStyle: 'italic', lineHeight: 1.5 }}>
                    &ldquo;{t.quote}&rdquo;
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ── 原文 ── */}
        <div style={{
          marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--line)',
        }}>
          <div style={{ fontSize: 10, color: 'var(--ink-3)', marginBottom: 8,
                        letterSpacing: 1, textTransform: 'uppercase' }}>
            {isZh ? '原文摘录' : 'Source excerpt'}
          </div>
          <div style={{
            whiteSpace: 'pre-wrap', fontSize: 13, lineHeight: 1.7,
            color: 'var(--ink-2)', maxHeight: '40vh', overflowY: 'auto',
            padding: 12, borderRadius: 8, background: 'var(--bg-sunk)',
            wordBreak: 'break-word',
          }}>
            {post.raw_text}
          </div>
        </div>
      </div>
    </div>
  )

  if (typeof document === 'undefined') return null
  return createPortal(node, document.body)
}

interface KolPageProps {
  initialPosts?: KolPostSummary[] | null
  initialDigest?: KolDigest | null
  initialChanges?: KolHoldingChange[] | null
  initialDivergence?: KolDivergence[] | null
}

export default function KolPage({
  initialPosts = null,
  initialDigest = null,
  initialChanges = null,
  initialDivergence = null,
}: KolPageProps) {
  const locale = useLocale()
  const isZh = false  // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json
  const dateLocale = isZh ? 'zh-CN' : 'en-US'
  const KOL_PAGE_SIZE = 20
  const [posts,   setPosts]   = useState<KolPostSummary[]>(initialPosts ?? [])
  const [loading, setLoading] = useState(initialPosts === null)
  const [err,     setErr]     = useState('')
  const [openPost, setOpenPost] = useState<KolPostDetail | null>(null)
  const [handleFilter, setHandleFilter] = useState<string>('all')
  const [tickerFilter, setTickerFilter] = useState<string | null>(null)
  const [kolPage, setKolPage] = useState(1)

  useEffect(() => {
    swrFetch(
      'kol-posts-100',
      15 * 60_000, // 15 min TTL — KOL feed is ingested daily
      () => getKolPosts({ limit: 100 }),
      fresh => setPosts(fresh.items),
    )
      .then(r => { setPosts(r.items); setErr('') })
      .catch(e => setErr(e instanceof Error ? e.message : (isZh ? '加载失败' : 'Failed to load posts')))
      .finally(() => setLoading(false))
  }, [isZh])

  const handles = useMemo(() => {
    const set = new Set(posts.map(p => p.kol_handle))
    return ['all', ...Array.from(set)]
  }, [posts])

  const filtered = useMemo(() => {
    let out = handleFilter === 'all' ? posts : posts.filter(p => p.kol_handle === handleFilter)
    if (tickerFilter) {
      out = out.filter(p => p.tickers.some(t => t.ticker === tickerFilter))
    }
    return out
  }, [posts, handleFilter, tickerFilter])

  const kolTotalPages = Math.max(1, Math.ceil(filtered.length / KOL_PAGE_SIZE))
  const kolSafePage   = Math.min(kolPage, kolTotalPages)
  const kolPageItems  = filtered.slice((kolSafePage - 1) * KOL_PAGE_SIZE, kolSafePage * KOL_PAGE_SIZE)

  async function openDetail(id: number) {
    try {
      const detail = await getKolPost(id)
      setOpenPost(detail)
    } catch (e) {
      setErr(e instanceof Error ? e.message : (isZh ? '详情加载失败' : 'Failed to load detail'))
    }
  }

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">{isZh ? 'KOL 信号' : 'KOL Signals'}</h1>
          <PageHint count={`${posts.length} posts`}>
            This page answers two questions only: which assets KOLs are pushing now,
            and whether tracked wallets confirm or contradict that public stance.
          </PageHint>
        </div>
      </div>

      <DigestWidget
        isZh={isZh}
        initialDigest={initialDigest}
        activeTicker={tickerFilter}
        onTickerClick={(sym) => {
          setTickerFilter(prev => prev === sym ? null : sym)
          setKolPage(1)
        }}
      />

      <WalletCheckWidget
        isZh={isZh}
        dateLocale={dateLocale}
        initialDigest={initialDigest}
        initialChanges={initialChanges}
        initialItems={initialDivergence}
        tickerFilter={tickerFilter}
      />

      {tickerFilter && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          marginBottom: 12, fontSize: 12,
        }}>
          <span style={{ color: 'var(--ink-3)' }}>{isZh ? '当前筛选标的：' : 'Filtered asset:'}</span>
          <strong>{tickerFilter}</strong>
          <button
            onClick={() => { setTickerFilter(null); setKolPage(1) }}
            style={{
              background: 'var(--bg-sunk)', border: '1px solid var(--line)',
              borderRadius: 4, padding: '2px 8px',
              cursor: 'pointer', fontSize: 11, color: 'var(--ink-2)',
            }}
          >{isZh ? '清除 ✕' : 'Clear ✕'}</button>
        </div>
      )}

      {handles.length > 2 && (
        <div className="nav-tabs" style={{ background: 'var(--bg-sunk)', marginBottom: 12 }}>
          {handles.map(h => (
            <button
              key={h}
              onClick={() => { setHandleFilter(h); setKolPage(1) }}
              className={`nav-tab ${handleFilter === h ? 'active' : ''}`}
              style={{ border: 'none', cursor: 'pointer' }}
            >
              {h === 'all' ? (isZh ? `全部 (${posts.length})` : `All (${posts.length})`) : `@${h}`}
            </button>
          ))}
        </div>
      )}

      {loading && <KolPostsSkeleton />}
      {err && <div style={{ padding: 20, color: '#dc2626' }}>{isZh ? `错误：${err}` : `Error: ${err}`}</div>}

      {!loading && !err && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {filtered.length === 0 && (
            <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)' }}>
              {isZh
                ? '当前没有数据，等待下一轮抓取任务（每天 01:15 UTC）。'
                : 'No data yet. Wait for the next feed ingestion run (daily 01:15 UTC).'}
            </div>
          )}
          {kolPageItems.map(p => (
            <div
              key={p.id}
              onClick={() => openDetail(p.id)}
              style={{
                padding: 14, borderRadius: 10,
                background: 'var(--surface)',
                border: '1px solid var(--line)',
                cursor: 'pointer',
                transition: 'border-color 0.15s',
              }}
              onMouseEnter={e => (e.currentTarget.style.borderColor = 'var(--amber)')}
              onMouseLeave={e => (e.currentTarget.style.borderColor = 'var(--line)')}
            >
              {/* 顶部：作者 + 右侧操作区 */}
              <div style={{ display: 'flex', justifyContent: 'space-between',
                            alignItems: 'center', gap: 8, marginBottom: 6,
                            flexWrap: 'wrap' }}>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                  @{p.kol_handle} · {sourceLabel(p.source, isZh)} · {new Date(p.published_at).toLocaleDateString(dateLocale)}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
                  <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                    {p.analyzed_at
                      ? (isZh ? '✓ 已分析' : '✓ Analyzed')
                      : (isZh ? '⏳ 待分析' : '⏳ Pending')}
                  </span>
                  {p.url && (
                    <a
                      href={p.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      onClick={e => e.stopPropagation()}
                      style={{
                        fontSize: 11, fontWeight: 600,
                        color: 'var(--amber)', textDecoration: 'none',
                        padding: '2px 8px', borderRadius: 4,
                        border: '1px solid color-mix(in srgb, var(--amber) 35%, transparent)',
                        whiteSpace: 'nowrap',
                      }}
                    >
                      {isZh ? '原帖 ↗' : 'Source ↗'}
                    </a>
                  )}
                </div>
              </div>
              <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 6,
                            wordBreak: 'break-word' }}>
                {p.title || (isZh ? '(无标题)' : '(Untitled)')}
              </div>
              {p.summary && (
                <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5,
                              marginBottom: 8 }}>
                  {p.summary}
                </div>
              )}
              <TickerChips tickers={p.tickers} isZh={isZh} />
            </div>
          ))}

          <Pagination
            page={kolSafePage}
            total={kolTotalPages}
            count={filtered.length}
            pageSize={KOL_PAGE_SIZE}
            onChange={setKolPage}
            scrollTop={false}
          />
        </div>
      )}

      {openPost && <PostDetail post={openPost} onClose={() => setOpenPost(null)} isZh={isZh} dateLocale={dateLocale} />}
    </div>
  )
}

function KolPostsSkeleton() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 8 }}>
      {Array.from({ length: 5 }).map((_, i) => (
        <div key={i} className="skeleton-card">
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div className="skeleton sk-line-sm" style={{ width: 160 }} />
            <div className="skeleton sk-line-sm" style={{ width: 56 }} />
          </div>
          <div className="skeleton sk-title sk-w-3q" />
          <div className="skeleton sk-line sk-w-full" />
          <div className="skeleton sk-line" style={{ width: '85%' }} />
          <div style={{ display: 'flex', gap: 6, marginTop: 2 }}>
            <div className="skeleton sk-line-sm" style={{ width: 48 }} />
            <div className="skeleton sk-line-sm" style={{ width: 48 }} />
          </div>
        </div>
      ))}
    </div>
  )
}
