// Polished Overview screen

function Overview({ setScreen, setProject }){
  return (
    <div data-screen-label="01 Overview" style={{ padding:"24px 28px 40px", maxWidth:1320, margin:"0 auto", display:"flex", flexDirection:"column", gap:20 }}>

      {/* ── Page header ───────────────────────────────────── */}
      <header style={{ display:"flex", alignItems:"flex-end", justifyContent:"space-between", gap:16 }}>
        <div>
          <div style={{ fontSize:11, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600, marginBottom:6 }}>Workspace overview</div>
          <h1 style={{ margin:0, fontSize:28, fontWeight:600, letterSpacing:-0.5, color:"var(--fg-0)" }}>May 2026</h1>
          <div style={{ color:"var(--fg-2)", fontSize:13, marginTop:5 }}>
            Day <span className="mono" style={{ color:"var(--fg-1)" }}>{PERIOD.daysElapsed}</span> of {PERIOD.daysTotal} · {PROJECTS.filter(p=>p.status==="active").length} active projects · last sync <span className="mono" style={{ color:"var(--fg-1)" }}>14:32:08 UTC</span>
          </div>
        </div>
        <div style={{ display:"flex", gap:8 }}>
          <PeriodSwitcher/>
          <RefreshBtn/>
        </div>
      </header>

      {/* ── Hero summary band ─────────────────────────────── */}
      <HeroBand/>

      {/* ── Where spend went + Provider mix ───────────────── */}
      <div style={{ display:"grid", gridTemplateColumns:"1.55fr 1fr", gap:18 }}>
        <SpendDistribution/>
        <ProviderMix/>
      </div>

      {/* ── Daily trend (combo) ───────────────────────────── */}
      <DailyTrend/>

      {/* ── Models + Insights ─────────────────────────────── */}
      <div style={{ display:"grid", gridTemplateColumns:"1.4fr 1fr", gap:18 }}>
        <ModelsCard/>
        <InsightsCard/>
      </div>

      {/* ── Top projects ───────────────────────────────────── */}
      <TopProjectsTable setScreen={setScreen} setProject={setProject}/>

      {/* ── Trust strip + quick actions ───────────────────── */}
      <BottomStrip/>

      <div style={{ textAlign:"center", color:"var(--fg-3)", fontSize:11, marginTop:6 }}>Data as of today · 14:32 UTC</div>
    </div>
  );
}

