/* ============================================
   COST TRACKING — Token burn + monthly budget
   ============================================ */
function CostScreen() {
  const budget = 18000;
  const spent = 12842;
  const pct = (spent / budget) * 100;

  const dailyBurn = [320, 412, 388, 401, 567, 122, 188, 478, 521, 487, 544, 612, 198, 240, 642, 698, 671, 740, 802, 287, 312, 822, 894, 901, 880, 950, 401, 412, 1024, 1082];
  const W = 800, H = 180, P = 26;
  const max = Math.max(...dailyBurn);
  const stepX = (W - P * 2) / (dailyBurn.length - 1);

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Cost Tracking</h1>
          <p className="page-subtitle">May 2026 · monthly budget cycle · billing in USD</p>
        </div>
        <div className="row">
          <button className="btn btn--ghost"><Icons.Download size={14} /> Invoice CSV</button>
          <button className="btn btn--secondary"><Icons.Settings size={14} /> Budget Settings</button>
        </div>
      </div>

      {/* Hero budget card */}
      <Card style={{ marginBottom: 16 }}>
        <div className="row" style={{ marginBottom: 14, alignItems: "flex-end" }}>
          <div>
            <div className="text-xs muted" style={{ textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600, marginBottom: 4 }}>Monthly Budget vs Actual Spend</div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
              <span style={{ fontSize: 40, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--orange-600)" }}>${spent.toLocaleString()}</span>
              <span className="muted" style={{ fontSize: 16 }}>/ ${budget.toLocaleString()} budgeted</span>
            </div>
          </div>
          <span className="spacer" />
          <div style={{ textAlign: "right" }}>
            <Badge kind="orange">{pct.toFixed(1)}% utilized</Badge>
            <div className="text-xs muted" style={{ marginTop: 6 }}>Day 23 of 31 · pacing 89%</div>
          </div>
        </div>

        <Progress value={pct} large="xl" />

        <div className="row" style={{ marginTop: 10, fontSize: 12 }}>
          <span className="muted">$0</span>
          <span className="spacer" />
          <span className="mono" style={{ color: "var(--ink-700)" }}>$5,000</span>
          <span className="spacer" />
          <span className="mono" style={{ color: "var(--ink-700)" }}>$10,000</span>
          <span className="spacer" />
          <span className="mono" style={{ color: "var(--orange-700)", fontWeight: 600 }}>${budget.toLocaleString()}</span>
        </div>

        <div className="grid-4" style={{ marginTop: 18, gap: 0, borderTop: "1px solid var(--ink-200)", paddingTop: 16 }}>
          <Stat label="Embeddings" value="$3,124" sub="312.4M tokens · emb-3-lg" />
          <Stat label="Inference" value="$7,902" sub="48.2M tokens · haiku-4.5" />
          <Stat label="Vision (OCR)" value="$1,418" sub="218K pages processed" />
          <Stat label="Storage & infra" value="$398" sub="Qdrant + workers" accent="var(--ink-700)" />
        </div>
      </Card>

      <div className="grid-2">
        {/* Daily burn */}
        <Card title="API Token Burn — Daily" subtitle="Tokens consumed per day across all models">
          <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block" }}>
            {/* gridlines */}
            {[0.5, 1].map(t => (
              <line key={t} x1={P} y1={H - P - t * (H - P * 2)} x2={W - P} y2={H - P - t * (H - P * 2)} stroke="#EFF1F5" strokeWidth="1"/>
            ))}
            {/* bars */}
            {dailyBurn.map((v, i) => {
              const x = P + i * stepX - stepX * 0.35;
              const barH = (v / max) * (H - P * 2);
              const isLast = i === dailyBurn.length - 1;
              return (
                <rect
                  key={i}
                  x={x}
                  y={H - P - barH}
                  width={stepX * 0.7}
                  height={barH}
                  fill={isLast ? "#F26419" : "var(--navy-500)"}
                  rx="1"
                />
              );
            })}
            {[0, 9, 19, 29].map(i => (
              <text key={i} x={P + i * stepX} y={H - P + 12} fontSize="9" fontFamily="IBM Plex Mono" fill="#98A2B3" textAnchor="middle">May {i + 1}</text>
            ))}
            <text x={W - P} y={14} fontSize="10" fontFamily="IBM Plex Mono" fill="#0B2447" textAnchor="end" fontWeight="600">PEAK 1,082K tok</text>
          </svg>
        </Card>

        {/* Cost by model */}
        <Card title="Cost by Model" subtitle="Current month breakdown">
          <table className="table">
            <thead>
              <tr><th>Model</th><th style={{ textAlign: "right" }}>Tokens</th><th style={{ textAlign: "right" }}>Cost</th><th style={{ textAlign: "right" }}>$/1M</th></tr>
            </thead>
            <tbody>
              {[
                ["claude-haiku-4.5", "44.2M", "$7,156", "$1.00 / $5.00"],
                ["emb-3-lg",         "312.4M","$3,124", "$0.10"],
                ["gpt-4o-vision",    "8.1M",  "$1,418", "$15.00"],
                ["claude-haiku-4.5 (cached)", "12.8M", "$640", "$0.05"],
                ["reranker-2.1",     "4.0M",  "$120", "$3.00"],
              ].map(([m, t, c, r], i) => (
                <tr key={i}>
                  <td><span className="mono text-xs" style={{ fontWeight: 600 }}>{m}</span></td>
                  <td className="mono text-xs" style={{ textAlign: "right" }}>{t}</td>
                  <td className="mono" style={{ textAlign: "right", fontWeight: 600 }}>{c}</td>
                  <td className="mono text-xs muted" style={{ textAlign: "right" }}>{r}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      <div className="grid-2" style={{ marginTop: 16 }}>
        {/* Cost by team */}
        <Card title="Cost by Department" subtitle="Internal chargeback">
          {[
            { name: "Plant Operations", v: 4820, pct: 37.5 },
            { name: "Maintenance & Reliability", v: 3140, pct: 24.5 },
            { name: "Quality Assurance", v: 2090, pct: 16.3 },
            { name: "Process Engineering", v: 1782, pct: 13.9 },
            { name: "EHS / Safety", v: 1010, pct: 7.8 },
          ].map(d => (
            <div key={d.name} style={{ marginBottom: 12 }}>
              <div className="row" style={{ marginBottom: 4 }}>
                <span className="text-sm fw-600">{d.name}</span>
                <span className="spacer" />
                <span className="mono text-xs">${d.v.toLocaleString()}</span>
                <span className="text-xs muted" style={{ marginLeft: 6, width: 40, textAlign: "right" }}>{d.pct}%</span>
              </div>
              <Progress value={d.pct * 2.5} />
            </div>
          ))}
        </Card>

        {/* Alerts */}
        <Card title="Budget Alerts" subtitle="Triggered thresholds and forecasts">
          <div className="col gap-12">
            <AlertRow kind="warn" title="Pacing 89% of monthly budget" sub="At current rate, will reach 102% by May 31. Consider raising cap or reviewing embedding refresh schedule." />
            <AlertRow kind="info" title="Vision OCR up 32% week-over-week" sub="Driven by ABB-IRB-6700 ingestion (31 MB, image-heavy). Normal ramp-up — expected to stabilize next week." />
            <AlertRow kind="ok" title="Caching saved $2,140 this month" sub="48% prompt cache hit rate on recurring system prompts. No action needed." />
          </div>
        </Card>
      </div>
    </>
  );
}

function AlertRow({ kind, title, sub }) {
  const colors = {
    warn: { bg: "#FFFBEB", fg: "#92400E", border: "#FDE68A", icon: <Icons.AlertCircle /> },
    info: { bg: "var(--navy-50)", fg: "var(--navy-700)", border: "var(--navy-100)", icon: <Icons.Activity /> },
    ok:   { bg: "#ECFDF5", fg: "#065F46", border: "#A7F3D0", icon: <Icons.Check /> },
  };
  const c = colors[kind];
  return (
    <div style={{ display: "flex", gap: 12, padding: 12, background: c.bg, border: `1px solid ${c.border}`, borderRadius: 6 }}>
      <span style={{ color: c.fg, flexShrink: 0, marginTop: 1 }}>{c.icon}</span>
      <div>
        <div style={{ fontWeight: 600, fontSize: 13, color: c.fg, marginBottom: 2 }}>{title}</div>
        <div className="text-xs" style={{ color: "var(--ink-700)", lineHeight: 1.55 }}>{sub}</div>
      </div>
    </div>
  );
}

window.CostScreen = CostScreen;
