/* Sentinel — Turnaround / SLA dashboard (4-hour SLA tracking). */

function Donut({ value, size = 96, tone = "var(--status-success)", label }) {
  const r = (size - 12) / 2, c = 2 * Math.PI * r;
  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--bg-sunken)" strokeWidth="9" />
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={tone} strokeWidth="9" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - value / 100)} style={{ transition: "stroke-dashoffset var(--motion-slower)" }} />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <span className="gj-money" style={{ fontSize: 24, color: "var(--content-strong)" }}>{value}%</span>
        {label && <span style={{ fontSize: 11, color: "var(--content-muted)" }}>{label}</span>}
      </div>
    </div>
  );
}

function HBar({ label, value, max, suffix, tone = "var(--ec-primary)" }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 11 }}>
      <span style={{ width: 130, flex: "none", fontSize: 13, color: "var(--content-base)", textAlign: "right", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
      <div style={{ flex: 1, height: 22, background: "var(--bg-sunken)", borderRadius: "var(--radius-sm)", overflow: "hidden" }}>
        <div style={{ width: (value / max * 100) + "%", height: "100%", background: tone, borderRadius: "var(--radius-sm)", transition: "width var(--motion-slow)" }} /></div>
      <span className="text-mono" style={{ width: 52, flex: "none", fontSize: 12.5, color: "var(--content-strong)", fontWeight: 600 }}>{value}{suffix}</span>
    </div>
  );
}