// ── Hero summary band ─────────────────────────────────────
function HeroBand(){
  const trajectory = PERIOD.totalGBP / PERIOD.daysElapsed * PERIOD.daysTotal;
  const dayPct = PERIOD.daysElapsed / PERIOD.daysTotal;
  const spendShape = DAILY.map(d => d.cost);

  return (
    <div className="card" style={{ padding:0, overflow:"hidden", display:"grid", gridTemplateColumns:"1.45fr 1fr" }}>
      {/* Left — primary metric */}
      <div style={{ padding:"22px 26px 20px", borderRight:"1px solid var(--line-1)", position:"relative" }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start" }}>
          <div>
            <div style={{ fontSize:11, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600, marginBottom:8 }}>Total spend</div>
            <div style={{ display:"flex", alignItems:"baseline", gap:14, flexWrap:"wrap" }}>
              <Money value={PERIOD.totalGBP} size="hero"/>
              <span className="mono" style={{ fontSize:13, color:"var(--fg-2)" }}>≈ {fmtUSD(PERIOD.totalUSD, 2)}</span>
            </div>
            <div style={{ display:"flex", alignItems:"center", gap:14, marginTop:10 }}>
              <span style={{ display:"inline-flex", alignItems:"center", gap:6 }}>
                <Delta pct={PERIOD.deltaPct}/>
                <span style={{ fontSize:12, color:"var(--fg-2)" }}>vs April ({fmtGBP(PERIOD.previousTotalGBP)})</span>
              </span>
            </div>
          </div>
          <div style={{ width:140 }}>
            <Sparkline data={spendShape} w={140} h={36} color="var(--accent)" dot/>
            <div style={{ display:"flex", justifyContent:"space-between", marginTop:4, fontSize:10, color:"var(--fg-3)" }} className="mono">
              <span>1 May</span><span>today</span>
            </div>
          </div>
        </div>

        {/* Days progress + trajectory */}
        <div style={{ marginTop:18 }}>
          <div style={{ display:"flex", justifyContent:"space-between", marginBottom:6, fontSize:11.5, color:"var(--fg-2)" }}>
            <span>Pace: <span className="mono" style={{ color:"var(--fg-0)", fontWeight:500 }}>{fmtGBP(trajectory)}</span> projected by month-end</span>
            <span className="mono">{(dayPct*100).toFixed(0)}% of period elapsed</span>
          </div>
          <div style={{ position:"relative", height:7, background:"var(--bg-3)", borderRadius:99, overflow:"hidden" }}>
            <div style={{ position:"absolute", left:0, top:0, bottom:0, width:(dayPct*100)+"%", background:"linear-gradient(90deg,var(--accent),var(--accent-2))", borderRadius:99 }}/>
            <div style={{ position:"absolute", left:0, top:0, bottom:0, width:"100%", background:"repeating-linear-gradient(90deg, transparent 0 calc(100%/31 - 1px), rgba(20,16,8,0.06) calc(100%/31 - 1px) calc(100%/31))" }}/>
          </div>
        </div>
      </div>

      {/* Right — 2×2 grid of richer secondary metrics */}
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gridTemplateRows:"1fr 1fr" }}>
        <MiniKPI label="Requests"
          value={PERIOD.requests.toLocaleString()}
          delta={0.521}
          sub={<><span className="mono">{Math.round(PERIOD.requests/PERIOD.daysElapsed)}</span>/day · 4 errors</>}
          icon="activity"
          spark={DAILY.map(d=>d.reqs)} sparkColor="var(--p-google)"
          borderL
        />
        <MiniKPI label="Avg cost / request"
          value={fmtGBP(PERIOD.avgCostPerRequest, 6)}
          delta={0.008}
          sub={<><span className="mono">6,723</span> Opus · <span className="mono">12</span> other</>}
          icon="coins"
          spark={DAILY.map(d=>d.cost/d.reqs)} sparkColor="var(--accent)"
          borderL borderT={false}
        />
        <MiniKPI label="Tokens used"
          value="41.2M"
          delta={null}
          sub={<><span className="mono">8.4M</span> in · <span className="mono">32.8M</span> out</>}
          icon="tokens"
          spark={DAILY.map(d=>d.cost*0.6 + d.reqs*0.02)} sparkColor="var(--fg-2)"
          borderL borderT
        />
        <MiniKPI label="Cache hit rate"
          value="38%"
          delta={0.06}
          sub={<>saved ≈ <span className="mono">£121</span> this period</>}
          icon="chip"
          progress={0.38} progressColor="var(--pos)"
          borderL borderT
        />
      </div>
    </div>
  );
}

function MiniKPI({ label, value, sub, delta, icon, borderL, borderT, spark, sparkColor, progress, progressColor }){
  return (
    <div style={{
      padding:"14px 16px 14px",
      borderLeft:  borderL ? "1px solid var(--line-1)" : "none",
      borderTop:   borderT ? "1px solid var(--line-1)" : "none",
      display:"flex", flexDirection:"column", justifyContent:"space-between",
      minHeight:96, position:"relative", overflow:"hidden",
    }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:6 }}>
        <span style={{ fontSize:10, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600 }}>{label}</span>
        <Icon name={icon} size={12} stroke="var(--fg-3)"/>
      </div>
      <div style={{ display:"flex", alignItems:"baseline", gap:7 }}>
        <span className="mono" style={{ fontSize:19, fontWeight:600, color:"var(--fg-0)", letterSpacing:-0.2 }}>{value}</span>
        {delta != null && <Delta pct={delta}/>}
      </div>
      <div style={{ fontSize:10.5, color:"var(--fg-2)", marginTop:4 }}>{sub}</div>
      {spark && (
        <div style={{ position:"absolute", right:10, bottom:32, opacity:0.55, pointerEvents:"none" }}>
          <Sparkline data={spark} w={52} h={16} color={sparkColor || "var(--fg-2)"} fill={false}/>
        </div>
      )}
      {progress != null && (
        <div style={{ position:"absolute", left:16, right:16, bottom:9, height:3, background:"var(--bg-3)", borderRadius:99, overflow:"hidden" }}>
          <div style={{ width:(progress*100)+"%", height:"100%", background:progressColor || "var(--accent)", borderRadius:99 }}/>
        </div>
      )}
    </div>
  );
}

