// Compliance Ops Vitals — the CIO/CTO view. A small "vitals" card cluster.
// Confirm the program is healthy, no stranded fixes, gates actually firing.

function OpsVitals({ vitals, applicants, withdrawals }) {
  const v = vitals;

  return (
    <>
      <div className="app-subheader">
        <div className="subheader-title">Compliance Ops Vitals</div>
        <div className="subheader-meta">Last 24h · refreshed 8s ago</div>
        <div className="subheader-spacer" />
        <Btn variant="outlined" icon={IDownload}>Export tile (PNG)</Btn>
        <Btn variant="outlined" icon={IExternal}>Embed in Admin Home</Btn>
      </div>

      <div className="page-scroll">
        <div className="vitals-wrap">
          <div className="vitals-grid">
            <div className="vital is-good">
              <span className="vital-lbl"><Term id="Mutation">Value-bearing mutations</Term> w/o <Term id="KYC">KYC</Term> gate (24h)</span>
              <span className="vital-num">{v.unverifiedMutations}</span>
              <span className="vital-sub">Target: 0 · gates firing on every <Mono dim>transfer.*</Mono>, <Mono dim>withdrawal.*</Mono>, <Mono dim>subscription.*</Mono> call.</span>
            </div>
            <div className="vital">
              <span className="vital-lbl">Median time to decision</span>
              <span className="vital-num">{v.medianDecision}</span>
              <span className="vital-sub">Across {v.decisionsToday} decisions today</span>
            </div>
            <div className="vital is-warn">
              <span className="vital-lbl">Pending review <Term id="SLA">SLA</Term> · <Term id="p95">p95</Term></span>
              <span className="vital-num">{v.slap95}</span>
              <span className="vital-sub">p95 above 48h target — see queue</span>
            </div>
            <div className="vital">
              <span className="vital-lbl"><Term id="EDD">EDD</Term> <Term id="Attestation">attestations</Term> · 24h</span>
              <span className="vital-num">{v.edd}</span>
              <span className="vital-sub">{v.rejectedToday} rejection · {v.decisionsToday - v.rejectedToday} approvals</span>
            </div>
          </div>

          <Card title="Workstreams" hint="Operational health by program area" actions={<Btn variant="outlined" size="xs" icon={IExternal}>Open runbook</Btn>} dense>
            <div className="workstreams">
              {v.workstreams.map(ws => (
                <div key={ws.name} className="workstream">
                  <span className={`ws-dot ${ws.state}`} />
                  <span className="ws-name">{ws.name}</span>
                  <span className="ws-hint">{ws.hint}</span>
                  <span className={`ws-state-pill ${ws.state}`}>{ws.state.toUpperCase()}</span>
                </div>
              ))}
            </div>
          </Card>

          <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:14}}>
            <Card title="Pending review backlog" hint="By tier · last 14 days" actions={<Btn variant="ghost" size="xs">View queue →</Btn>}>
              <BacklogChart applicants={applicants} />
            </Card>
            <Card title="Withdrawal approvals" hint="By tier · last 14 days" actions={<Btn variant="ghost" size="xs">View withdrawals →</Btn>}>
              <WithdrawalsChart withdrawals={withdrawals} />
            </Card>
          </div>
        </div>
      </div>
    </>
  );
}

// Stacked area chart of backlog by tier over 14 days (mocked)
function BacklogChart({ applicants }) {
  const days = 14;
  const data = Array.from({length:days}, (_,d) => {
    const seed = d * 23 + 41;
    return {
      low:    8  + ((seed * 7) % 5),
      medium: 12 + ((seed * 11) % 8),
      high:   6  + ((seed * 13) % 6),
    };
  });
  // ramp the trend up toward today (showing backlog growth)
  data.forEach((p, i) => { p.high += Math.floor(i / 3); });

  const W = 480, H = 160, P = 16;
  const max = Math.max(...data.map(d => d.low + d.medium + d.high));
  const xs = data.map((_, i) => P + (i / (days - 1)) * (W - P*2));

  const seriesPath = (key, baseKey) => {
    const top = data.map((d, i) => {
      const total = (baseKey ? d[baseKey] : 0) + d[key];
      const y = H - P - (total / max) * (H - P*2);
      return { x: xs[i], y };
    });
    const bot = data.map((d, i) => {
      const total = baseKey ? d[baseKey] : 0;
      const y = H - P - (total / max) * (H - P*2);
      return { x: xs[i], y };
    }).reverse();
    return [...top, ...bot].map((p, i) => `${i === 0 ? "M" : "L"} ${p.x.toFixed(1)} ${p.y.toFixed(1)}`).join(" ") + " Z";
  };

  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{display:"block"}}>
      <path d={seriesPath("low")}    fill="var(--green-bg)"  stroke="var(--green)"   strokeWidth="1" />
      <path d={seriesPath("medium","low")} fill="var(--amber-bg)" stroke="var(--amber)" strokeWidth="1" />
      <path d={seriesPath("high","medium")} fill="var(--red-bg)" stroke="var(--red)" strokeWidth="1" />
      {/* x ticks */}
      {data.map((_, i) => i % 3 === 0 ? (
        <text key={i} x={xs[i]} y={H - 2} textAnchor="middle" fontSize="9" fill="var(--fg-4)" fontFamily="var(--font-mono)">
          {`5/${(19 - days + i + 1)}`}
        </text>
      ) : null)}
    </svg>
  );
}

function WithdrawalsChart({ withdrawals }) {
  // Tiny stacked bars for 7 days
  const days = 14;
  const buckets = Array.from({length: days}, (_, d) => {
    const seed = d * 19 + 7;
    return {
      low:    2 + ((seed * 7)  % 4),
      medium: 1 + ((seed * 11) % 5),
      high:   ((seed * 13) % 3),
    };
  });
  const max = Math.max(...buckets.map(b => b.low + b.medium + b.high));
  const W = 480, H = 160, P = 16;
  const colW = (W - P*2) / days;
  const barW = colW * 0.6;

  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{display:"block"}}>
      {buckets.map((b, i) => {
        const x = P + i * colW + (colW - barW) / 2;
        const h = (n) => (n / max) * (H - P*2);
        const yLow    = H - P - h(b.low);
        const yMed    = yLow - h(b.medium);
        const yHigh   = yMed - h(b.high);
        return (
          <g key={i}>
            <rect x={x} y={yLow} width={barW} height={h(b.low)}    fill="var(--green-bg)" stroke="var(--green)" strokeWidth="0.6" />
            <rect x={x} y={yMed} width={barW} height={h(b.medium)} fill="var(--amber-bg)" stroke="var(--amber)" strokeWidth="0.6" />
            <rect x={x} y={yHigh} width={barW} height={h(b.high)}  fill="var(--red-bg)"   stroke="var(--red)"   strokeWidth="0.6" />
            {i % 3 === 0 && (
              <text x={x + barW/2} y={H - 2} textAnchor="middle" fontSize="9" fill="var(--fg-4)" fontFamily="var(--font-mono)">
                {`5/${(19 - days + i + 1)}`}
              </text>
            )}
          </g>
        );
      })}
    </svg>
  );
}

Object.assign(window, { OpsVitals });
