// AI 推薦 + 每日股票整理頁
// 接線：live.picks.main_zone + small_zone；live.history（歷史命中）；live.themes（題材精選）
(function(){
const T = window.STOCK_TOKENS;

// ── DataMode 標示 ────────────────────────────────────────────────────────────
function DataModeBadge() {
  const live = window.STOCK_DATA_LIVE;
  const isLive = live.loaded && live.picks;
  const dateStr = live.manifest && live.manifest.generated_at
    ? live.manifest.generated_at.slice(0, 10) : '';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4,
      fontSize: 10, color: T.text3, fontFamily: T.fontMono }}>
      <span style={{
        display: 'inline-block', width: 6, height: 6, borderRadius: 3,
        background: isLive ? 'oklch(0.7 0.15 155)' : 'oklch(0.7 0 0)',
      }} />
      {isLive ? ('LIVE ' + dateStr) : 'DEMO'}
    </div>
  );
}

// ── 將 live pick 物件轉換成與原 mock 相同結構 ─────────────────────────────
function livePickToRow(pk, idx) {
  const score = (pk.score || 0) * 10;  // pipeline score 0-10 → 顯示 0-100
  const tag = score >= 80 ? '強烈買進'
    : score >= 70 ? '買進'
    : score >= 60 ? '加碼'
    : score >= 50 ? '觀察'
    : '中性';
  const tagColor = score >= 70 ? T.up : score >= 50 ? T.warn : T.text3;
  return {
    c: pk.code,
    n: pk.name,
    score: score,
    p: pk.current_price,
    chg: pk.change_pct,
    tag,
    tagColor,
    reasons: (pk.key_reasons && pk.key_reasons.length)
      ? pk.key_reasons
      : (pk.momentum_reasons && pk.momentum_reasons.length)
        ? pk.momentum_reasons
        : (pk.llm_card && pk.llm_card.fallback ? [pk.llm_card.fallback] : ['—']),
    risk: pk.warnings && pk.warnings.length ? pk.warnings.join('；') : '—',
    target: null,   // pipeline 尚未給 target
    stop: null,     // pipeline 尚未給 stop
  };
}

