// CostMeter — pure renderer for a task's observability cost rollup
// (arch §3.3 primitive / §6.2 telemetry, §3.2 Ledger). Takes a TaskCostReport
// (or null) as `cost`; does no data loading and never touches the Api tier —
// the page tier supplies data.
// Shape: { sessions,
//          byRoleModel:[{role,model,inputTokens,outputTokens,cacheReadTokens,cacheWriteTokens,cost}],
//          byStation:[{station,...same token fields}],
//          totalTokens, totalCost, errorEvents }.
// The Cache column is shown, not hidden: totalTokens counts cache tokens (a
// live Anthropic turn can be 99% cache write), so In+Out alone would never add
// up to the headline number.
const CostMeter = ({ cost }) => {
  if (!cost) {
    return <p className="text-neutral-400 text-sm italic">No cost data recorded yet.</p>;
  }
  const usd = (n) => {
    const v = Number(n) || 0;
    return `$${v.toFixed(v > 0 && Math.abs(v) < 0.1 ? 4 : 2)}`;
  };
  const tok = (n) => (Number(n) || 0).toLocaleString();
  const rows = Array.isArray(cost.byRoleModel) ? cost.byRoleModel : [];
  const stationRows = Array.isArray(cost.byStation) ? cost.byStation : [];
  const cache = (r) => (Number(r.cacheReadTokens) || 0) + (Number(r.cacheWriteTokens) || 0);

  const Stat = ({ label, value, tone = 'neutral' }) => (
    <div>
      <div className={`text-[11px] font-bold uppercase tracking-widest ${tone === 'red' ? 'text-red-400' : 'text-neutral-400'}`}>{label}</div>
      <div className={`text-2xl font-bold tabular-nums ${tone === 'red' ? 'text-red-600' : 'text-neutral-900'}`}>{value}</div>
    </div>
  );

  return (
    <div>
      <div className="flex flex-wrap gap-8 mb-5">
        <Stat label="Total spend" value={usd(cost.totalCost)} />
        <Stat label="Tokens" value={tok(cost.totalTokens)} />
        <Stat label="Sessions" value={cost.sessions || 0} />
        {cost.errorEvents > 0 && <Stat label="Errors" value={cost.errorEvents} tone="red" />}
      </div>
      {rows.length === 0 ? (
        <p className="text-neutral-400 text-sm italic">No model usage recorded for this task.</p>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[11px] uppercase tracking-widest text-neutral-400">
                <th className="font-bold py-1 pr-4">Role</th>
                <th className="font-bold py-1 pr-4">Model</th>
                <th className="font-bold py-1 px-2 text-right">In</th>
                <th className="font-bold py-1 px-2 text-right">Out</th>
                <th className="font-bold py-1 px-2 text-right">Cache</th>
                <th className="font-bold py-1 pl-2 text-right">Cost</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r, i) => (
                <tr key={`${r.role || '-'}:${r.model || '-'}:${i}`} className="border-t border-neutral-200">
                  <td className="py-1.5 pr-4 text-neutral-800">{r.role || '—'}</td>
                  <td className="py-1.5 pr-4 font-mono text-xs text-neutral-600 break-all">{r.model || '—'}</td>
                  <td className="py-1.5 px-2 text-right tabular-nums text-neutral-600">{tok(r.inputTokens)}</td>
                  <td className="py-1.5 px-2 text-right tabular-nums text-neutral-600">{tok(r.outputTokens)}</td>
                  <td className="py-1.5 px-2 text-right tabular-nums text-neutral-600">{tok(cache(r))}</td>
                  <td className="py-1.5 pl-2 text-right tabular-nums text-neutral-900 font-semibold">{usd(r.cost)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
      {stationRows.length > 0 && (
        <div className="overflow-x-auto mt-5">
          <div className="text-[11px] font-bold uppercase tracking-widest text-neutral-400 mb-1">By station</div>
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-[11px] uppercase tracking-widest text-neutral-400">
                <th className="font-bold py-1 pr-4">Station</th>
                <th className="font-bold py-1 px-2 text-right">In</th>
                <th className="font-bold py-1 px-2 text-right">Out</th>
                <th className="font-bold py-1 px-2 text-right">Cache</th>
                <th className="font-bold py-1 pl-2 text-right">Cost</th>
              </tr>
            </thead>
            <tbody>
              {stationRows.map((s, i) => (
                <tr key={`${s.station || '-'}:${i}`} className="border-t border-neutral-200">
                  <td className="py-1.5 pr-4 font-mono text-xs text-neutral-700 break-all">{s.station || '—'}</td>
                  <td className="py-1.5 px-2 text-right tabular-nums text-neutral-600">{tok(s.inputTokens)}</td>
                  <td className="py-1.5 px-2 text-right tabular-nums text-neutral-600">{tok(s.outputTokens)}</td>
                  <td className="py-1.5 px-2 text-right tabular-nums text-neutral-600">{tok(cache(s))}</td>
                  <td className="py-1.5 pl-2 text-right tabular-nums text-neutral-900 font-semibold">{usd(s.cost)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

window.CostMeter = CostMeter;
