// RUT241 eSIM Auto Provisioning — Dashboard (spec §39). Landing page for
// the "RUT241 eSIM" nav item — admin-only (super_admin / technical_admin
// / production_admin, see admin-shell.jsx's ADMIN_NAV_ITEMS + backend's
// lib/rut241Roles.ts), never visible to customers.
//
// Shows fleet totals by region + status, then a set of quick-nav cards
// into the rest of the RUT241 area (Add RUT241, All Routers, status
// sub-views, eSIM Management, Configurations, Audit Log) — mirroring
// the sidebar sub-nav described in the spec (Dashboard / + Add RUT241 /
// All Routers / Waiting for Connection / Provisioning / Ready / Failed /
// eSIM Management / Configurations / Logs), rendered here as one page
// rather than ten separate top-level nav items (keeps AdminShell's
// sidebar from ballooning — see admin-shell.jsx's single "RUT241 eSIM"
// entry, which always lands here first).
//
// Reuses SectionLabel/EmptyNote/ActionButton/adminNavBtnStyle from
// admin-assets-page.jsx, and AdminShell from admin-shell.jsx — must
// load after both (see index.html).

const RUT241_REGION_LABELS = { UK_EU: "UK / Europe", US_NA: "USA / North America" };

const RUT241_STATUS_BUCKETS = [
  { key: "ONLINE", label: "Ready", tone: "good" },
  { key: "WAITING", label: "Waiting for connection", tone: "neutral" },
  { key: "PROVISIONING", label: "Provisioning", tone: "neutral" },
  { key: "FAULT", label: "Failed / needs attention", tone: "bad" },
];

function rut241StatTone(tone) {
  if (tone === "good") return "rgba(20,140,60,0.95)";
  if (tone === "bad") return "rgba(190,40,40,0.95)";
  return "#000";
}

function AdminRut241DashboardPage({ onNavigate }) {
  const [state, setState] = useState({ status: "loading", admin: null, me: null, dashboard: null });
  const [error, setError] = useState("");

  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())),
      fetch("/api/admin/rut241/dashboard", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
    ])
      .then(([me, rut241Me, dashboard]) => {
        setState({ status: "ready", admin: me.admin, me: rut241Me, dashboard });
      })
      .catch(() => onNavigate("admin-login"));
  };

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

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

  const { dashboard, me } = state;
  const canAdd = me.permissions.includes("add_router");
  const canManageConfig = me.permissions.includes("manage_config_templates");
  const canViewProvider = me.permissions.includes("view_provider_credentials");
  const canViewLogs = me.permissions.includes("view_logs");

  const byStatus = Object.fromEntries((dashboard.byStatus || []).map((r) => [r.bucket, r.n]));
  const byRegion = dashboard.byRegion || [];

  return (
    <AdminShell admin={state.admin} page="admin-rut241-dashboard" onNavigate={onNavigate}
      subtitle="RUT241 eSIM Auto Provisioning" title="RUT241 fleet."
      actions={canAdd && (
        <ActionButton testId="rut241-add-router" onClick={() => onNavigate("admin-rut241-add")}>
          + Add RUT241
        </ActionButton>
      )}
    >
      {error && <ModalError>{error}</ModalError>}

      <div style={{
        fontFamily: "var(--font-body)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase",
        color: "rgba(0,0,0,0.4)", marginBottom: 28,
      }}>
        Signed in as <strong style={{ color: "#000" }}>{me.role.replace(/_/g, " ")}</strong>
      </div>

      <SectionLabel>Fleet totals</SectionLabel>
      <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginBottom: 40 }}>
        <Rut241StatCard label="Total routers" value={dashboard.total} onClick={() => onNavigate("admin-rut241-fleet")} />
        {RUT241_STATUS_BUCKETS.map((b) => (
          <Rut241StatCard
            key={b.key} label={b.label} value={byStatus[b.key] || 0} tone={b.tone}
            onClick={() => onNavigate("admin-rut241-fleet", { statusBucket: b.key })}
          />
        ))}
      </div>

      <SectionLabel>By region</SectionLabel>
      <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginBottom: 40 }}>
        {byRegion.length === 0 ? (
          <EmptyNote>No routers registered yet.</EmptyNote>
        ) : byRegion.map((r) => (
          <Rut241StatCard
            key={r.region} label={RUT241_REGION_LABELS[r.region] || r.region} value={r.n}
            onClick={() => onNavigate("admin-rut241-fleet", { region: r.region })}
          />
        ))}
      </div>

      <SectionLabel>Fleet management</SectionLabel>
      <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginBottom: 40 }}>
        <Rut241NavCard title="All routers" desc="Full fleet table — filter by region, status, connection method, or search." onClick={() => onNavigate("admin-rut241-fleet")} />
        {canAdd && (
          <Rut241NavCard title="+ Add RUT241" desc="Photograph or upload a label, or enter details manually." onClick={() => onNavigate("admin-rut241-add")} />
        )}
        <Rut241NavCard title="eSIM Management" desc="Regional eSIM pool — reserved / active / available profiles." onClick={() => onNavigate("admin-rut241-esim")} />
        {canManageConfig && (
          <Rut241NavCard title="Configurations" desc="Base configuration profiles for UK/EU and US/NA — versions and files." onClick={() => onNavigate("admin-rut241-config")} />
        )}
        {!canManageConfig && canViewProvider === false && (
          <Rut241NavCard title="Configurations" desc="View the current base configuration profile files." onClick={() => onNavigate("admin-rut241-config")} />
        )}
        {canViewLogs && (
          <Rut241NavCard title="Audit Log" desc="Every RUT241 action, by whom, and when." onClick={() => onNavigate("admin-rut241-fleet", { openAuditLog: true })} />
        )}
      </div>
    </AdminShell>
  );
}

function Rut241StatCard({ label, value, tone, onClick }) {
  return (
    <button
      type="button" onClick={onClick}
      style={{
        background: "rgba(0,0,0,0.02)", border: "1px solid rgba(0,0,0,0.14)",
        padding: "18px 22px", minWidth: 150, textAlign: "left", cursor: "pointer",
        fontFamily: "var(--font-body)",
      }}
    >
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 30, color: rut241StatTone(tone) }}>{value}</div>
      <div style={{ fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(0,0,0,0.5)", marginTop: 6 }}>{label}</div>
    </button>
  );
}

function Rut241NavCard({ title, desc, onClick }) {
  return (
    <button
      type="button" onClick={onClick}
      style={{
        background: "#000", color: "#fff", border: "1px solid #000",
        padding: "20px 22px", minWidth: 220, maxWidth: 280, textAlign: "left", cursor: "pointer",
        fontFamily: "var(--font-body)", flex: "1 1 220px",
      }}
    >
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15, textTransform: "uppercase", marginBottom: 8 }}>{title}</div>
      <div style={{ fontSize: 12, color: "rgba(255,255,255,0.7)", lineHeight: 1.5 }}>{desc}</div>
    </button>
  );
}

Object.assign(window, { AdminRut241DashboardPage, RUT241_REGION_LABELS });