function PicksPage() {
  const [tab, setTab] = React.useState('picks');
  const vp = window.useViewport();
  const live = window.STOCK_DATA_LIVE;
  const livePicks = (live.loaded && live.picks) ? live.picks : null;

  // ── summary 數字 ──────────────────────────────────────────────────────────
  const summary = livePicks ? livePicks.summary : null;
  const pickDate = livePicks ? livePicks.date : null;
  const totalCount = summary ? (summary.main_picks + summary.small_picks) : 0;
  const scanned = summary ? (summary.scanned || 0) : 0;

  // ── picks 陣列（用於 PicksList）──────────────────────────────────────────
  const picks = livePicks
    ? [
        ...(livePicks.main_zone || []),
        ...(livePicks.small_zone || []),
      ].map(livePickToRow)
    : [];

  const pad = vp.isMobile ? 12 : 24;

  return (
    <div style={{ padding: pad, display: 'flex', flexDirection: 'column', gap: vp.isMobile ? 12 : 16 }}>
      {/* Hero */}
      <div style={{
        background: 'linear-gradient(135deg, ' + T.aiSoft + ', oklch(0.97 0.018 290))',
        border: '1px solid ' + T.aiBorder, borderRadius: 14, padding: vp.isMobile ? 14 : 20,
        display: 'flex', gap: 20, alignItems: 'center',
      }}>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8, flexWrap: 'wrap' }}>
            <window.AIBadge size="md" />
            <span style={{ fontSize: 13, fontWeight: 600, color: T.ai }}>每日 AI 精選</span>
            {pickDate && (
              <span style={{ fontSize: 11, color: T.text3, fontFamily: T.fontMono }}>
                {pickDate.replace ? pickDate.replace(/-/g, '/') : pickDate} · 08:00 生成
              </span>
            )}
            <div style={{ marginLeft: 'auto' }}><DataModeBadge /></div>
          </div>
          {livePicks ? (
            <div style={{ fontSize: vp.isMobile ? 17 : 22, fontWeight: 700, color: T.text, letterSpacing: -0.5, marginBottom: 6 }}>
              從 <span style={{ fontFamily: T.fontMono }}>{window.fmt(scanned)}</span> 檔台股中，AI 為你篩選出{' '}
              <span style={{ color: T.ai }}>{totalCount} 檔</span> 今日重點
            </div>
          ) : (
            <div style={{ fontSize: vp.isMobile ? 17 : 22, fontWeight: 700, color: T.text, letterSpacing: -0.5, marginBottom: 6 }}>
              每日 AI 精選 · 待生成
            </div>
          )}
          {!vp.isMobile && (
            <div style={{ fontSize: 12, color: T.text2, lineHeight: 1.55 }}>
              根據你的偏好（短線、AI 題材、技術面），結合法人籌碼、新聞情緒、基本面動能綜合評分。每日 08:00 重新計算。
            </div>
          )}
        </div>
      </div>

      {/* 分頁 tab（mobile 可橫向滑動）*/}
      <div style={{
        display: 'flex', gap: 0,
        borderBottom: '1px solid ' + T.border,
        overflowX: 'auto', scrollbarWidth: 'none',
        WebkitOverflowScrolling: 'touch',
      }}>
        {[
          { k: 'picks', l: 'AI 選股 ' + totalCount + ' 檔' },
          { k: 'morning', l: '盤前晨報' },
          { k: 'theme', l: '題材精選' },
          { k: 'unusual', l: '異常偵測' },
          { k: 'history', l: '歷史命中' },
        ].map(t => (
          <button key={t.k} onClick={() => setTab(t.k)} style={{
            padding: vp.isMobile ? '10px 12px' : '10px 14px',
            fontSize: vp.isMobile ? 12 : 13,
            fontWeight: tab === t.k ? 600 : 500,
            background: 'none', border: 'none', cursor: 'pointer',
            color: tab === t.k ? T.text : T.text3,
            borderBottom: tab === t.k ? '2px solid ' + T.text : '2px solid transparent',
            marginBottom: -1, fontFamily: T.fontSans,
            whiteSpace: 'nowrap', flexShrink: 0,
          }}>{t.l}</button>
        ))}
      </div>

      {tab === 'picks' && <PicksList picks={picks} vp={vp} />}
      {tab === 'morning' && <MorningBrief />}
      {tab === 'theme' && <ThemePicks vp={vp} />}
      {tab === 'unusual' && <UnusualDetect />}
      {tab === 'history' && <HitHistory vp={vp} />}
    </div>
  );
}
window.PicksPage = PicksPage;

