/* =========================================================
   Admin / Operator console — observability + debugging tools
   =========================================================
   Pages exported here:
     - LiveOps           live call grid (real-time view of every call)
     - CallsGlobal       cross-tenant call search + filters
     - AdminCallDetail   call drill-down with debug rails (SIP, media, AI trace)
     - SystemHealth      full status page (services, regions, p95 timeline)
     - WebhooksLog       integration delivery log (per tenant)
     - Incidents         open ops tickets / on-call view
     - FeatureFlags      per-tenant flag matrix
     - Revenue           MRR, cohorts, usage outliers (replaces shallow Billing plans)
     - ImpersonationBanner  global banner shown while impersonating

   Convention: every action logs through window.api.* so a real
   backend can swap in. Pure presentational components mock data
   inline — keep this file the source of truth for ops chrome.
   ========================================================= */


/* ----------------------------------------------------------
   Shared admin primitives (kept local — used only by ops UI)
   ---------------------------------------------------------- */

/* Compact metric tile — smaller than StatCard, fits dense ops grids */
const OpsTile = ({ k, v, sub, tone, icon }) => (
  <div className="card card-pad" style={{ padding: 16 }}>
    <div className="row between" style={{ marginBottom: 8 }}>
      <div style={{ fontSize: 11.5, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--fg-muted)", fontWeight: 600 }}>{k}</div>
      {icon && <Icon name={icon} size={14} style={{ color: "var(--fg-faint)" }}/>}
    </div>
    <div className="num" style={{ fontSize: 26, color: tone === "danger" ? "var(--mk-danger)" : tone === "warn" ? "var(--mk-warning)" : tone === "success" ? "var(--mk-success)" : "var(--fg)" }}>{v}</div>
    {sub && <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 4 }}>{sub}</div>}
  </div>
);

/* Code-style block for raw payloads, SIP frames etc. */
const CodeBlock = ({ children, label, max = 240 }) => (
  <div style={{ position: "relative" }}>
    {label && <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--fg-muted)", fontWeight: 600, marginBottom: 6 }}>{label}</div>}
    <pre className="mono" style={{ margin: 0, padding: 14, background: "var(--bg-sunken)", border: "1px solid var(--border)", borderRadius: 10, fontSize: 12, lineHeight: 1.55, color: "var(--fg)", overflow: "auto", maxHeight: max, whiteSpace: "pre-wrap", wordBreak: "break-word" }}>{children}</pre>
  </div>
);

/* Sparkline timeline used for service health */
const HealthTimeline = ({ data, color = "var(--mk-success)" }) => {
  // data: array of 0=ok, 1=warn, 2=down
  const tone = (s) => s === 0 ? color : s === 1 ? "var(--mk-warning)" : "var(--mk-danger)";
  return (
    <div className="row" style={{ gap: 2, height: 22, alignItems: "stretch" }}>
      {data.map((s, i) => (
        <div key={i} title={s === 0 ? "ok" : s === 1 ? "degraded" : "down"} style={{ flex: 1, background: tone(s), borderRadius: 2, minWidth: 2, opacity: 0.85 }}/>
      ))}
    </div>
  );
};


/* ==========================================================
   IMPERSONATION BANNER
   Shown across the app when the operator is viewing as a tenant.
   Reads/writes localStorage("mk-impersonate") so it survives reload.
   ========================================================== */
