/* Stratum Leads — Operations Console. System Health (IT Operations): worker
   status, source blockers, run-health incidents, and pipeline queue depths.
   100% mock; reads SYSTEM (workers/incidents) + INTEL.sources + LEAD_QUEUE.
   UNIQUE top-level names only (shared global scope — see the fmtUSD trap). */

const { Button, Card, Metric, StatusChip, EmptyState, ProgressBar } = window.StratumLeadsDesignSystem_6367ed;
const { I } = window.OpsShared;

const HW_TONE = { healthy: "success", degraded: "warning", idle: "neutral", down: "danger" };
const HW_LABEL = { healthy: "Healthy", degraded: "Degraded", idle: "Idle", down: "Down" };
const HSRC_TONE = { healthy: "success", degraded: "warning", blocked: "danger" };

function HealthWorker({ w }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 12, alignItems: "center", padding: "12px 0", borderTop: "1px solid var(--border-subtle)" }}>
      <span style={{ width: 34, height: 34, display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent)" }}>{I("cpu", { width: 16 })}</span>
      <span style={{ minWidth: 0 }}>
        <strong style={{ fontSize: 13, display: "block" }}>{w.name}</strong>
        <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{w.role} · {w.throughput} · ♥ {w.heartbeat}{w.note ? ` · ${w.note}` : ""}</span>
      </span>
      <span style={{ display: "grid", justifyItems: "end", gap: 4 }}>
        <StatusChip tone={HW_TONE[w.status]} dot>{HW_LABEL[w.status]}</StatusChip>
        <span style={{ fontSize: 11, color: "var(--text-subtle)" }}>queue {w.depth}</span>
      </span>
    </div>);

}

function HealthDepth({ label, value, max, tone, onClick }) {
  return (
    <button onClick={onClick} disabled={!onClick} style={{ display: "grid", gap: 6, textAlign: "left", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-sm)", padding: "12px 14px", background: "var(--surface-subtle)", cursor: onClick ? "pointer" : "default", font: "inherit" }}>
      <span style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
        <span style={{ color: "var(--text-muted)" }}>{label}</span>
        <strong style={{ fontVariantNumeric: "tabular-nums" }}>{value.toLocaleString()}</strong>
      </span>
      <div style={{ height: 8, borderRadius: "var(--radius-pill)", background: "var(--surface-sunken)", overflow: "hidden" }}>
        <div style={{ width: `${Math.min(100, Math.round(value / max * 100))}%`, height: "100%", borderRadius: "var(--radius-pill)", background: `var(--${tone})` }} />
      </div>
    </button>);

}

function SystemHealthPage({ system, sources, leadQueue, onNavigate }) {
  React.useEffect(refresh);
  const blockers = sources.filter((s) => s.status !== "healthy");
  const workersOk = system.workers.filter((w) => w.status === "healthy").length;
  const degraded = system.workers.some((w) => w.status === "degraded" || w.status === "down") || blockers.some((s) => s.status === "blocked");
  const pending = leadQueue.filter((l) => l.status === "pending").length;
  const verified = leadQueue.filter((l) => l.status === "verified").length;
  const enrichBacklog = (system.workers.find((w) => w.id === "enrich-worker-1") || {}).depth || 0;
  // Keep the publish worker's queue depth in sync with the live publish-gate backlog.
  const workers = system.workers.map((w) => w.id === "publish-worker-1" ? { ...w, depth: verified } : w);

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)" }}>
      <PageHeader eyebrow="IT Operations" title="System Health"
        description="Live status of the crawl / enrichment / scoring / publish workers, blocked sources, and pipeline backlogs."
        actions={<StatusChip tone={degraded ? "warning" : "success"} dot>{degraded ? "Degraded — attention needed" : "All systems operational"}</StatusChip>} />

      <Reveal style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px,1fr))", gap: 14, marginBottom: 22 }}>
        <Metric icon={I("cpu")} value={`${workersOk}/${system.workers.length}`} label="Workers healthy" accent={degraded ? "amber" : "green"} />
        <Metric icon={I("plug-zap")} value={blockers.length} label="Source blockers" accent={blockers.length ? "amber" : "green"} />
        <Metric icon={I("list-checks")} value={pending} label="Review backlog" accent="cyan" />
        <Metric icon={I("upload-cloud")} value={verified} label="Publish-gate backlog" accent="violet" />
      </Reveal>

      <Reveal delay={60} style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 20, alignItems: "start" }}>
        <Card title="Workers" note={`Updated ${system.updatedAt}`}>
          <div>{workers.map((w) => <HealthWorker key={w.id} w={w} />)}</div>
        </Card>

        <div style={{ display: "grid", gap: 20 }}>
          <Card title="Pipeline backlogs">
            <div style={{ display: "grid", gap: 10 }}>
              <HealthDepth label="Awaiting review" value={pending} max={500} tone="warning" onClick={() => onNavigate("leadops")} />
              <HealthDepth label="Enrichment backlog" value={enrichBacklog} max={200} tone="info" onClick={() => onNavigate("enrich")} />
              <HealthDepth label="Publish-gate ready" value={verified} max={200} tone="violet" onClick={() => onNavigate("publishing")} />
            </div>
          </Card>

          <Card title="Source blockers" note={blockers.length ? "Adapters not healthy" : "All adapters healthy"} actions={<Button size="sm" variant="secondary" onClick={() => onNavigate("playbooks")}>Playbooks</Button>}>
            {blockers.length === 0 ?
            <EmptyState icon="circle-check" title="No blockers" message="Every source adapter is running clean." /> :
            <div style={{ display: "grid", gap: 10 }}>
                {blockers.map((s) =>
              <div key={s.id} style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 8, alignItems: "center", padding: "10px 0", borderTop: "1px solid var(--border-subtle)" }}>
                    <span style={{ minWidth: 0 }}>
                      <strong style={{ fontSize: 12.5, display: "block" }}>{s.name}</strong>
                      <span style={{ fontSize: 11.5, color: "var(--danger)" }}>{s.issue || "Adapter degraded"}</span>
                    </span>
                    <StatusChip tone={HSRC_TONE[s.status]} dot>{s.status}</StatusChip>
                  </div>
              )}
              </div>
            }
          </Card>
        </div>
      </Reveal>

      <Reveal delay={100} style={{ marginTop: 20 }}>
        <Card title="Recent incidents" note="Run-health exceptions across sources">
          {system.incidents.length === 0 ?
          <EmptyState icon="shield-check" title="No incidents" message="No run-health exceptions logged." /> :
          <div style={{ display: "grid", gap: 2 }}>
              {system.incidents.map((e, i) =>
            <div key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 12, alignItems: "center", padding: "11px 4px", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)" }}>
                  <StatusChip tone={e.level === "error" ? "danger" : "warning"}>{e.level}</StatusChip>
                  <span style={{ minWidth: 0 }}>
                    <strong style={{ fontSize: 12.5 }}>{e.source}</strong>
                    <span style={{ display: "block", fontSize: 11.5, color: "var(--text-muted)" }}>{e.message}</span>
                  </span>
                  <span style={{ fontSize: 11, color: "var(--text-subtle)", whiteSpace: "nowrap" }}>{e.at}</span>
                </div>
            )}
            </div>
          }
        </Card>
      </Reveal>
    </div>);

}

Object.assign(window, { OpsHealth: { SystemHealthPage } });