function PicksList({ picks, vp }) {
  const [expanded, setExpanded] = React.useState(0);

  if (!picks || picks.length === 0) {
    return (
      <window.EmptyState
        title="今日無推薦"
        hint="明天 08:00（台灣）pipeline 自動更新"
      />
    );
  }

  // mobile 卡片模式
  if (vp && vp.isMobile) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {picks.map((p, i) => {
          const scoreColor = p.score >= 85 ? T.up : p.score >= 70 ? T.warn : T.text3;
          return (
            <div key={p.c + i} style={{
              background: T.surface, border: '1px solid ' + T.border,
              borderRadius: T.radius, padding: 14,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <span style={{ fontFamily: T.fontMono, fontSize: 22, fontWeight: 700, color: scoreColor, letterSpacing: -0.5 }}>{p.score}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: T.fontMono, fontSize: 10, color: T.text3 }}>{p.c}</div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: T.text }}>{p.n}</div>
                </div>
                <span style={{ fontSize: 11, fontWeight: 700, color: p.tagColor,
                  background: p.tagColor === T.up ? T.upSoft : p.tagColor === T.down ? T.downSoft :
                    p.tagColor === T.warn ? T.warnSoft : T.hover,
                  padding: '4px 8px', borderRadius: 3 }}>{p.tag}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                <div style={{ fontFamily: T.fontMono, fontSize: 14, fontWeight: 600, color: T.text }}>
                  {p.p != null ? window.fmt(p.p, p.p < 100 ? 2 : 1) : '—'}
                </div>
                {p.chg != null && <window.ChangeChip value={p.chg} />}
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                {p.reasons.slice(0, 2).map((r, ri) => (
                  <span key={ri} style={{ fontSize: 11, color: T.text2, background: T.surface2,
                    padding: '3px 7px', borderRadius: 3, lineHeight: 1.4 }}>{r}</span>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  return (
    <window.Card padding={0}>
      <div style={{ display: 'grid', gridTemplateColumns: '60px 100px 1fr 120px 120px 80px',
        padding: '10px 20px', fontSize: 10, color: T.text3, fontWeight: 500,
        letterSpacing: 0.3, textTransform: 'uppercase',
        borderBottom: '1px solid ' + T.border, background: T.surface2 }}>
        <div>分數</div>
        <div>標的</div>
        <div>AI 推薦理由</div>
        <div style={{ textAlign: 'right' }}>現價 / 漲跌</div>
        <div style={{ textAlign: 'right' }}>目標 / 停損</div>
        <div style={{ textAlign: 'right' }}>動作</div>
      </div>
      {picks.map((p, i) => (
        <PickRow key={p.c + i} p={p} expanded={expanded === i}
          onClick={() => setExpanded(expanded === i ? -1 : i)}
          last={i === picks.length - 1} />
      ))}
    </window.Card>
  );
}

function PickRow({ p, expanded, onClick, last }) {
  const scoreColor = p.score >= 85 ? T.up : p.score >= 70 ? T.warn : T.text3;
  return (
    <div style={{ borderBottom: last && !expanded ? 'none' : '1px solid ' + T.border }}>
      <div onClick={onClick} style={{
        display: 'grid', gridTemplateColumns: '60px 100px 1fr 120px 120px 80px', gap: 12,
        padding: '14px 20px', cursor: 'pointer', alignItems: 'center',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontFamily: T.fontMono, fontSize: 18, fontWeight: 700, color: scoreColor,
            letterSpacing: -0.5 }}>{p.score}</span>
        </div>
        <div>
          <div style={{ fontFamily: T.fontMono, fontSize: 10, color: T.text3 }}>{p.c}</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: T.text }}>{p.n}</div>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {p.reasons.slice(0, 2).map((r, i) => (
            <span key={i} style={{ fontSize: 11, color: T.text2, background: T.surface2,
              padding: '3px 7px', borderRadius: 3, lineHeight: 1.4 }}>{r}</span>
          ))}
          {p.reasons.length > 2 && (
            <span style={{ fontSize: 10, color: T.text3, padding: '3px 0' }}>+{p.reasons.length - 2}</span>
          )}
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: T.fontMono, fontSize: 13, fontWeight: 600, color: T.text }}>
            {p.p != null ? window.fmt(p.p, p.p < 100 ? 2 : 1) : '—'}
          </div>
          {p.chg != null && <window.ChangeChip value={p.chg} />}
        </div>
        <div style={{ textAlign: 'right', fontFamily: T.fontMono, fontSize: 11 }}>
          {p.target ? <div style={{ color: T.up }}>↑ {p.target}</div> : <div style={{ color: T.text3 }}>—</div>}
          {p.stop  ? <div style={{ color: T.down }}>↓ {p.stop}</div>  : <div style={{ color: T.text3 }}>—</div>}
        </div>
        <div style={{ textAlign: 'right' }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: p.tagColor,
            background: p.tagColor === T.up ? T.upSoft : p.tagColor === T.down ? T.downSoft :
              p.tagColor === T.warn ? T.warnSoft : T.hover,
            padding: '4px 8px', borderRadius: 3 }}>{p.tag}</span>
        </div>
      </div>
      {expanded && (
        <div style={{ padding: '0 20px 16px 80px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <div>
            <div style={{ fontSize: 10, color: T.text3, fontWeight: 600, letterSpacing: 0.3,
              textTransform: 'uppercase', marginBottom: 8 }}>● AI 完整論點</div>
            {p.reasons.map((r, i) => (
              <div key={i} style={{ display: 'flex', gap: 8, marginBottom: 6, fontSize: 12, color: T.text2, lineHeight: 1.5 }}>
                <span style={{ color: T.up, fontWeight: 700 }}>+</span>
                <span>{r}</span>
              </div>
            ))}
          </div>
          <div>
            <div style={{ fontSize: 10, color: T.text3, fontWeight: 600, letterSpacing: 0.3,
              textTransform: 'uppercase', marginBottom: 8 }}>● 風險提醒</div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 6, fontSize: 12, color: T.text2, lineHeight: 1.5 }}>
              <span style={{ color: T.warn, fontWeight: 700 }}>!</span>
              <span>{p.risk}</span>
            </div>
            <div style={{ marginTop: 12 }}>
              <window.Sparkline data={window.genSeries(30, p.c.charCodeAt(0), p.chg > 0 ? 0.005 : -0.002)} w={300} h={50} fill strokeWidth={1.8} />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function MorningBrief() {
  return (
    <window.EmptyState
      title="今日無推薦"
      hint="明天 08:00（台灣）pipeline 自動更新"
    />
  );
}

function Gauge({ label, value, max, color, sub }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 4 }}>
        <span style={{ color: T.text2, fontWeight: 500 }}>{label}</span>
        <span style={{ fontFamily: T.fontMono, color, fontWeight: 600 }}>{value} · {sub}</span>
      </div>
      <div style={{ height: 5, background: T.hover, borderRadius: 3, overflow: 'hidden' }}>
        <div style={{ width: ((value / max) * 100) + '%', height: '100%', background: color }} />
      </div>
    </div>
  );
}

function ThemePicks({ vp }) {
  const live = window.STOCK_DATA_LIVE;
  // 優先用 live.themes
  const themeData = (live.loaded && live.themes && live.themes.themes)
    ? live.themes.themes.map(th => ({
        name: th.name,
        conf: th.heat * 10,
        picks: th.stocks ? th.stocks.slice(0, 4) : [],
        why: th.trigger || '—',
      }))
    : [];

  if (themeData.length === 0) {
    return (
      <window.EmptyState
        title="題材資料尚未更新"
        hint="明天 08:00 自動更新"
      />
    );
  }

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: (vp && vp.isMobile) ? '1fr' : 'repeat(2, 1fr)',
      gap: 12,
    }}>
      {themeData.map(th => (
        <div key={th.name} style={{
          background: T.surface, border: '1px solid ' + T.border, borderRadius: 8, padding: 16,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: T.text }}>{th.name}</span>
            <div style={{ flex: 1 }} />
            <window.AIBadge label="AI" />
            <span style={{ fontFamily: T.fontMono, fontSize: 13, fontWeight: 700, color: T.ai }}>{th.conf}</span>
          </div>
          <div style={{ height: 4, background: T.hover, borderRadius: 2, marginBottom: 10 }}>
            <div style={{ width: th.conf + '%', height: '100%', background: T.ai, borderRadius: 2 }} />
          </div>
          <div style={{ fontSize: 12, color: T.text2, lineHeight: 1.5, marginBottom: 10 }}>{th.why}</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
            {th.picks.map(p => (
              <span key={p} style={{ fontSize: 11, fontWeight: 500, color: T.primary,
                background: T.primarySoft, padding: '3px 8px', borderRadius: 3 }}>{p}</span>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function UnusualDetect() {
  return (
    <window.EmptyState
      title="今日無推薦"
      hint="明天 08:00（台灣）pipeline 自動更新"
    />
  );
}

function HitHistory({ vp }) {
  const live = window.STOCK_DATA_LIVE;

  // 優先用 live.history
  const histRecs = (live.loaded && live.history && live.history.recommendations)
    ? live.history.recommendations
    : null;

  const stats = [
    { period: '近 7 日', total: 0, hit: 0, rate: 0 },
    { period: '近 30 日', total: 0, hit: 0, rate: 0 },
    { period: '近 90 日', total: 0, hit: 0, rate: 0 },
    { period: '今年迄今', total: 0, hit: 0, rate: 0 },
  ];

  if (!histRecs || histRecs.length === 0) {
    return (
      <window.EmptyState
        title="今日無推薦"
        hint="明天 08:00（台灣）pipeline 自動更新"
      />
    );
  }

  // 從 history 轉換為列表格式
  const recent = histRecs.slice(0, 6).map(r => ({
    d: r.date ? r.date.slice(5).replace('-', '/') : '—',
    c: r.code,
    n: r.name,
    call: r.decision || '—',
    entry: r.entry_price || 0,
    now: r.entry_price || 0,   // 沒有 current price，暫用 entry_price
    ret: r.backtest && r.backtest.pnl_pct != null ? r.backtest.pnl_pct : 0,
    hit: r.backtest && r.backtest.result === 'hit',
  }));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: (vp && vp.isMobile) ? '1fr 1fr' : 'repeat(4, 1fr)',
        gap: (vp && vp.isMobile) ? 8 : 12,
      }}>
        {stats.map(s => (
          <div key={s.period} style={{ background: T.surface, border: '1px solid ' + T.border, borderRadius: 8, padding: 14 }}>
            <div style={{ fontSize: 10, color: T.text3, marginBottom: 4 }}>{s.period}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{ fontSize: 24, fontWeight: 700, color: T.up, fontFamily: T.fontMono, letterSpacing: -0.5 }}>{s.rate}%</span>
              <span style={{ fontSize: 11, color: T.text3 }}>命中率</span>
            </div>
            <div style={{ fontSize: 11, color: T.text3, fontFamily: T.fontMono, marginTop: 4 }}>
              {s.hit} / {s.total} 次
            </div>
          </div>
        ))}
      </div>
      <window.Card title="近期推薦追蹤" padding={0}>
        <div style={{ overflowX: 'auto', WebkitOverflowScrolling: 'touch' }}>
          <div style={{ minWidth: 580 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '70px 110px 1fr 80px 80px 80px 80px',
              padding: '10px 20px', fontSize: 10, color: T.text3, fontWeight: 500,
              letterSpacing: 0.3, textTransform: 'uppercase', borderBottom: '1px solid ' + T.border,
              background: T.surface2 }}>
              <div>日期</div>
              <div>標的</div>
              <div>動作</div>
              <div style={{ textAlign: 'right' }}>進場</div>
              <div style={{ textAlign: 'right' }}>現價</div>
              <div style={{ textAlign: 'right' }}>報酬</div>
              <div style={{ textAlign: 'right' }}>結果</div>
            </div>
            {recent.map((r, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '70px 110px 1fr 80px 80px 80px 80px',
                padding: '10px 20px', borderBottom: i < recent.length - 1 ? '1px solid ' + T.border : 'none',
                fontSize: 12, alignItems: 'center' }}>
                <div style={{ fontFamily: T.fontMono, color: T.text3, fontSize: 11 }}>{r.d}</div>
                <div>
                  <div style={{ fontFamily: T.fontMono, fontSize: 10, color: T.text3 }}>{r.c}</div>
                  <div style={{ fontWeight: 600, color: T.text }}>{r.n}</div>
                </div>
                <div>
                  <span style={{ fontSize: 11, fontWeight: 600,
                    color: r.call === '買進' ? T.up : r.call === '減碼' ? T.down : T.text2,
                    background: r.call === '買進' ? T.upSoft : r.call === '減碼' ? T.downSoft : T.hover,
                    padding: '3px 7px', borderRadius: 3 }}>{r.call}</span>
                </div>
                <div style={{ textAlign: 'right', fontFamily: T.fontMono, color: T.text2 }}>{r.entry ? window.fmt(r.entry, r.entry < 100 ? 2 : 1) : '—'}</div>
                <div style={{ textAlign: 'right', fontFamily: T.fontMono, color: T.text }}>{r.now ? window.fmt(r.now, r.now < 100 ? 2 : 1) : '—'}</div>
                <div style={{ textAlign: 'right', fontFamily: T.fontMono, fontWeight: 600,
                  color: window.dirColor(r.ret) }}>{window.sign(r.ret)}{r.ret.toFixed(1)}%</div>
                <div style={{ textAlign: 'right' }}>
                  <span style={{ fontSize: 11, fontWeight: 700,
                    color: r.hit ? T.up : T.down,
                    background: r.hit ? T.upSoft : T.downSoft,
                    padding: '3px 7px', borderRadius: 3 }}>{r.hit ? '✓ 命中' : '✗ 未中'}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </window.Card>
    </div>
  );
}

})();