// ── Where the spend went — Pareto with sparkline trends ───
function SpendDistribution(){
  const total = PROJECTS.reduce((s,p)=>s+p.spend, 0);
  const top = [...PROJECTS].sort((a,b)=>b.spend-a.spend).slice(0,6);
  const max = top[0].spend;
  let cum = 0;
  return (
    <section className="card" style={{ padding:"20px 22px" }}>
      <SectionHeader
        title="Where the spend went"
        subtitle="Top 6 projects · 91% of period spend"
        action={<button style={btnSubtle()}>All projects <Icon name="arrow" size={11}/></button>}
      />
      <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
        {top.map(p => {
          cum += p.spend;
          const share = p.spend/total;
          const cumShare = cum/total;
          const series = makeSeries(p.spend, 11, p.shape);
          return (
            <div key={p.slug} style={{ display:"grid", gridTemplateColumns:"160px 1fr 70px 60px", gap:14, alignItems:"center" }}>
              <div style={{ display:"flex", flexDirection:"column", minWidth:0 }}>
                <span style={{ fontSize:13, fontWeight:500, color:"var(--fg-0)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{p.name}</span>
                <span className="mono" style={{ fontSize:10.5, color:"var(--fg-3)", marginTop:1 }}>/{p.slug}</span>
              </div>
              <div style={{ position:"relative" }}>
                <div className="bar-track" style={{ height:8 }}>
                  <div className="bar-fill" style={{ width: (p.spend/max*100)+"%", height:"100%" }}/>
                </div>
                <div style={{ position:"absolute", left:0, right:0, top:-16, display:"flex", justifyContent:"flex-end" }}>
                  <Sparkline data={series} w={60} h={14} color="var(--accent)" fill={false}/>
                </div>
              </div>
              <div style={{ textAlign:"right" }}>
                <Money value={p.spend} size="sm"/>
              </div>
              <div style={{ textAlign:"right", display:"flex", flexDirection:"column", gap:2 }}>
                <span className="mono" style={{ fontSize:12, color:"var(--fg-1)", fontWeight:500 }}>{(share*100).toFixed(1)}%</span>
                <span className="mono" style={{ fontSize:10, color:"var(--fg-3)" }}>{(cumShare*100).toFixed(0)}% cum</span>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ── Provider mix — donut + risk insight when 1 dominant ────
function ProviderMix(){
  const totals = PROVIDER_TOTALS;
  const total = Object.values(totals).reduce((s,v)=>s+v.cost, 0);
  return (
    <section className="card" style={{ padding:"20px 22px", display:"flex", flexDirection:"column" }}>
      <SectionHeader title="Provider mix" subtitle="By cost · May 2026"/>
      <div style={{ display:"grid", gridTemplateColumns:"160px 1fr", gap:18, alignItems:"center", marginTop:4 }}>
        <ConcentricDonut totals={totals} size={160}/>
        <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
          {Object.entries(totals).sort((a,b)=>b[1].cost-a[1].cost).map(([k,v]) => (
            <div key={k}>
              <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:4 }}>
                <span style={{ display:"inline-flex", alignItems:"center", gap:7, fontSize:12.5 }}>
                  <ProviderDot provider={k}/><span style={{ color:"var(--fg-0)", fontWeight:500 }}>{PROVIDERS[k].name}</span>
                </span>
                <span className="mono" style={{ fontSize:12, color:"var(--fg-0)" }}>{fmtUSD(v.cost, v.cost<1 ? 4 : 2)}</span>
              </div>
              <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                <div className="bar-track" style={{ flex:1, height:5 }}>
                  <div style={{ position:"absolute", left:0, top:0, bottom:0, width:(v.cost/total*100)+"%", background:PROVIDERS[k].color, borderRadius:99 }}/>
                </div>
                <span className="mono" style={{ fontSize:11, color:"var(--fg-2)", minWidth:46, textAlign:"right" }}>{(v.cost/total*100).toFixed(1)}%</span>
              </div>
              <div className="mono" style={{ fontSize:10.5, color:"var(--fg-3)", marginTop:3 }}>{v.requests.toLocaleString()} reqs</div>
            </div>
          ))}
        </div>
      </div>

      {/* Concentration insight */}
      <div style={{ marginTop:18, padding:"10px 12px", borderRadius:8, background:"var(--pos-soft)", border:"1px solid rgba(15,138,79,0.22)", display:"flex", gap:10, alignItems:"flex-start" }}>
        <Icon name="info" size={14} stroke="var(--pos)"/>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:12, color:"var(--fg-0)", fontWeight:500 }}>Diversified across 7 providers</div>
          <div style={{ fontSize:11.5, color:"var(--fg-2)", marginTop:2 }}>60.6% Anthropic · 19.0% OpenAI · routing reduces blast radius and improves negotiating leverage.</div>
        </div>
      </div>
    </section>
  );
}

function ConcentricDonut({ totals, size }){
  const total = Object.values(totals).reduce((s,v)=>s+v.cost, 0) || 1;
  const r = size/2 - 14;
  const cx = size/2, cy = size/2;
  const stroke = 16;
  let acc = 0;
  const arcs = Object.entries(totals).filter(([,v])=>v.cost>0).map(([k,v]) => {
    const start = acc / total;
    const end = (acc + v.cost) / total;
    acc += v.cost;
    return { provider:k, value:v.cost, start, end };
  });
  function arcPath({ start, end }){
    if (end - start >= 0.999) {
      // full circle — draw two arcs
      return `M ${cx-r} ${cy} A ${r} ${r} 0 1 1 ${cx+r} ${cy} A ${r} ${r} 0 1 1 ${cx-r} ${cy}`;
    }
    const a0 = start * 2 * Math.PI - Math.PI/2;
    const a1 = end * 2 * Math.PI - Math.PI/2;
    const large = end - start > 0.5 ? 1 : 0;
    const x0 = cx + r*Math.cos(a0), y0 = cy + r*Math.sin(a0);
    const x1 = cx + r*Math.cos(a1), y1 = cy + r*Math.sin(a1);
    return `M ${x0} ${y0} A ${r} ${r} 0 ${large} 1 ${x1} ${y1}`;
  }
  return (
    <svg width={size} height={size}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--bg-3)" strokeWidth={stroke}/>
      {arcs.map(a => (
        <path key={a.provider} d={arcPath(a)} fill="none" stroke={PROVIDERS[a.provider].color} strokeWidth={stroke} strokeLinecap="butt"/>
      ))}
      <text x={cx} y={cy-4} textAnchor="middle" fontSize="10.5" fill="var(--fg-2)" fontFamily="var(--font-sans)" style={{ letterSpacing:0.06, textTransform:"uppercase" }}>Total</text>
      <text x={cx} y={cy+14} textAnchor="middle" fontSize="16" fill="var(--fg-0)" fontFamily="var(--font-mono)" fontWeight="600">${total.toFixed(2)}</text>
    </svg>
  );
}

// ── Daily trend — combo (cost area + request bars) ─────────
function DailyTrend(){
  const ref = useRef(null);
  const w = useWidth(ref);
  const [hover, setHover] = useState(null);
  const h = 220;
  const padL = 48, padR = 44, padT = 14, padB = 32;
  const innerW = Math.max(100, w - padL - padR);
  const innerH = h - padT - padB;
  const n = DAILY.length;

  const maxCost = Math.max(...DAILY.map(d=>d.cost), 1) * 1.18;
  const maxReq  = Math.max(...DAILY.map(d=>d.reqs), 1) * 1.18;
  const xC = i => (i/(n-1))*innerW;
  const yCost = v => innerH - (v/maxCost)*innerH;
  const yReq  = v => innerH - (v/maxReq)*innerH;

  const areaPts = DAILY.map((d,i)=>`${xC(i)},${yCost(d.cost)}`).join(" L");
  const areaPath = `M0,${innerH} L${areaPts} L${innerW},${innerH} Z`;
  const linePath = `M${areaPts}`;
  const barW = (innerW/n) * 0.32;

  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(t => ({ v: t*maxCost, y: yCost(t*maxCost) }));

  function onMove(e){
    const rect = ref.current.getBoundingClientRect();
    const px = e.clientX - rect.left - padL;
    if (px < 0 || px > innerW) { setHover(null); return; }
    const i = Math.max(0, Math.min(n-1, Math.round((px/innerW)*(n-1))));
    setHover(i);
  }

  // Spike annotation: max cost day
  const spikeIdx = DAILY.reduce((mi,d,i,arr)=> arr[mi].cost > d.cost ? mi : i, 0);

  return (
    <section className="card" style={{ padding:"20px 22px" }}>
      <SectionHeader
        title="Daily spend"
        subtitle="Cost area · request volume bars · last 11 days"
        action={
          <div style={{ display:"flex", gap:6 }}>
            <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:11.5, color:"var(--fg-2)" }}>
              <span style={{ width:10, height:3, borderRadius:2, background:"var(--accent)" }}/> Cost
            </span>
            <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:11.5, color:"var(--fg-2)", marginLeft:12 }}>
              <span style={{ width:6, height:10, borderRadius:1, background:"var(--bg-4)" }}/> Requests
            </span>
          </div>
        }
      />
      <div ref={ref} style={{ position:"relative", width:"100%", height:h }} onMouseMove={onMove} onMouseLeave={()=>setHover(null)}>
        <svg width={w} height={h} style={{ display:"block", overflow:"visible" }}>
          <defs>
            <linearGradient id="costGrad" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.25"/>
              <stop offset="100%" stopColor="var(--accent)" stopOpacity="0.02"/>
            </linearGradient>
          </defs>
          {/* Y grid */}
          {yTicks.map((t,i) => (
            <g key={i}>
              <line x1={padL} x2={padL+innerW} y1={padT+t.y} y2={padT+t.y} stroke="var(--line-1)" strokeDasharray={i===0?"":"2 4"}/>
              <text x={padL-10} y={padT+t.y+3} textAnchor="end" fontSize="10" fontFamily="var(--font-mono)" fill="var(--fg-3)">£{t.v.toFixed(0)}</text>
            </g>
          ))}
          {/* Right axis (requests) */}
          {yTicks.map((t,i) => (
            <text key={i} x={padL+innerW+10} y={padT+yReq(t.v/maxCost*maxReq)+3} textAnchor="start" fontSize="10" fontFamily="var(--font-mono)" fill="var(--fg-3)">{Math.round(t.v/maxCost*maxReq)}</text>
          ))}

          <g transform={`translate(${padL},${padT})`}>
            {/* Request bars */}
            {DAILY.map((d,i) => {
              const bh = innerH - yReq(d.reqs);
              return <rect key={i} x={xC(i)-barW/2} y={yReq(d.reqs)} width={barW} height={bh} rx="1.5" fill="var(--bg-4)" opacity="0.85"/>;
            })}
            {/* Cost area + line */}
            <path d={areaPath} fill="url(#costGrad)"/>
            <path d={linePath} fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            {/* Cost dots */}
            {DAILY.map((d,i) => (
              <circle key={i} cx={xC(i)} cy={yCost(d.cost)} r={hover===i?4:2.5} fill="var(--accent)" stroke="#fff" strokeWidth="1.5"/>
            ))}
            {/* Hover crosshair */}
            {hover != null && <line x1={xC(hover)} x2={xC(hover)} y1={0} y2={innerH} stroke="var(--fg-3)" strokeDasharray="3 3"/>}
            {/* Spike annotation */}
            <g transform={`translate(${xC(spikeIdx)},${yCost(DAILY[spikeIdx].cost)-12})`}>
              <rect x="-30" y="-14" width="60" height="14" rx="3" fill="#fff" stroke="var(--line-2)"/>
              <text x="0" y="-3.5" textAnchor="middle" fontSize="10" fill="var(--fg-1)" fontFamily="var(--font-mono)">peak £{DAILY[spikeIdx].cost}</text>
            </g>
          </g>

          {/* X axis labels */}
          {DAILY.map((d,i) => (i===0 || i===n-1 || i%2===0) && (
            <text key={i} x={padL+xC(i)} y={h-10} textAnchor="middle" fontSize="10.5" fontFamily="var(--font-mono)" fill="var(--fg-3)">{d.d} May</text>
          ))}
          {/* Axis labels */}
          <text x={padL-30} y={padT-2} fontSize="9.5" fontFamily="var(--font-sans)" fill="var(--fg-3)" style={{ letterSpacing:0.06, textTransform:"uppercase" }}>GBP</text>
          <text x={padL+innerW+8} y={padT-2} fontSize="9.5" fontFamily="var(--font-sans)" fill="var(--fg-3)" style={{ letterSpacing:0.06, textTransform:"uppercase" }}>REQS</text>
        </svg>

        {hover != null && (
          <div className="tt" style={{ left: Math.min(w-220, padL + xC(hover) + 14), top: padT + 6, minWidth:200 }}>
            <div style={{ fontSize:11, color:"var(--fg-3)", marginBottom:5 }} className="mono">{DAILY[hover].d} May 2026</div>
            <div style={{ display:"flex", justifyContent:"space-between", gap:14, fontSize:12, padding:"1px 0" }}>
              <span style={{ color:"var(--fg-2)" }}>Cost</span>
              <Money value={DAILY[hover].cost} size="sm"/>
            </div>
            <div style={{ display:"flex", justifyContent:"space-between", gap:14, fontSize:12, padding:"1px 0" }}>
              <span style={{ color:"var(--fg-2)" }}>Requests</span>
              <span className="mono" style={{ color:"var(--fg-0)", fontWeight:500 }}>{DAILY[hover].reqs.toLocaleString()}</span>
            </div>
            <div style={{ display:"flex", justifyContent:"space-between", gap:14, fontSize:12, padding:"1px 0", borderTop:"1px solid var(--line-1)", marginTop:5, paddingTop:5 }}>
              <span style={{ color:"var(--fg-2)" }}>Cost/req</span>
              <span className="mono" style={{ color:"var(--fg-1)" }}>{fmtGBP(DAILY[hover].cost/DAILY[hover].reqs, 4)}</span>
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

// ── Models used — horizontal stacked bars with efficiency ───
function ModelsCard(){
  const totalCost = MODEL_USE.reduce((s,m)=>s+m.cost, 0);
  const max = Math.max(...MODEL_USE.map(m=>m.cost));
  return (
    <section className="card" style={{ padding:"20px 22px" }}>
      <SectionHeader
        title="Models used"
        subtitle="Top models by cost · May 2026"
        action={<span className="badge badge--ghost">{MODEL_USE.length} models</span>}
      />
      <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
        {MODEL_USE.map(m => {
          const cpr = m.requests > 0 ? m.cost/m.requests : 0;
          const meta = MODELS[m.id] || MODELS.unknown;
          const provider = PROVIDERS[meta.provider];
          return (
            <div key={m.id} style={{ display:"grid", gridTemplateColumns:"160px 1fr 110px", gap:14, alignItems:"center" }}>
              <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                <span style={{ width:7, height:7, borderRadius:2, background:provider.color, flexShrink:0 }}/>
                <span className="mono" style={{ fontSize:12, color:"var(--fg-0)" }}>{meta.short}</span>
              </div>
              <div style={{ position:"relative" }}>
                <div className="bar-track" style={{ height:18 }}>
                  <div style={{ position:"absolute", left:0, top:0, bottom:0, width:Math.max(m.cost/max*100, 0.4)+"%", background:provider.color, borderRadius:99, opacity:m.cost===0?0.18:1 }}/>
                </div>
                <div style={{ position:"absolute", left:8, top:0, bottom:0, display:"flex", alignItems:"center", fontSize:10.5, color:m.cost/max>0.3?"#fff":"var(--fg-2)", fontWeight:500 }} className="mono">
                  {m.requests.toLocaleString()} reqs · {cpr<0.01? fmtUSD(cpr,6) : fmtUSD(cpr,4)}/req
                </div>
              </div>
              <div style={{ textAlign:"right", display:"flex", flexDirection:"column", gap:2 }}>
                <span className="mono" style={{ fontSize:13, color:"var(--fg-0)", fontWeight:600 }}>{fmtUSD(m.cost, m.cost<1?4:2)}</span>
                <span className="mono" style={{ fontSize:10.5, color:"var(--fg-3)" }}>{(m.cost/totalCost*100).toFixed(m.cost/totalCost<0.001?2:1)}%</span>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ── Insights ───────────────────────────────────────────────
function InsightsCard(){
  return (
    <section className="card" style={{ padding:"20px 22px" }}>
      <SectionHeader
        title="Observations"
        subtitle="Generated from your usage pattern"
        action={<span style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:11, color:"var(--accent)" }}><Icon name="sparkles" size={12}/> auto</span>}
      />
      <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
        {INSIGHTS.map((it,i) => {
          const palette = it.tone==="warn"
            ? { fg:"var(--warn)",   bg:"var(--warn-soft)",   border:"rgba(185,113,13,0.22)" }
            : it.tone==="accent"
              ? { fg:"var(--accent)", bg:"var(--accent-soft)", border:"var(--accent-line)" }
              : { fg:"var(--fg-2)",   bg:"var(--bg-3)",        border:"var(--line-1)" };
          const icon = it.tone==="warn" ? "alert" : it.tone==="accent" ? "bolt" : "info";
          return (
            <div key={i} style={{ display:"grid", gridTemplateColumns:"28px 1fr", gap:11, padding:"11px 12px", borderRadius:9, background:palette.bg, border:`1px solid ${palette.border}` }}>
              <div style={{ width:26, height:26, borderRadius:7, background:"#fff", display:"flex", alignItems:"center", justifyContent:"center", color:palette.fg, border:`1px solid ${palette.border}` }}>
                <Icon name={icon} size={13}/>
              </div>
              <div>
                <div style={{ fontSize:12.5, color:"var(--fg-0)", fontWeight:500 }}>{it.title}</div>
                <div style={{ fontSize:11.5, color:"var(--fg-2)", marginTop:3, lineHeight:1.45 }}>{it.body}</div>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ── Top projects table ─────────────────────────────────────
function TopProjectsTable({ setScreen, setProject }){
  const top = [...PROJECTS].sort((a,b)=>b.spend-a.spend).slice(0,7);
  return (
    <section className="card" style={{ padding:0, overflow:"hidden" }}>
      <div style={{ padding:"16px 22px", display:"flex", alignItems:"center", justifyContent:"space-between", borderBottom:"1px solid var(--line-1)" }}>
        <div>
          <h2 style={{ margin:0, fontSize:14, fontWeight:600, color:"var(--fg-0)" }}>Top projects</h2>
          <div style={{ fontSize:11.5, color:"var(--fg-2)", marginTop:3 }}>Highest spend · May 2026</div>
        </div>
        <button style={btnGhost()}>View all 21 <Icon name="arrow" size={11}/></button>
      </div>
      <table className="tbl">
        <thead>
          <tr>
            <th style={{ paddingLeft:22 }}>Project</th>
            <th className="right">Period spend</th>
            <th className="right">Requests</th>
            <th className="right">Cost / req</th>
            <th>Trend</th>
            <th>Primary model</th>
            <th style={{ paddingRight:22 }}>Last active</th>
          </tr>
        </thead>
        <tbody>
          {top.map(p => {
            const cpr = p.requests > 0 ? p.spend/p.requests : 0;
            const series = makeSeries(p.spend, 11, p.shape);
            return (
              <tr key={p.slug} className="clickable" onClick={() => { setProject && setProject(p.slug); setScreen && setScreen("project-detail"); }}>
                <td style={{ paddingLeft:22 }}>
                  <div style={{ display:"flex", flexDirection:"column", gap:1 }}>
                    <span style={{ color:"var(--fg-0)", fontWeight:500 }}>{p.name}</span>
                    <span className="mono" style={{ fontSize:11, color:"var(--fg-3)" }}>/{p.slug}</span>
                  </div>
                </td>
                <td className="right"><Money value={p.spend} size="sm"/></td>
                <td className="right mono" style={{ color:"var(--fg-1)" }}>{p.requests.toLocaleString()}</td>
                <td className="right mono" style={{ color:"var(--fg-2)", fontSize:12 }}>{fmtGBP(cpr, 4)}</td>
                <td><Sparkline data={series} w={84} h={20} color="var(--accent)"/></td>
                <td><ModelBadge model={p.primaryModel}/></td>
                <td className="mono" style={{ color:"var(--fg-2)", fontSize:12, paddingRight:22 }}>{p.lastActive}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </section>
  );
}

// ── Bottom strip — reconciliation + quick actions ─────────
function BottomStrip(){
  return (
    <div style={{ display:"grid", gridTemplateColumns:"1.4fr 1fr", gap:18 }}>
      {/* Reconciliation */}
      <div className="card" style={{ padding:"14px 18px", display:"flex", alignItems:"center", gap:14, borderColor:"rgba(15,138,79,0.22)", background:"linear-gradient(180deg, rgba(15,138,79,0.04), transparent 60%)" }}>
        <div style={{ width:34, height:34, borderRadius:9, background:"var(--pos-soft)", color:"var(--pos)", display:"flex", alignItems:"center", justifyContent:"center", border:"1px solid rgba(15,138,79,0.22)" }}>
          <Icon name="check" size={16}/>
        </div>
        <div style={{ flex:1 }}>
          <div style={{ display:"flex", alignItems:"center", gap:8 }}>
            <span style={{ fontSize:13, color:"var(--fg-0)", fontWeight:600 }}>Reconciliation perfect</span>
            <span className="badge badge--pos" style={{ fontSize:10.5 }}>0.30% variance</span>
          </div>
          <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:3 }}>Logged: <span className="mono" style={{ color:"var(--fg-1)" }}>£277.88</span> · Anthropic billed: <span className="mono" style={{ color:"var(--fg-1)" }}>£277.04</span> · last synced just now</div>
        </div>
        <button style={btnGhost()}>View ledger <Icon name="arrow" size={11}/></button>
      </div>

      {/* Quick actions */}
      <div className="card" style={{ padding:"14px 18px" }}>
        <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:8 }}>
          <span style={{ fontSize:12, color:"var(--fg-0)", fontWeight:600 }}>Quick actions</span>
          <span style={{ fontSize:11, color:"var(--fg-3)" }}>for this period</span>
        </div>
        <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
          <button style={btnSecondary()}><Icon name="folder" size={13}/> All projects</button>
          <button style={btnSecondary()}><Icon name="sparkles" size={13}/> Run optimisation</button>
          <button style={btnPrimary()}><Icon name="download" size={13}/> Generate report</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Overview });
