/* ============================================
   SYSTEM HEALTH — Queue gauges + service status
   ============================================ */
function SystemHealthScreen() {
  // Gauge values
  const textQueueDepth = 14;
  const textQueueMax = 50;
  const imgQueueDepth = 32;
  const imgQueueMax = 50;

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">System Health</h1>
          <p className="page-subtitle">Real-time worker, queue, and service status · auto-refreshes every 5 s</p>
        </div>
        <div className="row">
          <span className="badge badge--complete"><span className="dot" />All systems operational</span>
          <button className="btn btn--ghost"><Icons.Refresh size={14} /> Refresh</button>
        </div>
      </div>

      <div className="grid-2" style={{ marginBottom: 16 }}>
        <QueueGauge
          title="Local Text Queue Depth"
          subtitle="Worker pool: 4 concurrent · text extraction + chunking"
          depth={textQueueDepth}
          max={textQueueMax}
          status="healthy"
          rate="2.4 docs/min"
          oldest="48 s ago"
        />
        <QueueGauge
          title="Network Image Queue Depth"
          subtitle="50-page batch · vision OCR via external endpoint"
          depth={imgQueueDepth}
          max={imgQueueMax}
          status="elevated"
          rate="0.8 batch/min"
          oldest="4 min 18 s ago"
        />
      </div>

      {/* Service / pipeline status grid */}
      <Card title="Service Status" subtitle="All downstream dependencies — current ping and uptime" bodyFlush style={{ marginBottom: 16 }}>
        <table className="table">
          <thead>
            <tr>
              <th>Service</th>
              <th style={{ width: 120 }}>Status</th>
              <th style={{ width: 110 }}>Latency P50</th>
              <th style={{ width: 110 }}>Latency P95</th>
              <th style={{ width: 110 }}>Uptime 30d</th>
              <th style={{ width: 140 }}>Endpoint</th>
              <th style={{ width: 110 }}>Last error</th>
            </tr>
          </thead>
          <tbody>
            {[
              { name: "Qdrant Vector Store",      env: "production",  status: "ok",     p50: "12 ms",   p95: "38 ms",   up: "99.99%",  ep: "qdrant.bjp.local:6333",  err: "—" },
              { name: "Embedding Service",        env: "managed",     status: "ok",     p50: "84 ms",   p95: "212 ms",  up: "99.97%",  ep: "emb-api.bjp.cloud",      err: "2 d ago" },
              { name: "Qwen API - Inference",     env: "managed",     status: "ok",     p50: "318 ms",  p95: "1.21 s",  up: "99.94%",  ep: "dashscope-intl.aliyuncs.com",       err: "—" },
              { name: "Vision OCR Service",       env: "managed",     status: "warn",   p50: "1.84 s",  p95: "4.20 s",  up: "98.72%",  ep: "dashscope-intl.aliyuncs.com",       err: "12 min ago" },
              { name: "Document Worker Pool",     env: "local",       status: "ok",     p50: "—",       p95: "—",       up: "99.91%",  ep: "worker-pool-04",          err: "—" },
              { name: "Redis Queue Broker",       env: "production",  status: "ok",     p50: "1 ms",    p95: "4 ms",    up: "100.0%",  ep: "redis.bjp.local:6379",    err: "—" },
              { name: "Postgres · Metadata",      env: "production",  status: "ok",     p50: "4 ms",    p95: "18 ms",   up: "99.98%",  ep: "pg.bjp.local:5432",       err: "—" },
            ].map((s, i) => (
              <tr key={i}>
                <td>
                  <div className="doc-name">{s.name}</div>
                  <div className="mono text-xs muted">{s.env}</div>
                </td>
                <td>
                  {s.status === "ok" && <Badge kind="complete">Healthy</Badge>}
                  {s.status === "warn" && <Badge kind="pending">Degraded</Badge>}
                  {s.status === "down" && <Badge kind="failed">Down</Badge>}
                </td>
                <td className="mono text-xs">{s.p50}</td>
                <td className="mono text-xs">{s.p95}</td>
                <td className="mono text-xs" style={{ color: s.up.startsWith("99.9") || s.up === "100.0%" ? "var(--status-ok)" : "var(--status-warn)", fontWeight: 600 }}>{s.up}</td>
                <td className="mono text-xs muted">{s.ep}</td>
                <td className="mono text-xs muted">{s.err}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <div className="grid-2">
        {/* Worker utilization */}
        <Card title="Worker Utilization" subtitle="Last 60 minutes">
          {[
            { name: "worker-pool-01 · text", v: 78 },
            { name: "worker-pool-02 · text", v: 84 },
            { name: "worker-pool-03 · text", v: 62 },
            { name: "worker-pool-04 · text", v: 71 },
            { name: "worker-img-01 · vision", v: 92 },
            { name: "worker-img-02 · vision", v: 88 },
          ].map(w => (
            <div key={w.name} style={{ marginBottom: 12 }}>
              <div className="row" style={{ marginBottom: 4 }}>
                <span className="mono text-xs fw-600">{w.name}</span>
                <span className="spacer" />
                <span className="mono text-xs" style={{ color: w.v > 85 ? "var(--orange-700)" : "var(--ink-700)", fontWeight: 600 }}>{w.v}%</span>
              </div>
              <Progress value={w.v} kind={w.v > 85 ? undefined : "blue"} />
            </div>
          ))}
        </Card>

        {/* Recent events */}
        <Card title="Pipeline Events" subtitle="Last 24 hours · system log">
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, lineHeight: 1.7, maxHeight: 320, overflowY: "auto" }}>
            {[
              ["14:23", "INFO", "ingestion", "Document ING-26-0140 reached 89% (embedding stage)"],
              ["14:22", "INFO", "query", "Session 6f3a · retrieved 4 chunks · 0.913 max similarity"],
              ["14:18", "WARN", "vision", "OCR latency p95 exceeded 4s threshold (4.20s)"],
              ["14:16", "INFO", "ingestion", "ING-26-0141 entered processing — Fanuc-31i-B"],
              ["14:12", "INFO", "worker", "worker-pool-03 completed batch of 8 chunks"],
              ["13:58", "ERROR", "vision", "Image decode failure on page 28 — ABB-IRB-6700"],
              ["13:42", "INFO", "ingestion", "ING-26-0136 completed — Welding Consumables (218 chunks)"],
              ["13:31", "INFO", "ingestion", "ING-26-0135 completed — Pneumatics FRL (540 chunks)"],
              ["13:14", "INFO", "queue", "Image queue depth reached 32 / 50"],
              ["12:48", "INFO", "embed", "Embedding service connection re-established (was: 2 d ago)"],
            ].map(([t, lv, src, msg], i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "50px 60px 80px 1fr", gap: 8, padding: "4px 0", borderBottom: "1px dashed var(--ink-100)" }}>
                <span className="muted">{t}</span>
                <span style={{ color: lv === "ERROR" ? "var(--status-danger)" : lv === "WARN" ? "var(--status-warn)" : "var(--status-ok)", fontWeight: 700 }}>{lv}</span>
                <span style={{ color: "var(--navy-700)" }}>{src}</span>
                <span style={{ color: "var(--ink-700)" }}>{msg}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </>
  );
}

function QueueGauge({ title, subtitle, depth, max, status, rate, oldest }) {
  // semi-circular gauge — SVG Y goes down, so we negate sin to draw the top half
  const pct = Math.min(1, Math.max(0, depth / max));
  const r = 100, cx = 130, cy = 130;
  // Polar angle: π at the left endpoint, 0 at the right. As depth fills, sweep from π toward 0.
  const polar = (a) => ({ x: cx + r * Math.cos(a), y: cy - r * Math.sin(a) });
  const startA = Math.PI;
  const endA = Math.PI - pct * Math.PI;
  const p1 = polar(startA);     // left endpoint  (cx - r, cy)
  const p2 = polar(endA);       // current value endpoint
  const pEnd = polar(0);        // right endpoint (cx + r, cy)
  // sweep-flag = 0 makes the arc go through the TOP half in SVG's Y-down system
  const large = pct > 0.5 ? 1 : 0;

  const statusColor = status === "healthy" ? "var(--status-ok)" : status === "elevated" ? "var(--orange-500)" : "var(--status-danger)";
  const statusBadge = status === "healthy" ? "complete" : status === "elevated" ? "pending" : "failed";

  return (
    <Card title={title} subtitle={subtitle} right={<Badge kind={statusBadge}>{status === "healthy" ? "HEALTHY" : status === "elevated" ? "ELEVATED" : "CRITICAL"}</Badge>}>
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 24, alignItems: "center" }}>
        <svg viewBox="0 0 260 160" width="260">
          {/* Background arc — full top semicircle (sweep-flag 1 = clockwise in SVG screen coords = top half from left to right) */}
          <path
            d={`M ${p1.x} ${p1.y} A ${r} ${r} 0 0 1 ${pEnd.x} ${pEnd.y}`}
            fill="none"
            stroke="var(--ink-100)"
            strokeWidth="14"
            strokeLinecap="round"
          />
          {/* Foreground arc — from left endpoint, along top, to current value */}
          {pct > 0.001 && (
            <path
              d={`M ${p1.x} ${p1.y} A ${r} ${r} 0 0 1 ${p2.x} ${p2.y}`}
              fill="none"
              stroke={statusColor}
              strokeWidth="14"
              strokeLinecap="round"
            />
          )}
          {/* Ticks */}
          {[0, 0.25, 0.5, 0.75, 1].map(t => {
            const a = Math.PI - t * Math.PI;
            const inner = { x: cx + (r - 10) * Math.cos(a), y: cy - (r - 10) * Math.sin(a) };
            const outer = { x: cx + (r + 8)  * Math.cos(a), y: cy - (r + 8)  * Math.sin(a) };
            return <line key={t} x1={inner.x} y1={inner.y} x2={outer.x} y2={outer.y} stroke="var(--ink-400)" strokeWidth="1"/>;
          })}
          {/* Center value */}
          <text x={cx} y={cy - 16} fontSize="36" fontFamily="IBM Plex Mono" fontWeight="700" fill="var(--ink-900)" textAnchor="middle">{depth}</text>
          <text x={cx} y={cy + 2}  fontSize="11" fontFamily="IBM Plex Mono" fill="var(--ink-500)" textAnchor="middle">/ {max} items</text>
          {/* Min/max labels under the arc endpoints */}
          <text x={p1.x}   y={cy + 18} fontSize="9" fontFamily="IBM Plex Mono" fill="var(--ink-400)" textAnchor="middle">0</text>
          <text x={pEnd.x} y={cy + 18} fontSize="9" fontFamily="IBM Plex Mono" fill="var(--ink-400)" textAnchor="middle">{max}</text>
        </svg>
        <div className="col gap-12">
          <div>
            <div className="text-xs muted" style={{ textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>Throughput</div>
            <div className="mono" style={{ fontSize: 18, fontWeight: 700, marginTop: 2 }}>{rate}</div>
          </div>
          <div>
            <div className="text-xs muted" style={{ textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>Oldest in queue</div>
            <div className="mono" style={{ fontSize: 14, fontWeight: 600, marginTop: 2, color: status === "elevated" ? "var(--orange-700)" : "var(--ink-900)" }}>{oldest}</div>
          </div>
          <div>
            <div className="text-xs muted" style={{ textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>Capacity headroom</div>
            <div className="row gap-8" style={{ marginTop: 4 }}>
              <Progress value={(1 - depth / max) * 100} kind="green" />
              <span className="mono text-xs fw-600">{Math.round((1 - depth / max) * 100)}%</span>
            </div>
          </div>
        </div>
      </div>
    </Card>
  );
}

window.SystemHealthScreen = SystemHealthScreen;
