// RUT241 eSIM Auto Provisioning — eSIM Management page (spec §26/§29).
// Regional eSIM pool summary (reserved/active/available per region) plus
// a form to add new pool profiles. Gated at view_provider_credentials
// (super_admin only — see lib/rut241Roles.ts's explicit "production
// admins cannot access provider credentials" rule) — technical_admin
// and production_admin never even see this page's data, they only see
// per-router masked eSIM status on the router detail page.
//
// Activation codes/ICCIDs are never displayed raw here either — the
// pool summary only ever returns counts and (per lib/esimProvisioning.ts)
// masked ICCID last-4, matching spec §27's "never displayed raw" rule.
//
// Reuses SectionLabel/EmptyNote/MiniField/ActionButton/ModalError/
// adminInputStyle/adminSelectStyle from admin-assets-page.jsx, AdminShell
// from admin-shell.jsx, and RUT241_REGION_LABELS from
// admin-rut241-dashboard-page.jsx — must load after all three.

function AdminRut241EsimPage({ onNavigate }) {
  const [admin, setAdmin] = useState(null);
  const [status, setStatus] = useState("loading");
  const [summary, setSummary] = useState([]);
  const [error, setError] = useState("");
  const [showAdd, setShowAdd] = useState(false);
  const [canManage, setCanManage] = useState(false);

  const load = () => {
    Promise.all([
      fetch("/api/admin/me", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
      fetch("/api/admin/rut241/me", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
    ])
      .then(([me, rut241Me]) => {
        if (!rut241Me.permissions.includes("view_provider_credentials")) {
          onNavigate("admin-rut241-dashboard");
          return;
        }
        setAdmin(me.admin);
        setCanManage(true);
        return fetch("/api/admin/rut241/esim-pool", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject()));
      })
      .then((data) => {
        if (data) { setSummary(data.summary || []); setStatus("ready"); }
      })
      .catch(() => onNavigate("admin-login"));
  };

  useEffect(load, []); // eslint-disable-line react-hooks/exhaustive-deps -- mount-only

  if (status === "loading") {
    return <section style={{ background: "#fff", minHeight: "calc(100vh - 88px)" }} />;
  }

  return (
    <AdminShell admin={admin} page="admin-rut241-dashboard" onNavigate={onNavigate}
      subtitle="RUT241 eSIM Auto Provisioning" title="eSIM management."
      actions={canManage && <ActionButton onClick={() => setShowAdd(true)} testId="rut241-esim-add">+ Add profile</ActionButton>}
    >
      {error && <ModalError>{error}</ModalError>}

      <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "rgba(0,0,0,0.6)", marginBottom: 28, maxWidth: 640, lineHeight: 1.6 }}>
        Two independent regional eSIM pools — UK/Europe and USA/North America. Activation codes are encrypted at rest and never shown raw; only a masked ICCID is ever displayed.
      </div>

      <SectionLabel>Pool summary</SectionLabel>
      {summary.length === 0 ? (
        <EmptyNote>No eSIM profiles in the pool yet.</EmptyNote>
      ) : (
        <div style={{ display: "flex", gap: 20, flexWrap: "wrap" }}>
          {summary.map((s) => (
            <div key={s.region} style={{ background: "rgba(0,0,0,0.02)", border: "1px solid rgba(0,0,0,0.14)", padding: "18px 22px", minWidth: 220 }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15, textTransform: "uppercase", marginBottom: 14 }}>
                {RUT241_REGION_LABELS[s.region] || s.region}
              </div>
              <Rut241EsimStatRow label="Available" value={s.available} />
              <Rut241EsimStatRow label="Reserved" value={s.reserved} />
              <Rut241EsimStatRow label="Active" value={s.active} />
              <Rut241EsimStatRow label="Total" value={s.total} strong />
            </div>
          ))}
        </div>
      )}

      {showAdd && (
        <Rut241AddEsimModal
          onCancel={() => setShowAdd(false)}
          onSaved={() => { setShowAdd(false); load(); }}
        />
      )}
    </AdminShell>
  );
}

function Rut241EsimStatRow({ label, value, strong }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "5px 0", borderTop: strong ? "1px solid rgba(0,0,0,0.15)" : "none", marginTop: strong ? 8 : 0, paddingTop: strong ? 10 : 5 }}>
      <span style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "rgba(0,0,0,0.55)" }}>{label}</span>
      <span style={{ fontFamily: "var(--font-body)", fontSize: 14, fontWeight: strong ? 700 : 500, color: "#000" }}>{value}</span>
    </div>
  );
}

function Rut241AddEsimModal({ onCancel, onSaved }) {
  const [region, setRegion] = useState("UK_EU");
  const [profileLabel, setProfileLabel] = useState("");
  const [iccid, setIccid] = useState("");
  const [activationCode, setActivationCode] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  const save = async () => {
    if (!profileLabel.trim()) { setError("A profile label is required."); return; }
    setSaving(true);
    setError("");
    try {
      const res = await fetch("/api/admin/rut241/esim-pool", {
        method: "POST", credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ region, profileLabel: profileLabel.trim(), iccid: iccid.trim() || undefined, activationCode: activationCode.trim() || undefined }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { setError(data.error || "Couldn't add that profile."); setSaving(false); return; }
      onSaved();
    } catch {
      setError("Couldn't reach the server. Check your connection and try again.");
      setSaving(false);
    }
  };

  return (
    <ModalShell title="Add eSIM profile to pool" onCancel={onCancel}>
      {error && <ModalError>{error}</ModalError>}
      <MiniField label="Region">
        <select value={region} onChange={(e) => setRegion(e.target.value)} style={adminSelectStyle}>
          {Object.entries(RUT241_REGION_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
        </select>
      </MiniField>
      <MiniField label="Profile label">
        <input value={profileLabel} onChange={(e) => setProfileLabel(e.target.value)} placeholder="e.g. UK-EU-POOL-0042" style={adminInputStyle} />
      </MiniField>
      <MiniField label="ICCID (optional — stored encrypted, only last 4 digits ever shown)">
        <input value={iccid} onChange={(e) => setIccid(e.target.value)} style={adminInputStyle} />
      </MiniField>
      <MiniField label="Activation code (optional — stored encrypted, never displayed raw)">
        <input value={activationCode} onChange={(e) => setActivationCode(e.target.value)} style={adminInputStyle} />
      </MiniField>
      <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
        <ActionButton onClick={onCancel}>Cancel</ActionButton>
        <ActionButton onClick={save} disabled={saving}>{saving ? "Saving…" : "Add to pool"}</ActionButton>
      </div>
    </ModalShell>
  );
}

Object.assign(window, { AdminRut241EsimPage });