const ImpersonationBanner = ({ onExit }) => {
  const [name, setName] = useState(() => localStorage.getItem("mk-impersonate") || "");
  useEffect(() => {
    const h = () => setName(localStorage.getItem("mk-impersonate") || "");
    window.addEventListener("storage", h);
    window.addEventListener("mk-impersonate-changed", h);
    return () => { window.removeEventListener("storage", h); window.removeEventListener("mk-impersonate-changed", h); };
  }, []);
  if (!name) return null;
  return (
    <div className="impersonation-banner">
      <div className="row gap-2" style={{ flex: 1, minWidth: 0 }}>
        <Icon name="alert" size={14}/>
        <div style={{ fontSize: 13, fontWeight: 500, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          You're viewing as <b>{name}</b> · all actions are recorded in the audit log
        </div>
      </div>
      <button className="btn btn-sm" style={{ background: "rgba(255,255,255,.18)", color: "#fff", border: "1px solid rgba(255,255,255,.28)" }} onClick={onExit}>
        <Icon name="log-out" size={13}/> Stop impersonating
      </button>
    </div>
  );
};


/* ==========================================================
   LIVE OPS — real-time view of every active call across tenants.
   The bread-and-butter screen for operators on shift.
   ========================================================== */
const LIVE_CALLS = [
  { id: "c_8821", tenant: "Acme Dentistry", tenantId: "ten_acme", number: "+254 20 765 4110", caller: "+254 722 ••• 341", intent: "Book appointment", duration: 38, sentiment: "positive", agent: "Mikaka · v15", health: "ok", region: "nbo-1" },
  { id: "c_8822", tenant: "Twiga Foods",     tenantId: "ten_twiga",number: "+254 20 765 4212", caller: "+254 733 ••• 189", intent: "Order status",      duration: 64, sentiment: "neutral",  agent: "Mikaka · v22", health: "ok", region: "nbo-1" },
  { id: "c_8823", tenant: "Chipper Cash",    tenantId: "ten_chip", number: "+234 1 888 9012",   caller: "+234 80 ••• 4421",  intent: "Card help",         duration: 122,sentiment: "stressed", agent: "Mikaka · v8",  health: "degraded", region: "lag-1" },
  { id: "c_8824", tenant: "Sendy",           tenantId: "ten_sendy",number: "+254 20 765 4501", caller: "+254 711 ••• 902", intent: "Driver dispatch",   duration: 19, sentiment: "positive", agent: "Mikaka · v11", health: "ok", region: "nbo-1" },
  { id: "c_8825", tenant: "Acme Dentistry",  tenantId: "ten_acme", number: "+254 20 765 4110", caller: "+254 710 ••• 115", intent: "Pricing question",  duration: 8,  sentiment: "neutral",  agent: "Mikaka · v15", health: "ok", region: "nbo-1" },
  { id: "c_8826", tenant: "Chipper Cash",    tenantId: "ten_chip", number: "+234 1 888 9012",  caller: "+234 81 ••• 7720", intent: "Complaint",         duration: 201,sentiment: "negative", agent: "Mikaka · v8",  health: "ok", region: "lag-1" },
  { id: "c_8827", tenant: "Twiga Foods",     tenantId: "ten_twiga",number: "+254 20 765 4213", caller: "+254 700 ••• 552", intent: "Booking",           duration: 47, sentiment: "positive", agent: "Mikaka · v22", health: "ok", region: "nbo-1" },
];

const LiveOps = ({ onGo }) => {
  const [region, setRegion] = useState("all");
  const [watch, setWatch] = useState(null);
  const [tick, setTick] = useState(0);
  // Animate durations so the page feels alive.
  useEffect(() => { const h = setInterval(() => setTick(t => t + 1), 1000); return () => clearInterval(h); }, []);
  const regions = ["all", "nbo-1", "lag-1"];
  const rows = LIVE_CALLS.filter(c => region === "all" || c.region === region);
  const fmt = (s) => `${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, "0")}`;
  const watching = rows.find(c => c.id === watch);

  return (
    <div className="page page-mount">
      <WatchCallDrawer call={watching} tick={tick} onClose={() => setWatch(null)} onOpen={() => { onGo("admin-call-detail"); setWatch(null); }}/>
      <div className="page-header">
        <div>
          <div className="row gap-2" style={{ marginBottom: 8 }}>
            <Chip kind="live" dot>{rows.length} active</Chip>
            <Chip kind="accent">refreshing live</Chip>
          </div>
          <h1 className="page-title">Live operations</h1>
          <p className="page-sub">Every call in flight across all tenants. Click any row to watch the transcript in real time.</p>
        </div>
        <div className="row gap-2">
          <div className="seg">{regions.map(r => <button key={r} className={region === r ? "on" : ""} onClick={() => setRegion(r)}>{r}</button>)}</div>
          <button className="btn btn-outline btn-sm"><Icon name="refresh" size={13}/> Pause stream</button>
        </div>
      </div>

      <div className="grid grid-4 stagger" style={{ marginBottom: 24 }}>
        <OpsTile k="Active calls" v={rows.length} sub="across 4 tenants" icon="phone"/>
        <OpsTile k="Avg duration" v={fmt(Math.round(rows.reduce((s,r)=>s+r.duration,0) / rows.length))} sub="rolling" icon="clock"/>
        <OpsTile k="Trunk p95" v="142ms" sub="last 60s" tone="success" icon="zap"/>
        <OpsTile k="Distressed callers" v={rows.filter(c => c.sentiment === "stressed" || c.sentiment === "negative").length} sub="needs ear" tone="warn" icon="alert"/>
      </div>

      <div className="card">
        <div className="row between" style={{ padding: "14px 20px", borderBottom: "1px solid var(--border)" }}>
          <div style={{ fontSize: 14, fontWeight: 500 }}>In progress</div>
          <div className="row gap-2" style={{ fontSize: 12, color: "var(--fg-muted)" }}>
            <span className="live-dot"/> updated 1s ago
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>Call</th>
              <th>Tenant</th>
              <th>Caller → Number</th>
              <th>Intent</th>
              <th>Duration</th>
              <th>Sentiment</th>
              <th>Region</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {rows.map(c => (
              <tr key={c.id} style={{ cursor: "pointer" }} onClick={() => setWatch(c.id)}>
                <td className="mono cell-strong">
                  <div className="row gap-2"><span className="live-dot"/>{c.id}</div>
                </td>
                <td>{c.tenant}</td>
                <td className="mono" style={{ fontSize: 12 }}>{c.caller} → {c.number}</td>
                <td>{c.intent}</td>
                <td className="mono">{fmt(c.duration + tick)}</td>
                <td>
                  <span style={{ fontSize: 12.5, color: c.sentiment === "positive" ? "var(--mk-success)" : c.sentiment === "negative" || c.sentiment === "stressed" ? "var(--mk-danger)" : "var(--fg-muted)" }}>{c.sentiment}</span>
                </td>
                <td><Chip>{c.region}</Chip></td>
                <td><Icon name="chevron-right" size={14} style={{ color: "var(--fg-faint)" }}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

/* Side drawer that lets an operator watch a call in real-time */
const WatchCallDrawer = ({ call, tick, onClose, onOpen }) => {
  if (!call) return null;
  const lines = [
    { who: "agent",  t: "Acme Dentistry — how can I help?",                at: "0:01" },
    { who: "caller", t: "Hi, I'd like to book a cleaning for next week.", at: "0:05" },
    { who: "agent",  t: "Of course. Mornings or afternoons?",              at: "0:09" },
    { who: "caller", t: "Mornings please.",                                at: "0:14" },
    { who: "agent",  t: "I have Tuesday at 10am or Thursday at 9am.",      at: "0:18" },
  ];
  const fmt = (s) => `${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, "0")}`;
  return ReactDOM.createPortal(
    <div className="mk-drawer-backdrop" onClick={onClose}>
      <div className="mk-drawer" onClick={e => e.stopPropagation()} style={{ width: 520 }}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border)" }}>
          <div className="row between" style={{ marginBottom: 10 }}>
            <div className="row gap-2"><Chip kind="live" dot>live · {fmt(call.duration + tick)}</Chip><span className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>{call.id}</span></div>
            <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}><Icon name="x" size={14}/></button>
          </div>
          <div style={{ fontSize: 18, fontWeight: 500 }}>{call.intent}</div>
          <div style={{ fontSize: 13, color: "var(--fg-muted)", marginTop: 4 }}>{call.tenant} · {call.caller} → {call.number}</div>
        </div>
        <div style={{ padding: "16px 22px", borderBottom: "1px solid var(--border)" }}>
          <div className="row gap-3" style={{ padding: 12, background: "var(--bg-sunken)", borderRadius: 10 }}>
            <div className="wave" style={{ height: 26, gap: 2, flex: 1 }}>
              {Array.from({ length: 60 }).map((_, i) => (
                <span key={i} style={{ height: (8 + Math.abs(Math.sin((i + tick) * 0.6)) * 16) + "px", width: 2.5, background: "var(--mk-orange)", opacity: 0.7 + Math.abs(Math.sin((i + tick) * 0.4)) * 0.3, borderRadius: 2 }}/>
              ))}
            </div>
            <button className="btn btn-ghost btn-icon btn-sm" title="Mute audio"><Icon name="mic-off" size={13}/></button>
          </div>
        </div>
        <div style={{ flex: 1, overflow: "auto", padding: "18px 22px" }}>
          <div className="uppercase-kick" style={{ marginBottom: 10 }}>Transcript · streaming</div>
          <div className="stack gap-3">
            {lines.map((m, i) => (
              <div key={i} className="row gap-3" style={{ alignItems: "flex-start" }}>
                <div className="avatar" style={{ width: 26, height: 26, fontSize: 9, background: m.who === "agent" ? "var(--mk-orange)" : "var(--mk-ink)" }}>{m.who === "agent" ? "AI" : "C"}</div>
                <div style={{ flex: 1 }}>
                  <div className="row gap-2" style={{ marginBottom: 2 }}>
                    <span style={{ fontSize: 12, fontWeight: 500, color: m.who === "agent" ? "var(--mk-orange-600)" : "var(--fg)" }}>{m.who === "agent" ? "Mikaka" : "Caller"}</span>
                    <span className="mono" style={{ fontSize: 11, color: "var(--fg-faint)" }}>{m.at}</span>
                  </div>
                  <div style={{ fontSize: 13.5, lineHeight: 1.5 }}>{m.t}</div>
                </div>
              </div>
            ))}
            <div className="row gap-2" style={{ color: "var(--fg-muted)", fontSize: 12, fontStyle: "italic" }}>
              <span className="live-dot" style={{ background: "var(--mk-orange)" }}/> caller speaking…
            </div>
          </div>
        </div>
        <div style={{ padding: "14px 22px", borderTop: "1px solid var(--border)", display: "flex", gap: 8 }}>
          <button className="btn btn-outline btn-sm" style={{ flex: 1, justifyContent: "center" }} onClick={onOpen}><Icon name="external-link" size={13}/> Open full debug</button>
          <button className="btn btn-outline btn-sm" style={{ background: "rgba(208,69,58,.08)", color: "var(--mk-danger)", borderColor: "rgba(208,69,58,.25)" }}><Icon name="x" size={13}/> Force end</button>
        </div>
      </div>
    </div>,
    document.body
  );
};


/* ==========================================================
   CALLS GLOBAL — cross-tenant call browser with admin-only fields
   ========================================================== */
const CallsGlobal = ({ onGo }) => {
  const [q, setQ] = useState("");
  const [range, setRange] = useState("24h");
  const [outcome, setOutcome] = useState([]);
  const [tenant, setTenant] = useState([]);
  const rows = [
    { id: "c_8810", t: "Acme Dentistry", from: "+254 722 ••• 341", to: "+254 20 765 4110", intent: "Book appointment", outcome: "booked",     dur: "2:14", when: "8m ago",  cost: "$0.04", health: "ok" },
    { id: "c_8809", t: "Twiga Foods",    from: "+254 733 ••• 189", to: "+254 20 765 4212", intent: "Pricing",          outcome: "handled",    dur: "1:07", when: "24m ago", cost: "$0.02", health: "ok" },
    { id: "c_8808", t: "Chipper Cash",   from: "+234 80 ••• 4421",  to: "+234 1 888 9012", intent: "Card help",        outcome: "escalated",  dur: "3:08", when: "41m ago", cost: "$0.07", health: "warn" },
    { id: "c_8807", t: "Sendy",          from: "+254 711 ••• 902",  to: "+254 20 765 4501",intent: "Driver dispatch",  outcome: "booked",     dur: "0:48", when: "1h 02m",  cost: "$0.01", health: "ok" },
    { id: "c_8806", t: "Acme Dentistry", from: "+254 710 ••• 885",  to: "+254 20 765 4110",intent: "Hours",            outcome: "handled",    dur: "0:58", when: "1h 41m",  cost: "$0.02", health: "ok" },
    { id: "c_8805", t: "Java House",     from: "+254 705 ••• 712",  to: "+254 20 765 4801",intent: "Complaint",        outcome: "escalated",  dur: "3:42", when: "2h 11m",  cost: "$0.09", health: "warn" },
    { id: "c_8804", t: "Chipper Cash",   from: "+234 81 ••• 7720",  to: "+234 1 888 9012", intent: "Card help",        outcome: "missed",     dur: "0:08", when: "2h 30m",  cost: "$0.00", health: "down" },
    { id: "c_8803", t: "Twiga Foods",    from: "+254 700 ••• 552",  to: "+254 20 765 4213",intent: "Booking",          outcome: "booked",     dur: "1:24", when: "2h 55m",  cost: "$0.03", health: "ok" },
  ];
  const f = rows.filter(r =>
    (q === "" || r.from.includes(q) || r.to.includes(q) || r.t.toLowerCase().includes(q.toLowerCase()) || r.id.includes(q))
    && (outcome.length === 0 || outcome.includes(r.outcome))
    && (tenant.length === 0 || tenant.includes(r.t))
  );

  return (
    <div className="page page-mount">
      <div className="page-header">
        <div>
          <h1 className="page-title">All calls</h1>
          <p className="page-sub">Every call across every tenant — filterable for triage and audit.</p>
        </div>
        <div className="row gap-2">
          <button className="btn btn-outline"><Icon name="download"/> Export CSV</button>
          <button className="btn btn-primary"><Icon name="search"/> Saved searches</button>
        </div>
      </div>

      <div className="grid grid-4 stagger" style={{ marginBottom: 20 }}>
        <OpsTile k="Calls · 24h" v="4,128" sub="6% vs prior" tone="success"/>
        <OpsTile k="Answer rate" v="98.4%" sub="0.2 pt"     tone="success"/>
        <OpsTile k="Escalations" v="142"   sub="3.4%"/>
        <OpsTile k="Missed (carrier)" v="14" sub="0.34% — Lagos region" tone="warn"/>
      </div>

      <div className="row gap-3" style={{ marginBottom: 16, flexWrap: "wrap" }}>
        <div className="seg">{["1h","24h","7d","30d","Custom"].map(r => <button key={r} className={range === r ? "on" : ""} onClick={() => setRange(r)}>{r}</button>)}</div>
        <div style={{ flex: 1, maxWidth: 360, position: "relative" }}>
          <Icon name="search" size={14} style={{ position: "absolute", left: 12, top: 11, color: "var(--fg-faint)" }}/>
          <input className="input" placeholder="Search by tenant, number, call id…" style={{ paddingLeft: 34 }} value={q} onChange={e => setQ(e.target.value)}/>
        </div>
        <FilterMenu label="Tenant"  options={["Acme Dentistry","Twiga Foods","Chipper Cash","Sendy","Java House","Kopo Kopo"]} selected={tenant}  onChange={setTenant}/>
        <FilterMenu label="Outcome" options={["booked","handled","escalated","missed"]} selected={outcome} onChange={setOutcome}/>
      </div>

      <div className="card">
        <table className="tbl">
          <thead>
            <tr>
              <th>Call</th>
              <th>Tenant</th>
              <th>From → To</th>
              <th>Intent</th>
              <th>Outcome</th>
              <th>Duration</th>
              <th>Cost</th>
              <th>Health</th>
              <th>Time</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {f.map(r => (
              <tr key={r.id} style={{ cursor: "pointer" }} onClick={() => onGo("admin-call-detail")}>
                <td className="mono cell-strong">{r.id}</td>
                <td>{r.t}</td>
                <td className="mono" style={{ fontSize: 12 }}>{r.from} → {r.to}</td>
                <td>{r.intent}</td>
                <td><Chip kind={r.outcome === "booked" ? "live" : r.outcome === "escalated" ? "warn" : r.outcome === "missed" ? "danger" : "accent"} dot>{r.outcome}</Chip></td>
                <td className="mono">{r.dur}</td>
                <td className="mono" style={{ color: "var(--fg-muted)" }}>{r.cost}</td>
                <td>
                  <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 999, background: r.health === "ok" ? "var(--mk-success)" : r.health === "warn" ? "var(--mk-warning)" : "var(--mk-danger)" }}/>
                </td>
                <td style={{ color: "var(--fg-muted)" }}>{r.when}</td>
                <td><Icon name="chevron-right" size={14} style={{ color: "var(--fg-faint)" }}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};


/* ==========================================================
   ADMIN CALL DETAIL — debug-rail variant of the tenant call page
   Includes media metrics, AI step trace, SIP frames, raw events
   ========================================================== */
const AdminCallDetail = ({ onGo }) => {
  const [tab, setTab] = useState("transcript");
  return (
    <div className="page page-mount">
      <div className="row gap-2" style={{ marginBottom: 12, fontSize: 13, color: "var(--fg-muted)" }}>
        <a className="dot-link" onClick={() => onGo("calls-global")}>All calls</a> / <span className="mono">c_8808</span>
      </div>
      <div className="page-header">
        <div>
          <div className="row gap-3" style={{ marginBottom: 6 }}>
            <Chip kind="warn" dot>escalated</Chip>
            <span className="mono cell-strong" style={{ fontSize: 16 }}>+234 80 ••• 4421 → +234 1 888 9012</span>
            <span style={{ fontSize: 13, color: "var(--fg-muted)" }}>Chipper Cash · 41m ago · 3:08</span>
          </div>
          <h1 className="page-title">Card help → human transfer</h1>
        </div>
        <div className="row gap-2">
          <button className="btn btn-outline"><Icon name="download"/> Recording</button>
          <button className="btn btn-outline"><Icon name="copy"/> Copy call id</button>
          <button className="btn btn-primary">Actions <Icon name="chevron-down"/></button>
        </div>
      </div>

      {/* Quick metrics */}
      <div className="grid grid-4 stagger" style={{ marginBottom: 24 }}>
        <OpsTile k="Trunk RTT" v="148ms" sub="p95 · ok"          tone="success"/>
        <OpsTile k="STT latency" v="320ms" sub="p95 baseline 210"/>
        <OpsTile k="TTS latency" v="612ms" sub="p95 ↑ 60% vs baseline" tone="warn"/>
        <OpsTile k="Audio loss" v="2.1%"  sub="caller side · slight"   tone="warn"/>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "minmax(0, 2fr) minmax(0, 1fr)", gap: 20 }}>
        <div className="card">
          <div className="row" style={{ borderBottom: "1px solid var(--border)", padding: "0 16px" }}>
            {["transcript","ai-trace","media","sip","events","raw"].map(t => (
              <button key={t} onClick={() => setTab(t)} style={{ padding: "12px 14px", border: 0, background: "transparent", fontSize: 13, color: tab === t ? "var(--fg)" : "var(--fg-muted)", fontWeight: tab === t ? 500 : 400, borderBottom: "2px solid " + (tab === t ? "var(--mk-orange)" : "transparent"), marginBottom: -1, cursor: "pointer", textTransform: "capitalize" }}>{t.replace("-"," ")}</button>
            ))}
          </div>

          {tab === "transcript" && <DebugTranscript/>}
          {tab === "ai-trace"   && <DebugAITrace/>}
          {tab === "media"      && <DebugMedia/>}
          {tab === "sip"        && <DebugSIP/>}
          {tab === "events"     && <DebugEvents/>}
          {tab === "raw"        && <DebugRaw/>}
        </div>

        <div className="stack gap-4">
          <div className="card card-pad">
            <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 12 }}>Routing path</div>
            <div className="stack gap-2" style={{ fontSize: 12.5 }}>
              {[
                ["Carrier",     "Africa's Talking · NG"],
                ["Trunk IP",    "102.89.1.44"],
                ["Codec",       "OPUS · 16kHz"],
                ["Region",      "lag-1"],
                ["LK room",     "lk_chip_ng_8808"],
                ["Agent build", "Mikaka · v8 (built 14h ago)"],
              ].map(([k,v]) => (
                <div key={k} style={{ display: "grid", gridTemplateColumns: "92px 1fr", gap: 12, alignItems: "baseline" }}>
                  <span style={{ color: "var(--fg-muted)", whiteSpace: "nowrap" }}>{k}</span>
                  <span className="mono" style={{ fontSize: 12, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{v}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="card card-pad">
            <div className="row between" style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>What went wrong</div>
              <Chip kind="warn">2 issues</Chip>
            </div>
            <div className="stack gap-2" style={{ fontSize: 12.5 }}>
              <div style={{ padding: 10, background: "rgba(224,148,0,.08)", borderRadius: 8, border: "1px solid rgba(224,148,0,.18)" }}>
                <div style={{ fontWeight: 500, color: "var(--mk-warning)", marginBottom: 4 }}>TTS slow on second utterance</div>
                <div style={{ color: "var(--fg-muted)" }}>612ms vs baseline 380ms. Provider returned warning header.</div>
              </div>
              <div style={{ padding: 10, background: "rgba(208,69,58,.06)", borderRadius: 8, border: "1px solid rgba(208,69,58,.18)" }}>
                <div style={{ fontWeight: 500, color: "var(--mk-danger)", marginBottom: 4 }}>HubSpot webhook 503</div>
                <div style={{ color: "var(--fg-muted)" }}>Contact create failed, retried 3× then deferred.</div>
              </div>
            </div>
          </div>

          <div className="card card-pad">
            <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 10 }}>Quick actions</div>
            <div className="stack gap-2" style={{ fontSize: 13 }}>
              <button className="btn btn-outline btn-sm" style={{ width: "100%", justifyContent: "flex-start" }}><Icon name="zap" size={13}/> Re-run AI on transcript</button>
              <button className="btn btn-outline btn-sm" style={{ width: "100%", justifyContent: "flex-start" }}><Icon name="phone" size={13}/> Place test call to same number</button>
              <button className="btn btn-outline btn-sm" style={{ width: "100%", justifyContent: "flex-start" }}><Icon name="external-link" size={13}/> Open in Africa's Talking</button>
              <button className="btn btn-outline btn-sm" style={{ width: "100%", justifyContent: "flex-start" }}><Icon name="alert" size={13}/> Flag for review</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const DebugTranscript = () => (
  <div className="stack gap-3" style={{ padding: 20 }}>
    {[
      { who: "agent",  t: "Chipper Cash — how can I help?",            at: "0:01" },
      { who: "caller", t: "My card was blocked, can you help me unblock it?", at: "0:05" },
      { who: "agent",  t: "I'm sorry to hear that. Can you share the last 4 digits?", at: "0:11" },
      { who: "caller", t: "Four four one one.",                          at: "0:18" },
      { who: "agent",  t: "Thanks. I can see two declined attempts overnight — let me transfer you to a human agent who can verify your identity.", at: "0:24" },
      { who: "caller", t: "OK thank you.",                               at: "0:32" },
      { who: "system", t: "Transfer initiated → +234 800 555 0142",     at: "0:35" },
    ].map((m, i) => (
      <div key={i} className="row gap-3" style={{ alignItems: "flex-start" }}>
        <div className="avatar" style={{ width: 26, height: 26, fontSize: 9, background: m.who === "agent" ? "var(--mk-orange)" : m.who === "system" ? "var(--mk-slate-500)" : "var(--mk-ink)" }}>{m.who === "agent" ? "AI" : m.who === "system" ? "·" : "C"}</div>
        <div style={{ flex: 1 }}>
          <div className="row gap-2" style={{ marginBottom: 2 }}>
            <span style={{ fontSize: 12, fontWeight: 500, color: m.who === "agent" ? "var(--mk-orange-600)" : m.who === "system" ? "var(--fg-muted)" : "var(--fg)" }}>{m.who === "agent" ? "Mikaka" : m.who === "system" ? "system" : "Caller"}</span>
            <span className="mono" style={{ fontSize: 11, color: "var(--fg-faint)" }}>{m.at}</span>
          </div>
          <div style={{ fontSize: 13.5, lineHeight: 1.55 }}>{m.t}</div>
        </div>
      </div>
    ))}
  </div>
);

const DebugAITrace = () => (
  <div className="stack gap-2" style={{ padding: 20 }}>
    {[
      { step: "intent.classify", in: "My card was blocked, can you help me unblock it?", out: "card.unblock (conf 0.92)", ms: 240, ok: true },
      { step: "policy.check",    in: "card.unblock",                                     out: "requires.human · pii=last4",  ms: 8,   ok: true },
      { step: "tts.synthesize",  in: "I'm sorry to hear that…",                          out: "audio · 612ms",                ms: 612, ok: false, note: "above p95" },
      { step: "stt.transcribe",  in: "audio chunk 1",                                    out: "Four four one one.",           ms: 320, ok: true },
      { step: "tool.lookup_card",in: "{ last4: '4411' }",                                out: "2 declined attempts, status=blocked", ms: 156, ok: true },
      { step: "policy.escalate", in: "card.unblock + verified.pii",                      out: "transfer → +234 800 555 0142", ms: 12,  ok: true },
      { step: "webhook.hubspot.contact_upsert", in: "{ phone, intent }",                 out: "503 Service unavailable",      ms: 412, ok: false, note: "3 retries · deferred" },
    ].map((s, i) => (
      <div key={i} style={{ display: "grid", gridTemplateColumns: "200px 1fr 80px 16px", gap: 12, alignItems: "center", padding: 10, background: "var(--bg-sunken)", borderRadius: 8, borderLeft: "3px solid " + (s.ok ? "var(--mk-success)" : "var(--mk-warning)") }}>
        <div className="mono" style={{ fontSize: 12, fontWeight: 500 }}>{s.step}</div>
        <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>
          <div><span style={{ color: "var(--fg-faint)" }}>in:</span>  <span className="mono">{s.in}</span></div>
          <div><span style={{ color: "var(--fg-faint)" }}>out:</span> <span className="mono">{s.out}</span></div>
          {s.note && <div style={{ color: s.ok ? "var(--fg-muted)" : "var(--mk-warning)", fontStyle: "italic" }}>↳ {s.note}</div>}
        </div>
        <div className="mono" style={{ fontSize: 12, textAlign: "right", color: "var(--fg-muted)" }}>{s.ms}ms</div>
        <Icon name={s.ok ? "check" : "alert"} size={13} style={{ color: s.ok ? "var(--mk-success)" : "var(--mk-warning)" }}/>
      </div>
    ))}
  </div>
);

const DebugMedia = () => (
  <div className="stack gap-4" style={{ padding: 20 }}>
    <div>
      <div className="uppercase-kick" style={{ marginBottom: 10 }}>RTP jitter · ms (caller side)</div>
      <div className="bars" style={{ height: 110 }}>
        {[12,9,11,8,14,18,22,16,12,10,9,11,28,32,18,12,10,9,8,11,9,10,12,14].map((v,i) => (
          <div key={i} className="b" style={{ background: v > 25 ? "var(--mk-warning)" : v > 18 ? "var(--mk-warning)" : "var(--mk-orange)" }}/>
        ))}
      </div>
    </div>
    <div className="grid grid-2 gap-4">
      <div>
        <div className="uppercase-kick" style={{ marginBottom: 10 }}>Packet loss</div>
        <div className="num" style={{ fontSize: 28, color: "var(--mk-warning)" }}>2.1%</div>
        <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>peaks at 0:34 (caller WiFi handoff?)</div>
      </div>
      <div>
        <div className="uppercase-kick" style={{ marginBottom: 10 }}>MOS score</div>
        <div className="num" style={{ fontSize: 28 }}>3.8</div>
        <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>borderline · target ≥ 4.0</div>
      </div>
    </div>
    <CodeBlock label="Codec negotiation">{`m=audio 49170 RTP/AVP 96 0 8
a=rtpmap:96 opus/16000/2
a=rtpmap:0  PCMU/8000
a=fmtp:96 useinbandfec=1; maxaveragebitrate=24000
selected: OPUS @ 16kHz`}</CodeBlock>
  </div>
);

const DebugSIP = () => (
  <div style={{ padding: 20 }}>
    <CodeBlock label="SIP signalling — abridged">{`14:08:01.412  → INVITE sip:+2348005550142@trunk.at SIP/2.0
14:08:01.480  ← 100 Trying
14:08:01.612  ← 180 Ringing
14:08:03.211  ← 200 OK (codec OPUS/16k)
14:08:03.214  → ACK
14:08:03.214  Session established (call-id c_8808)
14:11:09.901  → BYE
14:11:09.972  ← 200 OK
14:11:09.974  Session terminated · reason=normal_clearing`}</CodeBlock>
  </div>
);

const DebugEvents = () => (
  <div style={{ padding: 0 }}>
    <table className="tbl">
      <thead><tr><th>t+</th><th>Event</th><th>Source</th><th>Payload</th></tr></thead>
      <tbody>
        {[
          ["0.00", "call.received",          "africas-talking", "{ from: '+234 80…' }"],
          ["0.02", "session.allocate",       "livekit",         "room=lk_chip_ng_8808"],
          ["0.04", "agent.spawn",            "core",            "build=v8"],
          ["0.05", "tts.start",              "core",            "greeting"],
          ["0.18", "stt.partial",            "stt-provider",    '"my card was blocked"'],
          ["1.24", "tool.lookup_card",       "core",            "last4=4411"],
          ["1.41", "webhook.delivered",      "hubspot",         "503 retry=1"],
          ["3.08", "transfer.initiated",     "core",            "→+234 800 555 0142"],
          ["3.08", "call.ended",             "core",            "reason=escalated"],
        ].map((r, i) => (
          <tr key={i}><td className="mono" style={{ fontSize: 12 }}>{r[0]}</td><td className="cell-strong" style={{ fontSize: 13 }}>{r[1]}</td><td className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>{r[2]}</td><td className="mono" style={{ fontSize: 12 }}>{r[3]}</td></tr>
        ))}
      </tbody>
    </table>
  </div>
);

const DebugRaw = () => (
  <div style={{ padding: 20 }}>
    <CodeBlock label="GET /admin/calls/c_8808">{`{
  "id": "c_8808",
  "tenant_id": "ten_chip",
  "from": "+2348012344421",
  "to":   "+23418889012",
  "started_at": "2026-11-14T14:08:01.412Z",
  "ended_at":   "2026-11-14T14:11:09.974Z",
  "duration_s": 188,
  "carrier": "africas-talking",
  "trunk_ip": "102.89.1.44",
  "codec":    "opus/16000",
  "agent":    { "build": "v8", "model": "claude-haiku-4-5" },
  "outcome":  "escalated",
  "sentiment":"negative",
  "cost_usd": 0.07,
  "media": { "rtt_ms_p95": 148, "loss_pct": 2.1, "mos": 3.8 },
  "issues": [
    { "level": "warn",  "code": "tts.slow",       "ms": 612 },
    { "level": "error", "code": "webhook.503",    "target": "hubspot" }
  ]
}`}</CodeBlock>
  </div>
);


/* ==========================================================
   SYSTEM HEALTH — full status page
   ========================================================== */
const SystemHealth = () => {
  // 60 buckets of 1m each
  const ok = Array.from({ length: 60 }).map(() => 0);
  const ttsTimeline = ok.map((_, i) => (i > 48 && i < 52 ? 1 : 0));
  const mpesaTimeline = ok.map((_, i) => (i > 38 && i < 42 ? 2 : i > 42 && i < 48 ? 1 : 0));
  const services = [
    { name: "Africa's Talking · KE trunk", p95: "142ms", uptime: "100.0%", region: "nbo-1", status: "ok",       tl: ok },
    { name: "Africa's Talking · NG trunk", p95: "168ms", uptime: "99.92%", region: "lag-1", status: "ok",       tl: ok },
    { name: "Livekit media",               p95: "89ms",  uptime: "100.0%", region: "global", status: "ok",      tl: ok },
    { name: "STT provider",                p95: "210ms", uptime: "99.99%", region: "global", status: "ok",      tl: ok },
    { name: "TTS provider",                p95: "412ms", uptime: "99.82%", region: "global", status: "degraded",tl: ttsTimeline, note: "elevated latency · provider notified" },
    { name: "M-Pesa Daraja",               p95: "—",     uptime: "98.21%", region: "ke",    status: "warn",     tl: mpesaTimeline, note: "intermittent timeouts since 14:32 UTC" },
    { name: "Supabase (primary)",          p95: "42ms",  uptime: "100.0%", region: "eu-west-1", status: "ok",   tl: ok },
    { name: "Webhook dispatcher",          p95: "184ms", uptime: "99.96%", region: "global", status: "ok",      tl: ok },
  ];
  const tone = (s) => s === "ok" ? "var(--mk-success)" : s === "degraded" || s === "warn" ? "var(--mk-warning)" : "var(--mk-danger)";

  return (
    <div className="page page-mount">
      <div className="page-header">
        <div>
          <div className="row gap-2" style={{ marginBottom: 8 }}><Chip kind="warn" dot>2 systems degraded</Chip></div>
          <h1 className="page-title">System health</h1>
          <p className="page-sub">Service status, latency, and the last 60 minutes — at a glance.</p>
        </div>
        <div className="row gap-2">
          <button className="btn btn-outline btn-sm"><Icon name="refresh" size={13}/> Refresh</button>
          <button className="btn btn-outline btn-sm"><Icon name="external-link" size={13}/> Public status</button>
        </div>
      </div>

      <div className="grid grid-4 stagger" style={{ marginBottom: 24 }}>
        <OpsTile k="Trunk success" v="99.91%" sub="rolling 24h" tone="success"/>
        <OpsTile k="Active calls"  v="7"      sub="across 2 regions"/>
        <OpsTile k="Open incidents" v="1"     sub="M-Pesa degraded"  tone="warn"/>
        <OpsTile k="Webhook backlog" v="48"   sub="oldest 4m"/>
      </div>

      <div className="card" style={{ marginBottom: 20 }}>
        <div style={{ padding: "14px 20px", borderBottom: "1px solid var(--border)", fontSize: 14, fontWeight: 500 }}>Services · last 60 min</div>
        <div style={{ padding: "8px 20px 20px" }}>
          {services.map((s, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 90px 80px 1fr 24px", gap: 16, alignItems: "center", padding: "12px 0", borderBottom: i < services.length - 1 ? "1px solid var(--border)" : 0 }}>
              <div>
                <div className="row gap-2" style={{ fontSize: 14 }}><span style={{ width: 8, height: 8, borderRadius: 99, background: tone(s.status) }}/>{s.name}</div>
                {s.note && <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 2, marginLeft: 16 }}>{s.note}</div>}
              </div>
              <div className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>{s.p95}</div>
              <div className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>{s.uptime}</div>
              <HealthTimeline data={s.tl} color={tone(s.status)}/>
              <Icon name="chevron-right" size={14} style={{ color: "var(--fg-faint)" }}/>
            </div>
          ))}
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 20 }}>
        <div className="card card-pad">
          <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 12 }}>Regions</div>
          <div className="stack gap-2" style={{ fontSize: 13 }}>
            {[["nbo-1","Nairobi · KE","ok","4 active calls"],["lag-1","Lagos · NG","warn","M-Pesa unavailable in region"],["eu-west-1","Frankfurt · core","ok","primary DB"]].map(([id,n,st,sub]) => (
              <div key={id} className="row between" style={{ padding: 12, background: "var(--bg-sunken)", borderRadius: 10 }}>
                <div>
                  <div className="row gap-2"><span style={{ width: 8, height: 8, borderRadius: 99, background: tone(st) }}/><span style={{ fontWeight: 500 }}>{n}</span></div>
                  <div className="mono" style={{ fontSize: 11.5, color: "var(--fg-muted)", marginLeft: 16, marginTop: 2 }}>{id} · {sub}</div>
                </div>
                <Chip kind={st === "ok" ? "live" : "warn"} dot>{st}</Chip>
              </div>
            ))}
          </div>
        </div>
        <div className="card card-pad">
          <div className="row between" style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 14, fontWeight: 500 }}>Recent incidents</div>
            <a className="dot-link" style={{ fontSize: 12.5 }}>All incidents →</a>
          </div>
          <div className="stack gap-2" style={{ fontSize: 13 }}>
            {[
              ["INC-2026-014", "M-Pesa Daraja intermittent timeouts", "investigating", "8m"],
              ["INC-2026-013", "TTS provider elevated latency",       "monitoring",    "1h"],
              ["INC-2026-012", "Lagos trunk packet loss (resolved)",  "resolved",      "yesterday"],
            ].map(([id, t, st, when]) => (
              <div key={id} style={{ padding: 12, background: "var(--bg-sunken)", borderRadius: 10 }}>
                <div className="row between" style={{ marginBottom: 4 }}>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 500 }}>{id}</span>
                  <Chip kind={st === "resolved" ? "live" : st === "monitoring" ? "accent" : "warn"} dot>{st}</Chip>
                </div>
                <div style={{ fontSize: 13 }}>{t}</div>
                <div style={{ fontSize: 11.5, color: "var(--fg-muted)", marginTop: 2 }}>opened {when} ago</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};


/* ==========================================================
   WEBHOOKS LOG — integration delivery debugger
   ========================================================== */
const WebhooksLog = () => {
  const [tenant, setTenant] = useState([]);
  const [status, setStatus] = useState([]);
  const [integration, setIntegration] = useState([]);
  const [selected, setSelected] = useState(null);

  const deliveries = [
    { id: "whk_8841", tenant: "Chipper Cash",   integration: "HubSpot",         event: "call.ended",       url: "https://hubapi.com/contacts/v3/upsert",    code: 503, ms: 412, when: "4m ago",  attempts: 3, ok: false },
    { id: "whk_8840", tenant: "Acme Dentistry", integration: "Google Calendar", event: "booking.created",  url: "https://www.googleapis.com/calendar/v3…",  code: 200, ms: 184, when: "8m ago",  attempts: 1, ok: true },
    { id: "whk_8839", tenant: "Twiga Foods",    integration: "Slack",           event: "call.escalated",   url: "https://hooks.slack.com/services/T0…",     code: 200, ms: 91,  when: "12m ago", attempts: 1, ok: true },
    { id: "whk_8838", tenant: "Acme Dentistry", integration: "M-Pesa",          event: "payment.requested",url: "https://sandbox.safaricom.co.ke/mpesa/…",  code: 408, ms: 30000, when: "18m ago", attempts: 2, ok: false },
    { id: "whk_8837", tenant: "Sendy",          integration: "Webhook",         event: "call.ended",       url: "https://api.sendy.co.ke/voice/events",     code: 200, ms: 142, when: "22m ago", attempts: 1, ok: true },
    { id: "whk_8836", tenant: "Java House",     integration: "Zapier",          event: "call.ended",       url: "https://hooks.zapier.com/…",                code: 200, ms: 220, when: "31m ago", attempts: 1, ok: true },
    { id: "whk_8835", tenant: "Chipper Cash",   integration: "HubSpot",         event: "call.ended",       url: "https://hubapi.com/contacts/v3/upsert",    code: 503, ms: 408, when: "42m ago", attempts: 3, ok: false },
  ];
  const f = deliveries.filter(d =>
    (tenant.length === 0 || tenant.includes(d.tenant))
    && (integration.length === 0 || integration.includes(d.integration))
    && (status.length === 0 || (status.includes("success") && d.ok) || (status.includes("failed") && !d.ok))
  );

  return (
    <div className="page page-mount">
      <WebhookDetailDrawer delivery={selected} onClose={() => setSelected(null)}/>
      <div className="page-header">
        <div>
          <h1 className="page-title">Webhooks & deliveries</h1>
          <p className="page-sub">Every outbound webhook fired by tenant integrations — with payloads, response codes, and a one-click replay.</p>
        </div>
        <div className="row gap-2">
          <button className="btn btn-outline btn-sm"><Icon name="download" size={13}/> Export</button>
          <button className="btn btn-outline btn-sm"><Icon name="refresh" size={13}/> Retry failed</button>
        </div>
      </div>

      <div className="grid grid-4 stagger" style={{ marginBottom: 20 }}>
        <OpsTile k="Deliveries · 24h" v="3,841"  sub="across 14 endpoints"/>
        <OpsTile k="Success rate"      v="97.4%" sub="0.3 pt"  tone="success"/>
        <OpsTile k="Failed · 24h"      v="98"    sub="HubSpot ↑" tone="warn"/>
        <OpsTile k="P95 latency"       v="184ms" sub="ok"/>
      </div>

      <div className="row gap-3" style={{ marginBottom: 16, flexWrap: "wrap" }}>
        <FilterMenu label="Tenant"      options={["Acme Dentistry","Twiga Foods","Chipper Cash","Sendy","Java House"]} selected={tenant} onChange={setTenant}/>
        <FilterMenu label="Integration" options={["HubSpot","Google Calendar","Slack","M-Pesa","Webhook","Zapier"]} selected={integration} onChange={setIntegration}/>
        <FilterMenu label="Status"      options={["success","failed"]} selected={status} onChange={setStatus}/>
      </div>

      <div className="card">
        <table className="tbl">
          <thead>
            <tr>
              <th>Delivery</th>
              <th>Tenant</th>
              <th>Integration</th>
              <th>Event</th>
              <th>Code</th>
              <th>Latency</th>
              <th>Attempts</th>
              <th>Time</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {f.map(d => (
              <tr key={d.id} style={{ cursor: "pointer" }} onClick={() => setSelected(d)}>
                <td className="mono cell-strong">{d.id}</td>
                <td>{d.tenant}</td>
                <td>{d.integration}</td>
                <td className="mono" style={{ fontSize: 12 }}>{d.event}</td>
                <td><Chip kind={d.ok ? "live" : "danger"} dot>{d.code}</Chip></td>
                <td className="mono" style={{ color: d.ms > 1000 ? "var(--mk-warning)" : "var(--fg)" }}>{d.ms >= 1000 ? (d.ms / 1000).toFixed(1) + "s" : d.ms + "ms"}</td>
                <td className="mono">{d.attempts}</td>
                <td style={{ color: "var(--fg-muted)" }}>{d.when}</td>
                <td><Icon name="chevron-right" size={14} style={{ color: "var(--fg-faint)" }}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

const WebhookDetailDrawer = ({ delivery, onClose }) => {
  if (!delivery) return null;
  return ReactDOM.createPortal(
    <div className="mk-drawer-backdrop" onClick={onClose}>
      <div className="mk-drawer" onClick={e => e.stopPropagation()} style={{ width: 560 }}>
        <div style={{ padding: "16px 22px", borderBottom: "1px solid var(--border)" }}>
          <div className="row between" style={{ marginBottom: 8 }}>
            <div className="row gap-2"><Chip kind={delivery.ok ? "live" : "danger"} dot>{delivery.code}</Chip><span className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>{delivery.id}</span></div>
            <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}><Icon name="x" size={14}/></button>
          </div>
          <div style={{ fontSize: 16, fontWeight: 500 }}>{delivery.event} → {delivery.integration}</div>
          <div style={{ fontSize: 12.5, color: "var(--fg-muted)", marginTop: 2 }}>{delivery.tenant} · {delivery.when} · {delivery.attempts} attempt{delivery.attempts > 1 ? "s" : ""}</div>
        </div>
        <div style={{ flex: 1, overflow: "auto", padding: "18px 22px" }}>
          <div className="stack gap-4">
            <div>
              <div className="uppercase-kick" style={{ marginBottom: 6 }}>Target</div>
              <CodeBlock>{`POST ${delivery.url}`}</CodeBlock>
            </div>
            <div>
              <div className="uppercase-kick" style={{ marginBottom: 6 }}>Request</div>
              <CodeBlock>{`Content-Type: application/json
X-Mikaka-Signature: t=1731585601,v1=8a3c…

{
  "event": "${delivery.event}",
  "tenant_id": "ten_chip",
  "call_id": "c_8808",
  "data": {
    "from": "+234801…4421",
    "intent": "card.unblock",
    "outcome": "escalated"
  }
}`}</CodeBlock>
            </div>
            <div>
              <div className="uppercase-kick" style={{ marginBottom: 6 }}>Response · {delivery.code}</div>
              <CodeBlock>{delivery.ok
                ? `HTTP/1.1 200 OK
content-type: application/json

{"received":true}`
                : `HTTP/1.1 ${delivery.code} ${delivery.code === 503 ? "Service Unavailable" : "Request Timeout"}
content-type: text/html

<html><body>upstream connect error</body></html>`}</CodeBlock>
            </div>
            <div>
              <div className="uppercase-kick" style={{ marginBottom: 6 }}>Attempt timeline</div>
              <div className="stack gap-2" style={{ fontSize: 12.5 }}>
                {Array.from({ length: delivery.attempts }).map((_, i) => (
                  <div key={i} className="row between" style={{ padding: 10, background: "var(--bg-sunken)", borderRadius: 8 }}>
                    <span className="mono">attempt {i + 1}</span>
                    <span style={{ color: i === delivery.attempts - 1 && delivery.ok ? "var(--mk-success)" : "var(--mk-danger)" }}>{i === delivery.attempts - 1 && delivery.ok ? delivery.code + " ok" : (i === 0 ? delivery.code : "503") + " failed"}</span>
                    <span className="mono" style={{ color: "var(--fg-muted)" }}>{delivery.ms}ms</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
        <div style={{ padding: "14px 22px", borderTop: "1px solid var(--border)", display: "flex", gap: 8 }}>
          <button className="btn btn-outline btn-sm" style={{ flex: 1, justifyContent: "center" }}><Icon name="copy" size={13}/> Copy payload</button>
          <button className="btn btn-accent btn-sm" style={{ flex: 1, justifyContent: "center" }}><Icon name="refresh" size={13}/> Replay delivery</button>
        </div>
      </div>
    </div>,
    document.body
  );
};


/* ==========================================================
   INCIDENTS — open ops tickets + on-call view
   ========================================================== */
const Incidents = () => {
  const [status, setStatus] = useState("open");
  const items = [
    { id: "INC-2026-014", t: "M-Pesa Daraja intermittent timeouts",       sev: "high",   status: "investigating", owner: "Frank · ops", opened: "8m ago",  affected: "2 tenants" },
    { id: "INC-2026-013", t: "TTS provider elevated latency",              sev: "medium", status: "monitoring",    owner: "Joyce · sre", opened: "1h 12m",  affected: "all tenants" },
    { id: "INC-2026-011", t: "Tenant 'Java House' billing dispute",        sev: "low",    status: "open",          owner: "—",          opened: "4h",      affected: "1 tenant" },
    { id: "INC-2026-010", t: "Outbound campaign stuck — Twiga Foods",      sev: "medium", status: "open",          owner: "Ops queue",   opened: "yesterday", affected: "1 tenant" },
    { id: "INC-2026-012", t: "Lagos trunk packet loss",                    sev: "high",   status: "resolved",      owner: "Frank · ops", opened: "yesterday", affected: "all NG tenants" },
  ];
  const list = items.filter(i => status === "all" || (status === "open" ? i.status !== "resolved" : i.status === status));
  const sevTone = (s) => s === "high" ? "danger" : s === "medium" ? "warn" : "neutral";

  return (
    <div className="page page-mount">
      <div className="page-header">
        <div>
          <h1 className="page-title">Incidents</h1>
          <p className="page-sub">Open ops work, ownership, and on-call rotation.</p>
        </div>
        <div className="row gap-2">
          <button className="btn btn-outline btn-sm"><Icon name="external-link" size={13}/> PagerDuty</button>
          <button className="btn btn-accent"><Icon name="plus"/> New incident</button>
        </div>
      </div>

      <div className="grid grid-4 stagger" style={{ marginBottom: 24 }}>
        <OpsTile k="Open"           v="4"     sub="2 high severity" tone="warn"/>
        <OpsTile k="MTTR · 7d"      v="32m"   sub="-12m vs prior"   tone="success"/>
        <OpsTile k="Affected tenants" v="3"  sub="of 24 active"/>
        <OpsTile k="On call"        v="Frank" sub="until 6pm UTC"/>
      </div>

      <div className="row gap-3" style={{ marginBottom: 16 }}>
        <div className="seg">
          {["open","investigating","monitoring","resolved","all"].map(s => (
            <button key={s} className={status === s ? "on" : ""} onClick={() => setStatus(s)} style={{ textTransform: "capitalize" }}>{s}</button>
          ))}
        </div>
      </div>

      <div className="stack gap-3">
        {list.map(i => (
          <div key={i.id} className="card card-pad">
            <div className="row between" style={{ marginBottom: 8 }}>
              <div className="row gap-3">
                <span className="mono" style={{ fontSize: 12, fontWeight: 500, color: "var(--fg-muted)" }}>{i.id}</span>
                <Chip kind={sevTone(i.sev)} dot>{i.sev}</Chip>
                <Chip kind={i.status === "resolved" ? "live" : i.status === "monitoring" ? "accent" : "warn"} dot>{i.status}</Chip>
              </div>
              <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>opened {i.opened}</div>
            </div>
            <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 6 }}>{i.t}</div>
            <div className="row between" style={{ marginTop: 12 }}>
              <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>Owner: <b style={{ color: "var(--fg)" }}>{i.owner}</b> · affects {i.affected}</div>
              <div className="row gap-2">
                <button className="btn btn-ghost btn-sm">View timeline</button>
                <button className="btn btn-outline btn-sm">Update</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};


/* ==========================================================
   FEATURE FLAGS — per-tenant kill switches & gradual rollouts
   ========================================================== */
const FeatureFlags = () => {
  const tenants = ["Acme Dentistry", "Twiga Foods", "Chipper Cash", "Sendy", "Java House", "Kopo Kopo"];
  const flags = [
    { id: "outbound_campaigns",   desc: "Bulk outbound calling UI",          rollout: 80, kill: false, scope: "all tenants" },
    { id: "voice_v2",             desc: "Switch to v2 voice model",          rollout: 35, kill: false, scope: "opt-in" },
    { id: "live_transcript",      desc: "Stream transcripts in real time",   rollout: 100, kill: false, scope: "all tenants" },
    { id: "mpesa_collection",     desc: "Collect M-Pesa during call",        rollout: 10, kill: false, scope: "beta" },
    { id: "claude_haiku_4_5",     desc: "Upgrade core agent to Haiku 4.5",   rollout: 100, kill: false, scope: "all tenants" },
    { id: "auto_translate_sw",    desc: "Auto-detect & translate Swahili",   rollout: 0,  kill: false, scope: "off" },
    { id: "outbound_emergency_stop", desc: "Global kill switch for outbound", rollout: 0, kill: true, scope: "kill switch" },
  ];
  // tenant-specific overrides (just for the matrix display)
  const overrides = {
    outbound_campaigns:  { "Java House": false },
    voice_v2:            { "Acme Dentistry": true, "Sendy": true },
    mpesa_collection:    { "Acme Dentistry": true },
  };
  const cell = (flag, t) => {
    const ov = overrides[flag.id]?.[t];
    if (ov === true)  return { v: "on",     tone: "live" };
    if (ov === false) return { v: "off",    tone: "neutral" };
    if (flag.kill)    return { v: "armed",  tone: "danger" };
    if (flag.rollout === 100) return { v: "on",   tone: "live" };
    if (flag.rollout === 0)   return { v: "off",  tone: "neutral" };
    // probabilistic for display purposes only
    const h = (flag.id + t).split("").reduce((s,c) => s + c.charCodeAt(0), 0);
    return (h % 100) < flag.rollout ? { v: "on", tone: "live" } : { v: "off", tone: "neutral" };
  };

  return (
    <div className="page page-mount">
      <div className="page-header">
        <div>
          <h1 className="page-title">Feature flags</h1>
          <p className="page-sub">Gradual rollouts, per-tenant overrides, and kill switches for risky features.</p>
        </div>
        <button className="btn btn-accent"><Icon name="plus"/> New flag</button>
      </div>

      <div className="grid grid-4 stagger" style={{ marginBottom: 24 }}>
        <OpsTile k="Flags" v={flags.length} sub="3 in rollout"/>
        <OpsTile k="Tenant overrides" v="4" sub="across 3 tenants"/>
        <OpsTile k="Kill switches"    v="1" sub="all disarmed"  tone="success"/>
        <OpsTile k="Last change"      v="2h" sub="by ops@mikaka.io"/>
      </div>

      <div className="card" style={{ overflow: "auto" }}>
        <table className="tbl" style={{ minWidth: 900 }}>
          <thead>
            <tr>
              <th style={{ minWidth: 280 }}>Flag</th>
              <th style={{ minWidth: 180 }}>Rollout</th>
              <th>Scope</th>
              {tenants.map(t => <th key={t} style={{ textAlign: "center", textTransform: "none", letterSpacing: 0, fontSize: 11, padding: "8px 6px" }}>{t.split(" ")[0]}</th>)}
            </tr>
          </thead>
          <tbody>
            {flags.map(f => (
              <tr key={f.id}>
                <td>
                  <div className="mono cell-strong" style={{ fontSize: 13 }}>{f.id}</div>
                  <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 2 }}>{f.desc}</div>
                </td>
                <td>
                  {f.kill ? (
                    <Chip kind="danger">disarmed · click to arm</Chip>
                  ) : (
                    <div className="row gap-2" style={{ minWidth: 160 }}>
                      <div style={{ flex: 1, height: 6, background: "var(--bg-sunken)", borderRadius: 3 }}>
                        <div style={{ width: f.rollout + "%", height: "100%", background: "var(--mk-orange)", borderRadius: 3 }}/>
                      </div>
                      <span className="mono" style={{ fontSize: 12, color: "var(--fg-muted)", minWidth: 32 }}>{f.rollout}%</span>
                    </div>
                  )}
                </td>
                <td><Chip kind={f.kill ? "danger" : f.rollout === 100 ? "live" : f.rollout === 0 ? "neutral" : "accent"}>{f.scope}</Chip></td>
                {tenants.map(t => {
                  const c = cell(f, t);
                  const isOverride = overrides[f.id]?.[t] !== undefined;
                  return (
                    <td key={t} style={{ textAlign: "center", padding: "8px 6px" }}>
                      <span title={(isOverride ? "override · " : "") + c.v} style={{ display: "inline-block", width: 18, height: 18, borderRadius: 5, background: c.tone === "live" ? "var(--mk-success)" : c.tone === "danger" ? "var(--mk-danger)" : "var(--bg-sunken)", border: isOverride ? "2px solid var(--mk-orange)" : "1px solid var(--border)" }}/>
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="row gap-4" style={{ marginTop: 16, fontSize: 12, color: "var(--fg-muted)" }}>
        <div className="row gap-2"><span style={{ width: 12, height: 12, borderRadius: 3, background: "var(--mk-success)" }}/>on</div>
        <div className="row gap-2"><span style={{ width: 12, height: 12, borderRadius: 3, background: "var(--bg-sunken)", border: "1px solid var(--border)" }}/>off</div>
        <div className="row gap-2"><span style={{ width: 12, height: 12, borderRadius: 3, background: "var(--bg-sunken)", border: "2px solid var(--mk-orange)" }}/>tenant override</div>
        <div className="row gap-2"><span style={{ width: 12, height: 12, borderRadius: 3, background: "var(--mk-danger)" }}/>kill switch armed</div>
      </div>
    </div>
  );
};


/* ==========================================================
   REVENUE — MRR, cohorts, usage outliers (replaces Billing plans)
   ========================================================== */
const Revenue = ({ onGo }) => {
  const [range, setRange] = useState("30d");
  const months = ["May","Jun","Jul","Aug","Sep","Oct","Nov"];
  const mrr = [4200, 4680, 5340, 6120, 7100, 7920, 8640];
  const max = Math.max(...mrr);

  return (
    <div className="page page-mount">
      <div className="page-header">
        <div>
          <h1 className="page-title">Revenue</h1>
          <p className="page-sub">MRR, plan distribution, usage outliers and upcoming renewals.</p>
        </div>
        <div className="row gap-2">
          <div className="seg">{["7d","30d","90d","12m"].map(r => <button key={r} className={range === r ? "on" : ""} onClick={() => setRange(r)}>{r}</button>)}</div>
          <button className="btn btn-outline"><Icon name="download"/> Export</button>
        </div>
      </div>

      <div className="grid grid-4 stagger" style={{ marginBottom: 24 }}>
        <OpsTile k="MRR"          v="$8,640" sub="+9.1% MoM" tone="success"/>
        <OpsTile k="ARPU"         v="$360"   sub="+$12 MoM"/>
        <OpsTile k="Active subs"  v="24"     sub="+3 this month"/>
        <OpsTile k="Churn · 30d"  v="0.0%"   sub="0 of 21"   tone="success"/>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "2fr 1fr", gap: 20, marginBottom: 20 }}>
        <div className="card card-pad">
          <div className="row between" style={{ marginBottom: 16 }}>
            <div>
              <div style={{ fontSize: 15, fontWeight: 500 }}>MRR trend</div>
              <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>last 7 months</div>
            </div>
            <Chip kind="live" dot>+105% YTD</Chip>
          </div>
          <div className="bars" style={{ height: 160 }}>
            {mrr.map((v, i) => (
              <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
                <div className="b" style={{ width: "100%", height: ((v / max) * 130) + "px", background: "linear-gradient(180deg, var(--mk-orange), var(--mk-orange-600))", borderRadius: "4px 4px 0 0" }}/>
                <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>{months[i]}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="card card-pad">
          <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 14 }}>Plan distribution</div>
          <div className="stack gap-3">
            {[
              { n: "Starter",    sub: "6 tenants",  rev: "$0",     pct: 25, c: "var(--mk-slate-400)" },
              { n: "Growth",     sub: "12 tenants", rev: "$468",   pct: 50, c: "var(--mk-orange)"    },
              { n: "Scale",      sub: "4 tenants",  rev: "$596",   pct: 16.6, c: "var(--mk-purple)"  },
              { n: "Enterprise", sub: "2 tenants",  rev: "$7,576", pct: 8.4, c: "var(--mk-ink)"      },
            ].map(p => (
              <div key={p.n}>
                <div className="row between" style={{ fontSize: 13, marginBottom: 4 }}>
                  <span style={{ fontWeight: 500 }}>{p.n} <span style={{ color: "var(--fg-muted)", fontWeight: 400 }}>· {p.sub}</span></span>
                  <span className="mono">{p.rev}/mo</span>
                </div>
                <div style={{ height: 6, background: "var(--bg-sunken)", borderRadius: 3 }}>
                  <div style={{ width: p.pct + "%", height: "100%", background: p.c, borderRadius: 3 }}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 20 }}>
        <div className="card">
          <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)" }}>
            <div className="row between">
              <div style={{ fontSize: 15, fontWeight: 500 }}>Usage outliers</div>
              <Chip kind="warn">over plan</Chip>
            </div>
            <div style={{ fontSize: 12.5, color: "var(--fg-muted)", marginTop: 2 }}>Tenants using &gt;85% of included minutes — talk to them about upgrading.</div>
          </div>
          <table className="tbl">
            <thead><tr><th>Tenant</th><th>Plan</th><th>Usage</th><th></th></tr></thead>
            <tbody>
              {[
                ["Chipper Cash", "Enterprise", 92, "ten_chip"],
                ["Twiga Foods",  "Scale",      88, "ten_twiga"],
                ["Acme Dentistry","Growth",    87, "ten_acme"],
              ].map(([n, p, u, id]) => (
                <tr key={id} style={{ cursor: "pointer" }} onClick={() => onGo("tenant-detail")}>
                  <td className="cell-strong">{n}</td>
                  <td><Chip kind={p === "Enterprise" ? "purple" : "accent"}>{p}</Chip></td>
                  <td style={{ minWidth: 160 }}>
                    <div className="row gap-2">
                      <div style={{ flex: 1, height: 6, background: "var(--bg-sunken)", borderRadius: 3 }}>
                        <div style={{ width: u + "%", height: "100%", background: u > 90 ? "var(--mk-danger)" : "var(--mk-warning)", borderRadius: 3 }}/>
                      </div>
                      <span className="mono" style={{ fontSize: 12 }}>{u}%</span>
                    </div>
                  </td>
                  <td><Icon name="chevron-right" size={14} style={{ color: "var(--fg-faint)" }}/></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="card">
          <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)" }}>
            <div className="row between">
              <div style={{ fontSize: 15, fontWeight: 500 }}>Renewals · next 30 days</div>
              <Chip kind="accent">5 due</Chip>
            </div>
          </div>
          <table className="tbl">
            <thead><tr><th>Tenant</th><th>Plan</th><th>Renews</th><th>Amount</th></tr></thead>
            <tbody>
              {[
                ["Chipper Cash",    "Enterprise · annual", "Dec 02", "$45,000"],
                ["Java House",      "Scale · monthly",     "Dec 04", "$149"],
                ["Acme Dentistry",  "Growth · annual",     "Dec 14", "$468"],
                ["Sendy",           "Growth · monthly",    "Dec 18", "$39"],
                ["Twiga Foods",     "Scale · monthly",     "Dec 22", "$149"],
              ].map(([n, p, d, a]) => (
                <tr key={n}>
                  <td className="cell-strong">{n}</td>
                  <td style={{ color: "var(--fg-muted)", fontSize: 12.5 }}>{p}</td>
                  <td className="mono">{d}</td>
                  <td className="mono">{a}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};


/* Plans editor (kept simple — was BillingPlans) — accessible from Revenue */
const PlansEditor = () => (
  <div className="page page-mount">
    <div className="page-header">
      <div><h1 className="page-title">Plans</h1><p className="page-sub">Plans offered to tenants.</p></div>
      <button className="btn btn-accent"><Icon name="plus"/> New plan</button>
    </div>
    <div className="grid grid-3 stagger">
      {[
        { n: "Starter",    p: "$0",    incl: "100 min",                 active: "6 tenants", kind: "neutral" },
        { n: "Growth",     p: "$39",   incl: "500 min · 1 number",      active: "12 tenants", kind: "accent" },
        { n: "Scale",      p: "$149",  incl: "5,000 min · 5 numbers",   active: "4 tenants",  kind: "purple" },
      ].map((pl, i) => (
        <div key={i} className="card card-pad">
          <div className="row between" style={{ marginBottom: 16 }}>
            <div className="display" style={{ fontSize: 24, fontWeight: 600 }}>{pl.n}</div>
            <Chip kind={pl.kind}>{pl.active}</Chip>
          </div>
          <div className="display" style={{ fontSize: 44, fontWeight: 600, letterSpacing: "-0.03em" }}>{pl.p}<span style={{ fontSize: 14, color: "var(--fg-muted)", fontWeight: 400 }}>/mo</span></div>
          <div style={{ fontSize: 13, color: "var(--fg-muted)", marginTop: 8 }}>{pl.incl}</div>
          <button className="btn btn-outline btn-sm" style={{ marginTop: 18, width: "100%", justifyContent: "center" }}>Edit plan</button>
        </div>
      ))}
    </div>
  </div>
);

Object.assign(window, {
  ImpersonationBanner,
  LiveOps, CallsGlobal, AdminCallDetail,
  SystemHealth, WebhooksLog, Incidents,
  FeatureFlags, Revenue, PlansEditor,
});
