/* MedBridge — Live FHIR / HL7 integration monitor */

function EndpointCard({ e }) {
  const { ago } = window.MB.util;
  const statusLabel = { on: "Connected", degraded: "Degraded", sandbox: "Sandbox", off: "Offline" }[e.status];
  return (
    <div className="card" style={{ padding: 0 }}>
      <div style={{ padding: "14px 16px" }}>
        <div className="row gap8" style={{ marginBottom: 10 }}>
          <span className={`sdot sdot-${e.status} ${e.status === "on" ? "live" : ""}`} />
          <div className="grow"><div className="fw7" style={{ fontSize: 13.5 }}>{e.name}</div><div className="muted" style={{ fontSize: 11.5 }}>{e.scope}</div></div>
          <Badge kind={e.status === "on" ? "good" : e.status === "degraded" ? "warn" : e.status === "sandbox" ? "info" : "neutral"}>{statusLabel}</Badge>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 4 }}>
          <div><div className="muted" style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>Latency</div><div className="mono fw7" style={{ fontSize: 15, color: e.latency > 500 ? "var(--mb-warn)" : "var(--text)" }}>{e.latency}<small style={{ fontSize: 10, color: "var(--text-3)" }}>ms</small></div></div>
          <div><div className="muted" style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>Queries</div><div className="mono fw7" style={{ fontSize: 15 }}>{e.queriesToday.toLocaleString()}</div></div>
          <div><div className="muted" style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>Uptime</div><div className="mono fw7" style={{ fontSize: 15, color: e.uptime < 99 ? "var(--mb-warn)" : "var(--mb-good)" }}>{e.uptime}%</div></div>
        </div>
      </div>
      <div className="row gap8" style={{ padding: "9px 16px", borderTop: "1px solid var(--hairline)", background: "var(--surface-2)" }}>
        <Badge kind="neutral">{e.standard}</Badge>
        {e.sites > 0 && <span className="muted" style={{ fontSize: 11.5 }}>{e.sites} site{e.sites > 1 ? "s" : ""}</span>}
        <span className="grow" />
        <span className="muted mono" style={{ fontSize: 10.5 }}>last msg {ago(e.lastMsg)}</span>
      </div>
      {e.msg && <div style={{ padding: "8px 16px", fontSize: 11.5, color: e.status === "degraded" ? "var(--mb-warn)" : "var(--text-3)", borderTop: "1px solid var(--hairline)" }}><Icon name="info" size={12} style={{ verticalAlign: "-2px" }} /> {e.msg}</div>}
    </div>
  );
}

function LiveLog() {
  const { logPool } = window.MB;
  const idRef = useRefMB(1000);
  const mk = (isNew) => {
    const ev = logPool.events[Math.floor(Math.random() * logPool.events.length)];
    const fac = logPool.facilities[Math.floor(Math.random() * logPool.facilities.length)];
    const score = ev.kind === "score" ? [62, 75, 87, 100, 88, 75, 50][Math.floor(Math.random() * 7)] : null;
    return { id: idRef.current++, t: new Date(), ev, fac, score, isNew };
  };
  const [rows, setRows] = useStateMB(() => Array.from({ length: 13 }, () => { const r = mk(false); r.t = window.MB.util.minsAgo(Math.random() * 14); return r; }).sort((a, b) => b.t - a.t));

  useEffectMB(() => {
    const id = setInterval(() => setRows((rs) => [mk(true), ...rs].slice(0, 26)), 2400);
    return () => clearInterval(id);
  }, []);

  const tagColor = (k) => ({ transfer: ["var(--purple-bg)", "var(--purple)"], admit: ["var(--info-bg)", "var(--info)"], discharge: ["var(--surface-3)", "var(--text-2)"], query: ["var(--primary-light)", "var(--primary-dark)"], score: ["var(--mb-good-bg)", "var(--mb-good)"] }[k]);

  return (
    <Card title="Live message stream" icon="activity" bodyClass="flush"
      action={<span className="row gap6" style={{ fontSize: 11.5, fontWeight: 600, color: "var(--mb-good)" }}><span className="sdot sdot-on live" />LIVE · HL7 v2 + FHIR R4</span>}>
      <div className="logfeed" style={{ maxHeight: 420, overflow: "auto" }}>
        {rows.map((r) => {
          const [bg, fg] = tagColor(r.ev.kind);
          return (
            <div key={r.id} className={`logrow ${r.isNew ? "new" : ""}`}>
              <span className="muted">{window.MB.util.fmtT(r.t)}</span>
              <span className="log-tag" style={{ background: bg, color: fg }}>{r.ev.tag}</span>
              <span><b style={{ fontWeight: 600 }}>{r.fac}</b> <span className="muted">· {r.ev.label}</span>{r.score != null && <span className="muted"> → </span>}{r.score != null && <span style={{ color: scoreColor(r.score), fontWeight: 700 }}>{r.score}%</span>}</span>
              <span className="muted" style={{ fontSize: 10.5 }}>{r.ev.kind === "score" ? "Tier 3 stored" : r.ev.kind === "query" ? "discarded" : "ack"}</span>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

function Integration() {
  const { endpoints } = window.MB;
  const totalQ = endpoints.reduce((s, e) => s + e.queriesToday, 0);
  const online = endpoints.filter((e) => e.status === "on").length;
  const avgLat = Math.round(endpoints.filter((e) => e.status === "on").reduce((s, e) => s + e.latency, 0) / online);

  return (
    <div className="content"><div className="pad" style={{ maxWidth: 1400, margin: "0 auto" }}>
      <div className="page-head">
        <div><h1>Integration Monitor</h1><div className="ph-sub">Federated FHIR R4 / HL7 v2 connections · data residency AWS ca-central-1 (Montreal)</div></div>
        <div className="row gap8"><Badge kind="good" icon="shield">AES-256 · TLS 1.3</Badge><Badge kind="neutral">SMART on FHIR · OAuth 2.0</Badge></div>
      </div>

      <div className="kpi-row" style={{ marginBottom: 16 }}>
        <Kpi label="Queries today" icon="send" value={totalQ.toLocaleString()} sub="across all endpoints" />
        <Kpi label="Endpoints online" icon="shield" value={online} unit={`/${endpoints.length}`} sub="1 degraded · 1 sandbox" accent="var(--mb-good)" />
        <Kpi label="Avg query latency" icon="clock" value={avgLat} unit="ms" sub="connected sites" />
        <Kpi label="Data residency" icon="check" value="100%" sub="Canadian infrastructure" accent="var(--mb-good)" />
      </div>

      <div className="section-title" style={{ marginBottom: 10 }}>EMR &amp; system endpoints</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(330px, 1fr))", gap: 14, marginBottom: 20 }}>
        {endpoints.map((e) => <EndpointCard key={e.name} e={e} />)}
      </div>

      <LiveLog />
    </div></div>
  );
}

Object.assign(window, { Integration });
