// Dashboard / history / calibration view
function Dashboard({ onNew, onOpenHistory }) {
  return (
    <div>
      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 16 }}>
        <KPI label="QUERIES TODAY" value="14" sub="/ ~20 target" trend={[8,12,14,18,15,12,14]} tone="paper" />
        <KPI label="AUTO-PERSISTED" value="6" sub="≥ 75% confidence" tone="green" />
        <KPI label="MEDIAN CONF" value="0.71" sub="weighted avg" tone="paper" trend={[0.65,0.7,0.68,0.72,0.69,0.73,0.71].map(v=>v*100)} />
        <KPI label="SPEND · MTD" value="฿612" sub="~฿40/query · 15.3k mo budget" tone="yellow" />
        <KPI label="SCRAPER HEALTH" value="5/6" sub="Shopee selector drift" tone="red" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16 }}>
        {/* Recent queries */}
        <div className="brut" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '10px 14px', display: 'flex', alignItems: 'center' }}>
            <Label style={{ color: 'var(--paper)' }}>RECENT QUERIES</Label>
            <span className="mono" style={{ fontSize: 11, marginLeft: 'auto' }}>{HISTORY.length} shown · 600 mo-to-date</span>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>TIMESTAMP</th><th>PRODUCT</th><th>CONFIDENCE</th><th>BAND</th><th>STATUS</th><th></th>
              </tr>
            </thead>
            <tbody>
              {HISTORY.map((h, i) => (
                <tr key={i} style={{ background: i%2 ? 'var(--paper-2)' : 'var(--paper)' }}>
                  <td className="mono">{h.ts}</td>
                  <td style={{ fontWeight: 700 }}>{h.product}</td>
                  <td><ConfBar value={h.conf} width={60} /></td>
                  <td className="mono">{h.band}</td>
                  <td>
                    {h.status === 'AUTO'  && <Chip tone="green">AUTO</Chip>}
                    {h.status === 'QUEUE' && <Chip tone="blue">QUEUE</Chip>}
                    {h.status === 'LOG'   && <Chip>LOG</Chip>}
                  </td>
                  <td><Btn size="sm" variant="ghost" onClick={onOpenHistory}>OPEN →</Btn></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Right column */}
        <div>
          {/* Calibration */}
          <div className="brut" style={{ padding: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <Chip tone="yellow">CALIBRATION</Chip>
              <Label>EXPECTED vs ACTUAL · 100-PRODUCT SET</Label>
            </div>
            {CALIBRATION.map((c, i) => (
              <div key={i} style={{ padding: '8px 0', borderBottom: i < CALIBRATION.length - 1 ? '2px dashed var(--ink)' : 'none' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
                  <span style={{ fontWeight: 700 }}>{c.bucket}</span>
                  <span className="mono">n={c.n}</span>
                </div>
                <div style={{ position: 'relative', height: 14, border: '2px solid var(--ink)', background: 'var(--paper-2)' }}>
                  <div style={{ position:'absolute', left:0, top:0, bottom:0, width:`${c.expected*100}%`, background:'var(--yellow)' }} />
                  <div style={{ position:'absolute', left:0, top:0, bottom:0, width:`${c.actual*100}%`, borderRight:'3px solid var(--ink)' }} />
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, marginTop: 2 }} className="mono">
                  <span>exp {(c.expected*100).toFixed(0)}%</span>
                  <span style={{ color: c.actual >= c.expected - 0.05 ? 'var(--green)' : 'var(--red)' }}>
                    actual {(c.actual*100).toFixed(0)}%
                  </span>
                </div>
              </div>
            ))}
          </div>

          {/* Scraper health */}
          <div className="brut" style={{ padding: 14, marginTop: 12 }}>
            <Label>SOURCE HEALTH · 24H</Label>
            <div style={{ marginTop: 10 }}>
              {[
                { s: 'Shopee TH',   rate: '94%', status: 'warn', note: 'selector drift detected' },
                { s: 'Lazada TH',   rate: '99%', status: 'ok',   note: 'nominal' },
                { s: 'TikTok Shop', rate: '91%', status: 'ok',   note: 'Apify actor stable' },
                { s: '1688.com',    rate: '100%',status: 'ok',   note: 'cache hit rate 62%' },
                { s: 'Alibaba',     rate: '98%', status: 'ok',   note: 'nominal' },
                { s: 'Priceza',     rate: '100%',status: 'ok',   note: 'nominal' },
              ].map((s, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 0', borderBottom: i < 5 ? '1px dashed var(--ink)' : 'none', fontSize: 12 }}>
                  <div style={{ width: 10, height: 10, background: s.status === 'ok' ? 'var(--green)' : 'var(--yellow)', border: '2px solid var(--ink)' }} />
                  <span style={{ fontWeight: 700, minWidth: 92 }}>{s.s}</span>
                  <span className="mono" style={{ minWidth: 38 }}>{s.rate}</span>
                  <span className="mono" style={{ color: 'var(--muted)', fontSize: 11 }}>{s.note}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="brut" style={{ padding: 14, marginTop: 12, background: 'var(--red)', color: '#fff' }}>
            <Label style={{ color: '#fff' }}>READY TO PRICE A PRODUCT?</Label>
            <div className="big-num" style={{ fontSize: 22, marginTop: 6 }}>Start a new query.</div>
            <div className="mono" style={{ fontSize: 11, opacity: 0.9, marginTop: 4 }}>Est. ฿40 · ~42s end-to-end</div>
            <div style={{ marginTop: 12 }}>
              <Btn variant="ink" onClick={onNew}>+ NEW QUERY →</Btn>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function KPI({ label, value, sub, trend, tone = 'paper' }) {
  const bgMap = { paper: 'var(--paper)', green: 'var(--green)', yellow: 'var(--yellow)', red: 'var(--red)' };
  const fgMap = { paper: 'var(--ink)', green: '#fff', yellow: 'var(--ink)', red: '#fff' };
  return (
    <div className="brut" style={{ padding: 14, background: bgMap[tone], color: fgMap[tone] }}>
      <Label style={{ color: fgMap[tone], opacity: tone === 'paper' ? 0.6 : 0.85 }}>{label}</Label>
      <div className="big-num mono" style={{ fontSize: 30, marginTop: 4 }}>{value}</div>
      <div className="mono" style={{ fontSize: 10, opacity: 0.75, marginTop: 2 }}>{sub}</div>
      {trend && (
        <div style={{ marginTop: 6 }}>
          <Sparkline values={trend} width={160} height={22} color={fgMap[tone]} />
        </div>
      )}
    </div>
  );
}

window.Dashboard = Dashboard;
