// page-chips.jsx — 法人籌碼追蹤（NEW，1:1 對齊設計檔，2026-05-10）
// 設計檔結構：4 KPI + 5 日 FiveDayFlow（SVG bar chart）+ tab(inst/broker/margin/borrow)
// D1 接線：flow_tw（institutions / 5day_history / top_buy / top_sell / margin / borrow）
// 重要 export：window.ChipsPage
(function(){
  const T = window.STOCK_TOKENS;

  function ChipsPage() {
    const live = window.STOCK_DATA_LIVE || {};
    const flowTw = live.flow_tw || {};
    const [tab, setTab] = React.useState('inst');

    // 當日三大法人合計（億）
    // D1 schema 可能是 institutions: [{name, buy_b/sell_b/net_b}]
    const institutions = flowTw.institutions || [];
    const findNet = (label) => {
      const it = institutions.find(i => (i.name || '').includes(label));
      if (!it) return 0;
      return (typeof it.net_b === 'number') ? it.net_b
           : (typeof it.net === 'number') ? it.net : 0;
    };
    const today = {
      foreign: findNet('外資'),
      trust: findNet('投信'),
      dealer: findNet('自營'),
      total: institutions.reduce((s, i) => s + (i.net_b ?? i.net ?? 0), 0),
    };

    // 5 日歷史
    const history = flowTw.history_5d || flowTw.daily || [];
    const hasFlowData = history.length > 0;

    return (
      <div style={{ padding: 16, maxWidth: 1400, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', paddingBottom: 16, borderBottom: '1px solid var(--line)' }}>
          <div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', letterSpacing: '.1em' }}>
              INSTITUTIONAL · MARGIN · BROKER FLOW · {flowTw.date || '—'}
            </div>
            <div className="title-serif" style={{ fontSize: 24, fontWeight: 600, color: 'var(--fg-0)', marginTop: 4 }}>法人籌碼追蹤</div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-2)', marginTop: 2 }}>
              三大法人買賣超 · 主力券商進出 · 融資融券 · 借券賣出
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <select defaultValue="t"><option value="t">當日</option><option>近 5 日</option><option>近 20 日</option></select>
            <button className="btn">📤 匯出 CSV</button>
          </div>
        </div>

        {/* 4 KPI */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 16 }}>
          <BigKpi label="三大法人合計" value={Math.round(today.total)} unit="億" sub={hasFlowData ? '盤後 18:00 更新' : '盤後更新'} />
          <BigKpi label="外資買賣超"   value={Math.round(today.foreign)} unit="億" sub="日 fcst" />
          <BigKpi label="投信買賣超"   value={Math.round(today.trust)} unit="億" sub="日 fcst" />
          <BigKpi label="自營商"       value={Math.round(today.dealer)} unit="億" sub="避險 + 自行" />
        </div>

        {/* 5 日 bar chart */}
        <div className="panel" style={{ marginTop: 12, padding: 16 }}>
          <div className="panel-h" style={{ padding: 0, borderBottom: 'none', marginBottom: 8 }}>
            <span className="label">近 5 日三大法人買賣超（億）</span>
            <span className="pill mono">FOREIGN · TRUST · DEALER</span>
          </div>
          {hasFlowData ? (
            <FiveDayFlow data={history} />
          ) : (
            <div style={{ padding: '40px 14px', textAlign: 'center', color: 'var(--fg-3)' }}>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '.08em', marginBottom: 6 }}>// NO FLOW HISTORY</div>
              <div style={{ fontSize: 12 }}>盤後 18:00 自動更新</div>
            </div>
          )}
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', borderBottom: '1px solid var(--line)', marginTop: 16, gap: 24 }}>
          {[
            { id: 'inst', label: '三大法人', n: 20 },
            { id: 'broker', label: '主力券商', n: 10 },
            { id: 'margin', label: '融資融券', n: (flowTw.margin || []).length },
            { id: 'borrow', label: '借券賣出', n: (flowTw.borrow || []).length },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              background: 'transparent', border: 'none', cursor: 'pointer', padding: '10px 0',
              color: tab === t.id ? 'var(--fg-0)' : 'var(--fg-3)',
              borderBottom: `2px solid ${tab === t.id ? 'var(--accent)' : 'transparent'}`,
              fontSize: 13,
            }}>
              {t.label} <span className="mono" style={{ color: 'var(--fg-4)', marginLeft: 4, fontSize: 11 }}>{t.n}</span>
            </button>
          ))}
        </div>

        {tab === 'inst'   && <InstTab flowTw={flowTw} />}
        {tab === 'broker' && <BrokerTab flowTw={flowTw} />}
        {tab === 'margin' && <MarginTab flowTw={flowTw} />}
        {tab === 'borrow' && <BorrowTab flowTw={flowTw} />}
      </div>
    );
  }
  window.ChipsPage = ChipsPage;

  function BigKpi({ label, value, unit, sub }) {
    const cls = value > 0 ? 'up' : value < 0 ? 'down' : '';
    return (
      <div className="panel" style={{ padding: 16 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '.1em' }}>{label.toUpperCase()}</div>
        <div className={`num ${cls}`} style={{ fontSize: 32, fontWeight: 600, marginTop: 6, lineHeight: 1.1 }}>
          {value > 0 ? '+' : ''}{value.toLocaleString()}
          <span className="mono" style={{ fontSize: 13, color: 'var(--fg-3)', marginLeft: 6, fontWeight: 400 }}>{unit}</span>
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 6 }}>{sub}</div>
      </div>
    );
  }

  // ── FiveDayFlow：對齊設計檔 SVG bar chart ────────────────────────
  function FiveDayFlow({ data }) {
    // data: [{ d: 'MM/DD', foreign, trust, dealer }]
    const all = data.flatMap(d => [d.foreign, d.trust, d.dealer]);
    const rawMax = Math.max(...all.map(Math.abs), 1);
    const niceMax = Math.ceil(rawMax / 1000) * 1000 || 1000;
    const ticks = [];
    for (let v = -niceMax; v <= niceMax; v += niceMax / 2) ticks.push(v);

    const W = 880, H = 240;
    const padL = 56, padR = 16, padT = 16, padB = 44;
    const plotW = W - padL - padR;
    const plotH = H - padT - padB;
    const zeroY = padT + plotH / 2;
    const yScale = v => zeroY - (v / niceMax) * (plotH / 2);

    const groupW = plotW / data.length;
    const barW = 16;
    const innerGap = 6;
    const groupInner = barW * 3 + innerGap * 2;

    const series = [
      { key: 'foreign', label: '外資',   color: 'var(--accent)' },
      { key: 'trust',   label: '投信',   color: 'var(--accent-2)' },
      { key: 'dealer',  label: '自營商', color: '#9d6cff' },
    ];

    return (
      <div>
        <div style={{ display: 'flex', gap: 18, padding: '4px 0 12px 56px', fontSize: 11.5, color: 'var(--fg-2)' }}>
          {series.map(s => (
            <span key={s.key} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 10, height: 10, background: s.color, borderRadius: 1 }}></span>
              {s.label}
            </span>
          ))}
          <span style={{ marginLeft: 'auto', color: 'var(--fg-3)', fontSize: 10.5 }} className="mono">UNIT · 億 NTD</span>
        </div>
        <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', overflow: 'visible' }}>
          {ticks.map((t, i) => (
            <g key={i}>
              <line x1={padL} x2={W - padR} y1={yScale(t)} y2={yScale(t)}
                stroke={t === 0 ? 'var(--line-2)' : 'var(--line)'}
                strokeWidth={t === 0 ? 1 : 0.5}
                strokeDasharray={t === 0 ? '' : '2 3'} />
              <text x={padL - 8} y={yScale(t) + 3} textAnchor="end" fill="var(--fg-3)" fontSize="10" fontFamily="ui-monospace, monospace">
                {t > 0 ? `+${t}` : t}
              </text>
            </g>
          ))}

          {data.map((d, i) => {
            const gx = padL + i * groupW + groupW / 2;
            const total = (d.foreign || 0) + (d.trust || 0) + (d.dealer || 0);
            return (
              <g key={i}>
                {series.map((s, j) => {
                  const v = d[s.key] || 0;
                  const x = gx - groupInner / 2 + j * (barW + innerGap);
                  const y = v >= 0 ? yScale(v) : zeroY;
                  const h = Math.abs(yScale(v) - zeroY);
                  return (
                    <g key={s.key}>
                      <rect x={x} y={y} width={barW} height={h} fill={s.color} opacity={v >= 0 ? 1 : 0.55} rx="1" />
                      <text x={x + barW / 2} y={v >= 0 ? y - 4 : y + h + 11} textAnchor="middle"
                        fill="var(--fg-2)" fontSize="9.5" fontFamily="ui-monospace, monospace">
                        {v > 0 ? `+${v}` : v}
                      </text>
                    </g>
                  );
                })}
                <text x={gx} y={H - 22} textAnchor="middle" fill="var(--fg-2)" fontSize="11" fontFamily="ui-monospace, monospace">{d.d}</text>
                <text x={gx} y={H - 8} textAnchor="middle" fontSize="10.5" fontFamily="ui-monospace, monospace"
                  fill={total > 0 ? 'var(--up)' : total < 0 ? 'var(--down)' : 'var(--fg-3)'}>
                  合計 {total > 0 ? '+' : ''}{total}
                </text>
              </g>
            );
          })}
        </svg>
      </div>
    );
  }

  // ── InstTab ──────────────────────────────────────────────────────
  function InstTab({ flowTw }) {
    const top10Buy = flowTw.top10_buy || flowTw.top_buy || [];
    const top10Sell = flowTw.top10_sell || flowTw.top_sell || [];
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 16 }}>
        <FlowList title="買超榜 · TOP 10" data={top10Buy} side="buy" />
        <FlowList title="賣超榜 · TOP 10" data={top10Sell} side="sell" />
      </div>
    );
  }

  function FlowList({ title, data, side }) {
    if (!data || data.length === 0) {
      return (
        <div className="panel">
          <div className="panel-h"><span className="label">{title}</span></div>
          <div style={{ padding: '40px 14px', textAlign: 'center', color: 'var(--fg-3)' }}>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '.08em' }}>// NO DATA</div>
          </div>
        </div>
      );
    }
    return (
      <div className="panel">
        <div className="panel-h">
          <span className="label">
            <span style={{ color: side === 'buy' ? 'var(--up)' : 'var(--down)' }}>●</span>
            {title}
          </span>
          <span className="pill mono">{side === 'buy' ? '三大法人合計買超' : '合計賣超'} · 張</span>
        </div>
        <table>
          <thead>
            <tr>
              <th style={{ width: 40 }}>#</th>
              <th>個股</th>
              <th className="r">收盤</th>
              <th className="r">漲跌%</th>
              <th className="r">外資</th>
              <th className="r">投信</th>
              <th className="r">自營</th>
              <th className="r">連續</th>
            </tr>
          </thead>
          <tbody>
            {data.slice(0, 10).map((s, i) => {
              const code = s.sym || s.code;
              const name = s.name || '—';
              const price = s.price ?? null;
              const chg = s.chg ?? s.change_pct ?? 0;
              const fnet = s.fnet ?? s.foreign_net ?? 0;
              const tnet = s.tnet ?? s.trust_net ?? 0;
              const dnet = s.dnet ?? s.dealer_net ?? 0;
              const days = s.days ?? s.streak ?? '—';
              return (
                <tr key={code} className="row-fade" style={{ animationDelay: `${i * 30}ms` }}>
                  <td className="mono" style={{ color: 'var(--fg-3)' }}>{i + 1}</td>
                  <td>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)' }}>{code}</div>
                    <div style={{ fontSize: 12.5 }}>{name}</div>
                  </td>
                  <td className="r num">{price != null ? price.toLocaleString() : '—'}</td>
                  <td className={`r num ${chg > 0 ? 'up' : chg < 0 ? 'down' : ''}`}>{chg > 0 ? '+' : ''}{chg}%</td>
                  <td className={`r num ${fnet > 0 ? 'up' : fnet < 0 ? 'down' : ''}`}>{fnet > 0 ? '+' : ''}{Number(fnet).toLocaleString()}</td>
                  <td className={`r num ${tnet > 0 ? 'up' : tnet < 0 ? 'down' : ''}`}>{tnet > 0 ? '+' : ''}{Number(tnet).toLocaleString()}</td>
                  <td className={`r num ${dnet > 0 ? 'up' : dnet < 0 ? 'down' : ''}`}>{dnet > 0 ? '+' : ''}{Number(dnet).toLocaleString()}</td>
                  <td className="r mono" style={{ fontSize: 11 }}>
                    <span className="chip" style={{ fontSize: 10, padding: '1px 6px', color: side === 'buy' ? 'var(--up)' : 'var(--down)' }}>
                      {side === 'buy' ? '↗' : '↘'} {days}日
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }

  // ── BrokerTab ────────────────────────────────────────────────────
  function BrokerTab({ flowTw }) {
    // 預設選一支股票（從 picks/portfolio 取第一支或 2330）
    const live = window.STOCK_DATA_LIVE || {};
    const defaultCode = (live.picks?.picks?.[0]?.code) || (live.portfolio?.holdings?.[0]?.code) || '2330';
    const [code, setCode] = React.useState(defaultCode);
    const [broker, setBroker] = React.useState(null);
    const [loading, setLoading] = React.useState(true);

    React.useEffect(() => {
      setLoading(true); setBroker(null);
      fetch('_data/broker/' + code + '.json', { cache: 'no-store' })
        .then(r => r.ok ? r.json() : null)
        .then(d => { setBroker(d); setLoading(false); })
        .catch(() => { setBroker(null); setLoading(false); });
    }, [code]);

    return (
      <div style={{ marginTop: 16 }}>
        <div className="panel" style={{ padding: 16, marginBottom: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '.1em' }}>SYMBOL · 鎖定個股查看主力券商分佈</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 4 }}>
              <span className="mono" style={{ fontSize: 14, color: 'var(--fg-2)' }}>{code}</span>
              <span style={{ fontSize: 20, fontWeight: 600 }}>{broker?.name || '—'}</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <input placeholder="搜尋代號…" defaultValue={code} onKeyDown={(e) => { if (e.key === 'Enter') setCode(e.target.value.trim()); }} style={{ width: 160 }} />
            <button className="btn">🔄 換股</button>
          </div>
        </div>
        {loading ? (
          <div className="panel" style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)' }}>載入分點資料中…</div>
        ) : !broker || broker._status !== 'live' ? (
          <div className="panel" style={{ padding: '40px 20px', textAlign: 'center' }}>
            <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', letterSpacing: '.08em', marginBottom: 6 }}>// BROKER DATA NOT AVAILABLE</div>
            <div style={{ fontSize: 12, color: 'var(--fg-2)' }}>明日 cron 自動更新（需 FINMIND_API_KEY）</div>
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <BrokerList title="主買券商 TOP 5" data={(broker.top_buys || []).map(b => ({
              name: b.broker_name, vol: b.net_shares, pct: 0,
            }))} side="buy" />
            <BrokerList title="主賣券商 TOP 5" data={(broker.top_sells || []).map(b => ({
              name: b.broker_name, vol: Math.abs(b.net_shares), pct: 0,
            }))} side="sell" />
          </div>
        )}
      </div>
    );
  }

  function BrokerList({ title, data, side }) {
    const max = Math.max(...data.map(d => d.vol), 1);
    return (
      <div className="panel">
        <div className="panel-h">
          <span className="label">
            <span style={{ color: side === 'buy' ? 'var(--up)' : 'var(--down)' }}>●</span> {title}
          </span>
        </div>
        <div style={{ padding: 12 }}>
          {data.map((b, i) => (
            <div key={i} className="row-fade" style={{ animationDelay: `${i * 60}ms`, padding: '8px 0', borderBottom: i < data.length - 1 ? '1px solid var(--line)' : 'none' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
                <span style={{ fontSize: 13 }}>{b.name}</span>
                <span className="mono" style={{ fontSize: 11.5, color: 'var(--fg-2)' }}>
                  {b.vol >= 1000 ? `${(b.vol/1000).toFixed(0)}K` : b.vol.toLocaleString()} 張
                </span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ flex: 1, height: 6, background: 'var(--bg-2)', borderRadius: 2, overflow: 'hidden' }}>
                  <div className="bar-fill" style={{ width: `${(b.vol/max)*100}%`, height: '100%', background: side === 'buy' ? 'var(--up)' : 'var(--down)', animationDelay: `${i * 60}ms` }}></div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── MarginTab ────────────────────────────────────────────────────
  function MarginTab({ flowTw }) {
    const data = flowTw.margin || [];
    if (data.length === 0) {
      return (
        <div className="panel" style={{ padding: '40px 20px', textAlign: 'center', marginTop: 16 }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', letterSpacing: '.08em' }}>// NO MARGIN DATA</div>
        </div>
      );
    }
    return (
      <div className="panel" style={{ marginTop: 16, overflow: 'hidden' }}>
        <div className="panel-h">
          <span className="label">融資融券餘額 · 券資比</span>
          <span className="pill mono">張 · 前日比較</span>
        </div>
        <table>
          <thead>
            <tr>
              <th>個股</th>
              <th className="r">融資餘額</th>
              <th className="r">融資增減</th>
              <th className="r">融券餘額</th>
              <th className="r">融券增減</th>
              <th className="r">券資比</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {data.map((s, i) => (
              <tr key={s.sym || s.code} className="row-fade" style={{ animationDelay: `${i * 30}ms` }}>
                <td>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', marginRight: 8 }}>{s.sym || s.code}</span>
                  {s.name}
                </td>
                <td className="r num">{(s.mlong || 0).toLocaleString()}</td>
                <td className={`r num ${s.mlongChg > 0 ? 'up' : 'down'}`}>{s.mlongChg > 0 ? '+' : ''}{s.mlongChg}</td>
                <td className="r num">{(s.sshort || 0).toLocaleString()}</td>
                <td className={`r num ${s.sshortChg > 0 ? 'up' : 'down'}`}>{s.sshortChg > 0 ? '+' : ''}{s.sshortChg}</td>
                <td className="r mono" style={{ fontWeight: 600, color: s.ratio > 20 ? 'var(--accent)' : 'var(--fg-1)' }}>{s.ratio}%</td>
                <td style={{ width: 80 }}>
                  {s.ratio > 20 && <span className="chip" style={{ fontSize: 9.5, color: 'var(--accent)', borderColor: 'var(--accent)' }}>軋空潛力</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  // ── BorrowTab ────────────────────────────────────────────────────
  function BorrowTab({ flowTw }) {
    const data = flowTw.borrow || [];
    if (data.length === 0) {
      return (
        <div className="panel" style={{ padding: '40px 20px', textAlign: 'center', marginTop: 16 }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', letterSpacing: '.08em' }}>// NO BORROW DATA</div>
        </div>
      );
    }
    return (
      <div className="panel" style={{ marginTop: 16, overflow: 'hidden' }}>
        <div className="panel-h">
          <span className="label">借券賣出餘額 · TOP</span>
          <span className="pill mono">張 · 借券賣出佔成交比例</span>
        </div>
        <table>
          <thead>
            <tr>
              <th>個股</th>
              <th className="r">借券賣出餘額</th>
              <th className="r">當日增減</th>
              <th className="r">佔成交比</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {data.map((s, i) => (
              <tr key={s.sym || s.code} className="row-fade" style={{ animationDelay: `${i * 30}ms` }}>
                <td>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', marginRight: 8 }}>{s.sym || s.code}</span>
                  {s.name}
                </td>
                <td className="r num">{(s.balance || 0).toLocaleString()}</td>
                <td className={`r num ${s.chg > 0 ? 'up' : 'down'}`}>{s.chg > 0 ? '+' : ''}{s.chg}</td>
                <td className="r mono" style={{ fontWeight: 600 }}>{s.ratio}%</td>
                <td style={{ width: 100 }}>
                  {s.ratio > 1 && <span className="chip chip-down" style={{ fontSize: 9.5 }}>空方壓力</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

})();