function SlaDashboard({ contracts, decisions }) {
  const stages = [
    { label: "Uploaded", icon: "upload", mins: 0 }, { label: "Classified", icon: "sparkles", mins: 3 },
    { label: "Routed", icon: "route", mins: 4 }, { label: "Decided", icon: "gavel", mins: 118 }, { label: "Outputs sent", icon: "send", mins: 126 },
  ];
  const live = contracts.filter((c) => c.status === "in_review");
  return (
    <div style={{ padding: 24 }}>
      {/* KPI row */}
      <div style={{ display: "flex", gap: 14, marginBottom: 18 }}>
        <Card padding={18} style={{ flex: 1, display: "flex", alignItems: "center", gap: 16 }}>
          <Donut value={96} label="within 4h" />
          <div><div className="text-label" style={{ marginBottom: 4 }}>SLA adherence</div>
            <div style={{ fontSize: 13.5, color: "var(--content-base)", lineHeight: 1.5 }}>47 of 49 contracts processed inside the 4-hour window this month.</div>
            <div style={{ fontSize: 12.5, color: "var(--status-success)", fontWeight: 600, marginTop: 6 }}>↑ 6 pts vs last month</div></div>
        </Card>
        <KpiCard label="Avg turnaround" value="2.4h" icon="timer" sub="target 4.0h" subTone="success" />
        <KpiCard label="Median" value="1.9h" icon="activity" sub="across all tiers" subTone="muted" />
        <KpiCard label="SLA breach rate" value="4%" icon="alarm-clock-off" sub="2 contracts" subTone="warning" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 14, marginBottom: 14 }}>
        {/* Stage timeline */}
        <Card padding={20}>
          <div style={{ fontSize: 15, fontWeight: 600, color: "var(--content-strong)", marginBottom: 4 }}>Time in stage</div>
          <div style={{ fontSize: 13, color: "var(--content-muted)", marginBottom: 20 }}>Average minutes spent at each step, upload → send.</div>
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", position: "relative" }}>
            <div style={{ position: "absolute", top: 18, left: 18, right: 18, height: 2, background: "var(--border-base)" }} />
            {stages.map((s, i) => (
              <div key={i} style={{ position: "relative", display: "flex", flexDirection: "column", alignItems: "center", gap: 8, flex: 1, zIndex: 1 }}>
                <span style={{ width: 38, height: 38, borderRadius: "50%", background: i === stages.length - 1 ? "var(--status-success)" : "var(--green-50)", color: i === stages.length - 1 ? "#fff" : "var(--green-700)", display: "flex", alignItems: "center", justifyContent: "center", border: "2px solid var(--bg-surface)" }}><Icon name={s.icon} size={17} /></span>
                <span style={{ fontSize: 12, fontWeight: 600, color: "var(--content-strong)", textAlign: "center" }}>{s.label}</span>
                {i > 0 && <span className="text-mono" style={{ fontSize: 11.5, color: "var(--content-muted)" }}>+{s.mins - stages[i - 1].mins}m</span>}
              </div>
            ))}
          </div>
          <div style={{ marginTop: 20, paddingTop: 16, borderTop: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--content-muted)" }}>
            <Icon name="lightbulb" size={15} style={{ color: "var(--status-warning)" }} /> The decision stage dominates turnaround — the review console is where time is won or lost.
          </div>
        </Card>

        {/* CEO touch */}
        <Card padding={20}>
          <div style={{ fontSize: 15, fontWeight: 600, color: "var(--content-strong)", marginBottom: 16 }}>Routing mix</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {[["Auto-accepted", 22, "var(--neutral-400)"], ["Head of SP Contracting", 61, "var(--ec-primary)"], ["CEO (high-risk only)", 17, "var(--status-danger)"]].map(([l, v, t]) => (
              <div key={l}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 5, fontSize: 13 }}><span style={{ color: "var(--content-base)" }}>{l}</span><span className="text-mono" style={{ fontWeight: 600, color: "var(--content-strong)" }}>{v}%</span></div>
                <div style={{ height: 8, background: "var(--bg-sunken)", borderRadius: 999, overflow: "hidden" }}><div style={{ width: v + "%", height: "100%", background: t, borderRadius: 999 }} /></div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 18, padding: "11px 13px", background: "var(--green-50)", borderRadius: "var(--radius-md)", fontSize: 13, color: "var(--content-base)", display: "flex", gap: 9 }}>
            <Icon name="trending-down" size={15} style={{ color: "var(--green-700)", flex: "none", marginTop: 1 }} /> CEO touch rate down from 100% (every contract) to 17% — only genuine high-risk reaches the CEO.</div>
        </Card>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
        <Card padding={20}>
          <div style={{ fontSize: 15, fontWeight: 600, color: "var(--content-strong)", marginBottom: 16 }}>Turnaround by contract type</div>
          {[["Hospital Services Agmt", 2.6], ["Data Processing Agmt", 2.1], ["Service Level Agmt", 1.7], ["Data Sharing Agmt", 3.1]].map(([l, v]) => (
            <HBar key={l} label={l} value={v} max={4} suffix="h" tone={v > 3 ? "var(--status-warning)" : "var(--ec-primary)"} />
          ))}
        </Card>
        <Card padding={20}>
          <div style={{ fontSize: 15, fontWeight: 600, color: "var(--content-strong)", marginBottom: 16 }}>Turnaround by reviewer</div>
          {[["Head of SP Contracting", 2.2], ["CEO", 1.1], ["Auto-accept", 0.1]].map(([l, v]) => (
            <HBar key={l} label={l} value={v} max={4} suffix="h" tone="var(--green-600)" />
          ))}
          <div style={{ marginTop: 8, fontSize: 12.5, color: "var(--content-muted)" }}>Reviewer active time per change averages 48 seconds — under the one-minute target.</div>
        </Card>
      </div>

      {/* Live countdown */}
      <Card padding={0} style={{ overflow: "hidden" }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border-base)", display: "flex", alignItems: "center", gap: 9 }}>
          <Icon name="radio" size={16} style={{ color: "var(--status-danger)" }} />
          <span style={{ fontSize: 15, fontWeight: 600, color: "var(--content-strong)" }}>Live — contracts in flight</span>
          <span style={{ fontSize: 13, color: "var(--content-muted)" }}>· countdown to SLA</span>
        </div>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
          <tbody>
            {live.map((c) => (
              <tr key={c.id}>
                <td style={{ padding: "12px 20px", borderTop: "1px solid var(--border-subtle)", fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--content-strong)" }}>{c.id}</td>
                <td style={{ padding: "12px 20px", borderTop: "1px solid var(--border-subtle)", color: "var(--content-strong)" }}>{PROVIDERS[c.provider].name}</td>
                <td style={{ padding: "12px 20px", borderTop: "1px solid var(--border-subtle)", color: "var(--content-muted)", fontSize: 13 }}>{c.type}</td>
                <td style={{ padding: "12px 20px", borderTop: "1px solid var(--border-subtle)" }}><RiskMini risk={highestRisk(c, decisions)} /></td>
                <td style={{ padding: "12px 20px", borderTop: "1px solid var(--border-subtle)", textAlign: "right" }}><SlaPill uploadedMs={c.uploadedMs} size="sm" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

Object.assign(window, { SlaDashboard });
