// ─────────────────────────────────────────────────────────────────────────
// Meridian — System / Ops status (wired to /api/ops/status + /api/health)
// ─────────────────────────────────────────────────────────────────────────
const BADGE_TO_STATE = { green: "ok", amber: "warn", red: "err", pending: "warn" };
const STATE_WORD = { ok: "Healthy", warn: "Attention", err: "Failed" };

function fmtDur(s) {
  if (s == null) return "—";
  const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
  if (d > 0) return `${d} d ${h} h`;
  if (h > 0) return `${h} h ${m} min`;
  return `${m} min`;
}

function SystemStatus({ theme, onNavigate }) {
  const ops = useAsync(() => API.opsStatus(), []);
  const health = useAsync(() => API.healthDetails().catch(() => null), []);

  if (ops.loading) {
    return <div className="rise"><PageHeader title="System status" subtitle="Loading job health…" /><SkelCard lines={4} /></div>;
  }
  if (ops.error) {
    return <div className="rise"><PageHeader title="System status" /><Card><EmptyState icon="cloud-off" title="Couldn't load status" body={ops.error.message} action={<button className="btn btn-sm" onClick={ops.reload}>Retry</button>} /></Card></div>;
  }

  const data = ops.data;
  const jobs = (data.jobs || []).map((j) => ({ ...j, state: BADGE_TO_STATE[j.badge] || "warn" }));
  const overall = BADGE_TO_STATE[data.overall] || "ok";
  const overallText = { ok: "All systems healthy", warn: "Mostly healthy — some jobs need attention", err: "A job has failed" }[overall];
  const dotCls = { ok: "dot-ok", warn: "dot-warn", err: "dot-err" };
  const counts = data.counts || {};

  // recent activity from jobs, newest first
  const activity = [...jobs]
    .filter((j) => j.last_run_at)
    .sort((a, b) => new Date(b.last_run_at) - new Date(a.last_run_at))
    .slice(0, 8)
    .map((j) => ({
      t: j.last_run_at,
      s: j.state,
      x: j.last_error ? `${j.name}: ${j.last_error}` : `${j.name} ran successfully${j.last_duration_ms != null ? ` · ${j.last_duration_ms} ms` : ""}`,
    }));

  const h = health.data;
  const env = [
    ["Host", "self-hosted"],
    ["Version", h ? h.version : "—"],
    ["Node", h ? h.node : "—"],
    ["Uptime", h ? fmtDur(h.uptime_s) : "—"],
    ["Users", h && h.stats ? String(h.stats.users) : "—"],
    ["Ledger entries", h && h.stats ? String(h.stats.ledger_entries) : "—"],
  ];

  return (
    <div className="rise">
      <PageHeader title="System status" subtitle="A calm read on the background jobs that keep Meridian current."
        actions={<button className="btn btn-sm" onClick={() => { ops.reload(); health.reload(); }}><Icon name="refresh-cw" size={13} /> Refresh</button>} />

      {/* overall banner */}
      <div className="card" style={{ display: "flex", alignItems: "center", gap: 16, borderColor: overall === "ok" ? "var(--signal-border)" : "var(--mixed-border)", background: overall === "ok" ? "linear-gradient(140deg, var(--signal-soft), var(--bg-surface))" : "linear-gradient(140deg, var(--mixed-soft), var(--bg-surface))", marginBottom: 16 }}>
        <div style={{ width: 46, height: 46, borderRadius: 13, background: "var(--bg-surface)", border: "1px solid var(--border-1)", display: "grid", placeItems: "center", flexShrink: 0 }}>
          <span className={"dot dot-pulse " + dotCls[overall]} style={{ width: 14, height: 14 }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 17, letterSpacing: "-0.01em" }}>{overallText}</div>
          <div className="muted" style={{ fontSize: 13, marginTop: 2 }}>{counts.jobs || jobs.length} jobs · {counts.jobs_green || 0} healthy{counts.jobs_amber ? ` · ${counts.jobs_amber} attention` : ""}{counts.jobs_red ? ` · ${counts.jobs_red} failed` : ""}</div>
        </div>
        <Row gap={16} wrap style={{ flexShrink: 0 }}>
          {[["Jobs OK", (counts.jobs_green || 0) + " / " + (counts.jobs || jobs.length)], ["Uptime", h ? fmtDur(h.uptime_s) : "—"], ["Version", h ? h.version : "—"]].map(([k, v]) => (
            <div key={k} style={{ textAlign: "right" }}><div className="kpi-label" style={{ fontSize: 10 }}>{k}</div><div className="mono" style={{ fontSize: 16, fontWeight: 600, whiteSpace: "nowrap" }}>{v}</div></div>
          ))}
        </Row>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.5fr) minmax(0, 1fr)", gap: 16, alignItems: "start" }} className="dash-grid">
        {/* jobs */}
        <Col gap={12} style={{ minWidth: 0 }}>
          <SectionTitle icon="activity">Background jobs</SectionTitle>
          {jobs.length === 0 ? <Card><EmptyState icon="inbox" title="No jobs registered" /></Card> : jobs.map((j) => (
            <div key={j.name} className="card" style={{ padding: "15px 18px" }}>
              <Row justify="space-between" align="flex-start" gap={12}>
                <Row gap={12} align="flex-start" style={{ minWidth: 0 }}>
                  <span className={"dot " + dotCls[j.state]} style={{ width: 10, height: 10, marginTop: 5, flexShrink: 0 }} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 14.5 }}>{j.name}</div>
                    <div className="muted-2 mono" style={{ fontSize: 11.5, marginTop: 4 }}>{j.last_run_at ? "ran " + relTime(j.last_run_at) : "never run"}{j.schedule ? " · " + j.schedule : ""}</div>
                    {j.last_error && <div style={{ fontSize: 12, color: "var(--danger-fg)", marginTop: 4 }}>{j.last_error}</div>}
                  </div>
                </Row>
                <span className={"badge badge-" + j.state} style={{ flexShrink: 0 }}>{j.badge === "pending" ? "Pending" : STATE_WORD[j.state]}</span>
              </Row>
            </div>
          ))}
        </Col>

        {/* activity + meta */}
        <Col gap={16} style={{ minWidth: 0 }}>
          <Card>
            <SectionTitle icon="scroll-text">Recent activity</SectionTitle>
            {activity.length === 0 ? <EmptyState icon="inbox" title="No activity yet" /> : (
              <Col gap={0}>
                {activity.map((l, i) => (
                  <Row key={i} gap={11} align="flex-start" style={{ padding: "10px 0", borderTop: i ? "1px solid var(--border-1)" : 0 }}>
                    <span className={"dot " + dotCls[l.s]} style={{ marginTop: 6, width: 7, height: 7 }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, lineHeight: 1.45 }}>{l.x}</div>
                      <div className="muted-2 mono" style={{ fontSize: 11, marginTop: 2 }}>{fmt.date(l.t)} · {fmt.time(l.t)}</div>
                    </div>
                  </Row>
                ))}
              </Col>
            )}
          </Card>
          <Card>
            <SectionTitle icon="server">Environment</SectionTitle>
            <Col gap={0}>
              {env.map(([k, v], i) => (
                <Row key={k} justify="space-between" style={{ padding: "10px 0", borderTop: i ? "1px solid var(--border-1)" : 0, fontSize: 13.5, gap: 12 }}><span className="muted" style={{ whiteSpace: "nowrap" }}>{k}</span><span className="mono" style={{ fontWeight: 500, whiteSpace: "nowrap" }}>{v}</span></Row>
              ))}
            </Col>
          </Card>

          {/* data files freshness */}
          {data.files && data.files.length > 0 && (
            <Card>
              <SectionTitle icon="files">Data freshness</SectionTitle>
              <Col gap={0}>
                {data.files.map((f, i) => (
                  <Row key={f.key} justify="space-between" align="center" style={{ padding: "9px 0", borderTop: i ? "1px solid var(--border-1)" : 0, fontSize: 13, gap: 12 }}>
                    <Row gap={8}><span className={"dot " + (f.exists ? "dot-ok" : "dot-warn")} style={{ width: 7, height: 7 }} /><span className="muted">{f.key}</span></Row>
                    <span className="mono muted-2" style={{ fontSize: 11.5 }}>{f.exists ? relTime(f.mtime) : "missing"}</span>
                  </Row>
                ))}
              </Col>
            </Card>
          )}
        </Col>
      </div>
    </div>
  );
}
window.SystemStatus = SystemStatus;
