// Mission Control — Command OS's standalone fleet-operations screen.
//
// Deliberately NOT rendered inside <AdminShell> (see admin-shell.jsx) — the
// customer explicitly confirmed this is "a new full page screen... a
// complete separate mission control area" with its own top bar (asset
// picker / search / notifications / user) and its own left sidebar
// (Live Map, Fleet Health, Power, Connectivity, Cameras, Alerts,
// Incidents — the full COMMAND OS sub-tree). Reached from the admin
// sidebar's "Mission Control" nav item (see MC_ENTRY_NAV_ID in
// admin-shell.jsx) via onNavigate("mission-control").
//
// v1 scope (confirmed with the customer — "focus on schema + Mission
// Control UI", full COMMAND OS tree "we can revisit" later): only Fleet
// Health (asset index + per-asset detail matching the mock-up) is fully
// built. Every other nav item renders a "Coming soon" placeholder using
// the exact same pattern UM_ComingSoon already established, so the wider
// nav tree is visibly present (not forgotten) without pretending it's
// built.
//
// Data model per asset (GET /api/admin/mission-control/assets/:id):
//   unit       — asset_units row (+ product/company names)
//   telemetry  — unit_telemetry demo-data fallback (lib/telemetry.ts),
//                ALWAYS present, used for fields with no vendor
//                equivalent yet (Mains Power connected?, Controls
//                toggles, Live Power Draw, Internet Router fallback)
//   victron    — { installation, devices[] } or null if not linked yet.
//                devices[].device_role: shunt | mppt_1 | mppt_2 | mains_charger
//                devices[].cached_fields_json: JSON string of VRM code -> value
//   ajax       — { hub, devices[] } or null if not linked yet.
//   teltonika  — a single teltonika_devices row, or null if not linked yet.
//
// Real vendor data always wins over demo telemetry when present — see
// MC_pick() below. Cards for data that has NO demo-telemetry equivalent
// (Energy Storage, System Status) show an honest "not linked yet" empty
// state instead of inventing numbers, per the customer's own framing:
// "we would need to work on every single data string... that connects
// to either victron, ajax or teltonika."

const MC_NAV_ITEMS = [
  { id: "fleet-health", label: "Fleet Health" },
  { id: "live-map", label: "Live Map" },
  { id: "power", label: "Power" },
  { id: "connectivity", label: "Connectivity" },
  { id: "cameras", label: "Cameras" },
  { id: "alerts", label: "Alerts" },
  { id: "incidents", label: "Incidents" },
];

function MissionControlPage({ onNavigate }) {
  const [state, setState] = useState({ status: "loading", admin: null, fleet: [] });
  const [section, setSection] = useState("fleet-health");
  const [selectedAssetId, setSelectedAssetId] = useState(null);
  const [search, setSearch] = useState("");

  const loadFleet = () => {
    Promise.all([
      fetch("/api/admin/me", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
      fetch("/api/admin/mission-control/fleet", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
    ])
      .then(([me, fleetRes]) => {
        setState({ status: "ready", admin: me.admin, fleet: fleetRes.fleet || [] });
      })
      .catch(() => onNavigate("admin-login"));
  };

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

  const handleSelectSection = (id) => {
    setSection(id);
    setSelectedAssetId(null);
  };

  const handleSelectAsset = (id) => {
    setSection("fleet-health");
    setSelectedAssetId(id);
  };

  let body;
  if (state.status === "loading") {
    body = <MC_EmptyNote>Loading fleet&hellip;</MC_EmptyNote>;
  } else if (section === "fleet-health" && selectedAssetId != null) {
    body = (
      <MC_AssetDetail
        assetId={selectedAssetId}
        onBack={() => setSelectedAssetId(null)}
      />
    );
  } else if (section === "fleet-health") {
    body = (
      <MC_FleetHealthIndex
        fleet={state.fleet}
        search={search}
        onSelectAsset={handleSelectAsset}
      />
    );
  } else {
    body = <MC_ComingSoon item={MC_NAV_ITEMS.find((n) => n.id === section)} />;
  }

  return (
    <MC_Shell
      admin={state.admin}
      section={section}
      onSelectSection={handleSelectSection}
      onNavigate={onNavigate}
      fleet={state.fleet}
      onSelectAsset={handleSelectAsset}
      search={search}
      onSearchChange={setSearch}
    >
      {body}
    </MC_Shell>
  );
}

// ─────────────────────────────── Shell ───────────────────────────────

function MC_Shell({ admin, section, onSelectSection, onNavigate, fleet, onSelectAsset, search, onSearchChange, children }) {
  const handleLogout = async () => {
    try { await fetch("/api/admin/logout", { method: "POST", credentials: "same-origin" }); }
    finally { onNavigate("home"); }
  };

  const filteredFleet = search
    ? fleet.filter((a) => (a.serial_number || "").toLowerCase().includes(search.toLowerCase()))
    : fleet;

  return (
    <section style={{ background: "#0B0C0E", color: "#fff", minHeight: "calc(100vh - 88px)", display: "flex", flexDirection: "column" }}>
      {/* Top bar */}
      <header
        data-testid="mission-control-topbar"
        style={{
          display: "flex", alignItems: "center", gap: 20,
          padding: "14px 28px", borderBottom: "1px solid rgba(255,255,255,0.1)",
          background: "#111318", flexWrap: "wrap",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15,
            letterSpacing: "0.08em", color: "#fff", textTransform: "uppercase",
          }}>Solo Command</div>
          <div style={{
            fontFamily: "var(--font-body)", fontSize: 10, letterSpacing: "0.28em",
            textTransform: "uppercase", color: "rgba(255,255,255,0.6)", fontWeight: 500,
          }}>Mission Control</div>
        </div>

        {/* Asset picker */}
        <select
          value=""
          onChange={(e) => { if (e.target.value) onSelectAsset(Number(e.target.value)); }}
          data-testid="mission-control-asset-picker"
          style={{
            background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.18)",
            color: "#fff", padding: "9px 12px", fontFamily: "var(--font-body)", fontSize: 12.5,
            minWidth: 200,
          }}
        >
          <option value="">Jump to asset&hellip;</option>
          {fleet.map((a) => (
            <option key={a.id} value={a.id}>{a.serial_number} — {a.product_name}</option>
          ))}
        </select>

        {/* Search */}
        <input
          type="text" value={search} onChange={(e) => onSearchChange(e.target.value)}
          placeholder="Search serial number&hellip;"
          data-testid="mission-control-search"
          style={{
            flex: "1 1 220px", minWidth: 180, background: "rgba(255,255,255,0.06)",
            border: "1px solid rgba(255,255,255,0.18)", color: "#fff",
            padding: "9px 12px", fontFamily: "var(--font-body)", fontSize: 12.5, outline: "none",
          }}
        />

        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 16 }}>
          <button
            type="button" title="Notifications" data-testid="mission-control-notifications"
            style={{
              background: "none", border: "1px solid rgba(255,255,255,0.2)", borderRadius: "50%",
              width: 34, height: 34, color: "rgba(255,255,255,0.8)", cursor: "pointer", fontSize: 14,
            }}
          >&#128276;</button>
          {admin && (
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{
                width: 30, height: 30, borderRadius: "50%", background: "#fff",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontFamily: "var(--font-body)", fontSize: 12, fontWeight: 600, color: "#000",
              }}>{(admin.name || admin.email || "?").slice(0, 1).toUpperCase()}</div>
              <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "rgba(255,255,255,0.6)" }}>{admin.email}</div>
            </div>
          )}
          <button
            type="button" onClick={() => onNavigate("admin-assets")} data-testid="mission-control-back-to-admin"
            style={{
              background: "none", border: "1px solid rgba(255,255,255,0.25)", color: "rgba(255,255,255,0.75)",
              cursor: "pointer", padding: "8px 14px", fontFamily: "var(--font-body)", fontSize: 10.5,
              fontWeight: 500, letterSpacing: "0.1em", textTransform: "uppercase",
            }}
          >&larr; Admin</button>
          <button
            type="button" onClick={handleLogout} data-testid="mission-control-logout"
            style={{
              background: "none", border: "1px solid rgba(255,255,255,0.25)", color: "rgba(255,255,255,0.75)",
              cursor: "pointer", padding: "8px 14px", fontFamily: "var(--font-body)", fontSize: 10.5,
              fontWeight: 500, letterSpacing: "0.1em", textTransform: "uppercase",
            }}
          >Sign out</button>
        </div>
      </header>

      <div style={{ display: "flex", flex: 1 }}>
        {/* Sidebar */}
        <aside
          data-testid="mission-control-sidebar"
          style={{
            width: 220, flex: "0 0 220px", borderRight: "1px solid rgba(255,255,255,0.1)",
            display: "flex", flexDirection: "column", padding: "22px 0",
          }}
        >
          <nav style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {MC_NAV_ITEMS.map((item) => {
              const active = section === item.id;
              return (
                <button
                  key={item.id} type="button" onClick={() => onSelectSection(item.id)}
                  data-testid={`mission-control-nav-${item.id}`}
                  style={{
                    background: active ? "rgba(255,255,255,0.06)" : "none",
                    border: "none",
                    borderLeft: `2px solid ${active ? "#fff" : "transparent"}`,
                    color: active ? "#fff" : "rgba(255,255,255,0.55)",
                    textAlign: "left", cursor: "pointer", padding: "12px 22px",
                    fontFamily: "var(--font-body)", fontSize: 12.5,
                    fontWeight: active ? 600 : 500, letterSpacing: "0.06em",
                  }}
                >{item.label}</button>
              );
            })}
          </nav>

          {/* Wider COMMAND OS tree — visible but deliberately inert in v1
              (customer: "let's make sure we don't forget the wide scope
              but we can revisit"). Keeping these listed, disabled, and
              clearly marked rather than omitted so the roadmap stays
              visible in the product itself, not just in docs. */}
          <div style={{ marginTop: 28, padding: "0 22px" }}>
            <div style={{
              fontFamily: "var(--font-body)", fontSize: 9.5, letterSpacing: "0.2em",
              textTransform: "uppercase", color: "rgba(255,255,255,0.3)", marginBottom: 10,
            }}>Command OS (roadmap)</div>
            {["Fleet", "Assets", "Manufacturing", "Deployments", "Maintenance", "Analytics", "Administration"].map((label) => (
              <div key={label} style={{
                fontFamily: "var(--font-body)", fontSize: 11.5, color: "rgba(255,255,255,0.25)",
                padding: "6px 0",
              }}>{label}</div>
            ))}
          </div>
        </aside>

        <div style={{ flex: 1, minWidth: 0, padding: "28px 32px 80px", overflowX: "auto" }}>
          {children}
        </div>
      </div>
    </section>
  );
}

// ───────────────────────────── Fleet Health ─────────────────────────────

function MC_FleetHealthIndex({ fleet, search, onSelectAsset }) {
  const filtered = search
    ? fleet.filter((a) => (a.serial_number || "").toLowerCase().includes(search.toLowerCase()))
    : fleet;

  if (fleet.length === 0) {
    return <MC_EmptyNote>No assets found yet.</MC_EmptyNote>;
  }

  return (
    <div>
      <div style={{
        fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22,
        textTransform: "uppercase", marginBottom: 20, color: "#fff",
      }}>Fleet Health</div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 16 }}>
        {filtered.map((a) => (
          <button
            key={a.id} type="button" onClick={() => onSelectAsset(a.id)}
            data-testid={`mission-control-fleet-card-${a.id}`}
            style={{
              textAlign: "left", cursor: "pointer", background: "#15171C",
              border: "1px solid rgba(255,255,255,0.1)", padding: "18px 18px 16px",
              color: "#fff", display: "flex", flexDirection: "column", gap: 10,
            }}
          >
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div>
                <div style={{ fontFamily: "monospace", fontSize: 14, fontWeight: 600 }}>{a.serial_number}</div>
                <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "rgba(255,255,255,0.5)", marginTop: 2 }}>{a.product_name}</div>
              </div>
              <MC_StatusPill status={a.status} />
            </div>
            <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "rgba(255,255,255,0.45)" }}>
              {a.company_name || "Unassigned"}{a.region ? ` · ${a.region}` : ""}
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 4 }}>
              <MC_LinkChip label="Victron" linked={!!a.victron_linked} />
              <MC_LinkChip label="Ajax" linked={!!a.ajax_linked} />
              <MC_LinkChip label="Teltonika" linked={!!a.teltonika_linked} />
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

function MC_LinkChip({ label, linked }) {
  return (
    <span style={{
      fontFamily: "var(--font-body)", fontSize: 9.5, fontWeight: 600, letterSpacing: "0.04em",
      textTransform: "uppercase", padding: "3px 8px", borderRadius: 3,
      background: linked ? "#fff" : "rgba(255,255,255,0.06)",
      color: linked ? "#000" : "rgba(255,255,255,0.35)",
    }}>{label}</span>
  );
}

function MC_StatusPill({ status }) {
  const tones = {
    assigned: { bg: "#fff", fg: "#000" },
    deployed: { bg: "#fff", fg: "#000" },
    in_stock: { bg: "rgba(255,255,255,0.08)", fg: "rgba(255,255,255,0.6)" },
    maintenance: { bg: "rgba(255,255,255,0.4)", fg: "#000" },
  };
  const c = tones[status] || tones.in_stock;
  return (
    <span style={{
      background: c.bg, color: c.fg, fontFamily: "var(--font-body)", fontSize: 9.5,
      fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase",
      padding: "4px 9px", borderRadius: 3, whiteSpace: "nowrap",
    }}>{(status || "unknown").replace(/_/g, " ")}</span>
  );
}

// ───────────────────────────── Asset Detail ─────────────────────────────

function MC_AssetDetail({ assetId, onBack }) {
  const [state, setState] = useState({ status: "loading", data: null, error: "" });

  const load = () => {
    fetch(`/api/admin/mission-control/assets/${assetId}`, { credentials: "same-origin" })
      .then(async (r) => {
        const data = await r.json().catch(() => ({}));
        if (!r.ok) throw new Error(data.error || "Couldn't load this asset.");
        return data;
      })
      .then((data) => setState({ status: "ready", data, error: "" }))
      .catch((err) => setState({ status: "error", data: null, error: err.message }));
  };

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

  if (state.status === "loading") return <MC_EmptyNote>Loading asset&hellip;</MC_EmptyNote>;
  if (state.status === "error") return <MC_EmptyNote>{state.error}</MC_EmptyNote>;

  const { unit, telemetry, victron, ajax, teltonika } = state.data;

  // Victron sub-device lookups.
  const vDevices = (victron && victron.devices) || [];
  const findV = (role) => {
    const row = vDevices.find((d) => d.device_role === role);
    if (!row) return null;
    let fields = {};
    try { fields = JSON.parse(row.cached_fields_json || "{}"); } catch { /* ignore */ }
    return { row, fields };
  };
  const shunt = findV("shunt");
  const mppt1 = findV("mppt_1");
  const mppt2 = findV("mppt_2");
  const mainsCharger = findV("mains_charger");

  const ajaxHub = ajax && ajax.hub;

  const fmt = (n, dp) => (n === null || n === undefined ? "\u2014" : Number(n).toFixed(dp));
  const fmtUptime = (seconds) => {
    if (seconds === null || seconds === undefined) return "\u2014";
    const h = Math.floor(seconds / 3600);
    const d = Math.floor(h / 24);
    return d > 0 ? `${d}d ${h % 24}h` : `${h}h`;
  };

  const backAction = (
    <button
      type="button" onClick={onBack} data-testid="mission-control-asset-back"
      style={{
        background: "none", border: "1px solid rgba(255,255,255,0.3)", color: "rgba(255,255,255,0.8)",
        cursor: "pointer", padding: "9px 16px", fontFamily: "var(--font-body)", fontSize: 11,
        fontWeight: 500, letterSpacing: "0.12em", textTransform: "uppercase",
      }}
    >&larr; Fleet Health</button>
  );

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20, flexWrap: "wrap", gap: 12 }}>
        <div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, textTransform: "uppercase" }}>{unit.serial_number}</div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "rgba(255,255,255,0.5)", marginTop: 2 }}>
            {unit.product_name}{unit.company_name ? ` · ${unit.company_name}` : ""}
          </div>
        </div>
        {backAction}
      </div>

      <div style={{
        background: "#fff", border: "1px solid rgba(0,0,0,0.15)", padding: "32px",
        display: "grid", gridTemplateColumns: "280px 1fr 280px", gap: 28,
      }}>
        {/* Left column */}
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <MC_Card
            title="Energy Storage"
            badge={shunt ? { label: "Live", tone: "green" } : { label: "Not linked", tone: "grey" }}
            testId="mission-control-card-energy-storage"
          >
            {shunt ? (
              <>
                <MC_BigValue>{shunt.fields.SOC || "\u2014"}</MC_BigValue>
                <MC_Row label="Voltage" value={shunt.fields.V || "\u2014"} />
                <MC_Row label="Current" value={shunt.fields.I || "\u2014"} />
                <MC_Row label="Consumed Energy" value={shunt.fields.CE || "\u2014"} last />
              </>
            ) : (
              <MC_NotLinked hint="Connect this asset's Victron GlobalLink installation to see live shunt data." />
            )}
          </MC_Card>

          <MC_Card title="Mains Power" testId="mission-control-card-mains-power">
            {mainsCharger ? (
              <>
                <MC_BigValue small>{mainsCharger.fields.cSt || "\u2014"}</MC_BigValue>
                <MC_Row label="Output Voltage" value={mainsCharger.fields.c0V || "\u2014"} />
                <MC_Row label="Output Current" value={mainsCharger.fields.c0I || "\u2014"} last />
              </>
            ) : (
              <MC_BigValue small>{telemetry.mains_connected ? "Connected" : "Disconnected"}</MC_BigValue>
            )}
          </MC_Card>

          <MC_Card
            title="PV Charger"
            badge={mppt1 || mppt2 ? { label: "Live", tone: "green" } : undefined}
            testId="mission-control-card-pv-charger"
          >
            {(mppt1 || mppt2) ? (
              <>
                {mppt1 && <MC_Row label="Mppt 1" value={mppt1.fields.ScW || "\u2014"} />}
                {mppt2 && <MC_Row label="Mppt 2" value={mppt2.fields.ScW || "\u2014"} last />}
              </>
            ) : (
              <>
                <MC_BigValue>{fmt(telemetry.pv_power_w, 0)} W</MC_BigValue>
                <MC_Row label="Panel Voltage" value={`${fmt(telemetry.pv_panel_voltage_v, 2)} V`} />
                <MC_Row label="Output Current" value={`${fmt(telemetry.pv_output_current_a, 2)} A`} last />
              </>
            )}
          </MC_Card>

          <MC_Card title="Controls" testId="mission-control-card-controls">
            {!!unit.has_strobe && <MC_Row label="Strobe" value={telemetry.strobe_on ? "On" : "Off"} />}
            {!!unit.has_alarm && <MC_Row label="Armed" value={telemetry.armed_on ? "Armed" : "Disarmed"} />}
            {!!unit.has_cameras && <MC_Row label="Cameras" value={telemetry.cameras_on ? "On" : "Off"} last />}
            {!unit.has_strobe && !unit.has_alarm && !unit.has_cameras && (
              <div style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "rgba(0,0,0,0.4)" }}>No controls on this product.</div>
            )}
          </MC_Card>
        </div>

        {/* Center — product viewer */}
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
          <MC_StatusPill status={unit.status} />
          <div style={{ marginTop: 14 }}>
            <TowerSchematic width={220} height={340} stroke="#000" />
          </div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "rgba(0,0,0,0.55)", marginTop: 14, textAlign: "center" }}>{unit.product_name}</div>
          <div style={{ fontFamily: "monospace", fontSize: 12, color: "#000", marginTop: 4, textAlign: "center" }}>{unit.serial_number}</div>
        </div>

        {/* Right column */}
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <MC_Card title="Live Power Draw" testId="mission-control-card-power-draw">
            <MC_BigValue>{fmt(telemetry.power_w, 2)} W</MC_BigValue>
            <MC_Row label="Current" value={`${fmt(telemetry.power_current_a, 4)} A`} last />
          </MC_Card>

          <MC_Card
            title="Internet Router"
            badge={teltonika ? { label: teltonika.connection_state || "Live", tone: "green" } : undefined}
            testId="mission-control-card-internet-router"
          >
            {teltonika ? (
              <>
                <MC_Row label="Operator" value={teltonika.operator || "\u2014"} />
                <MC_Row label="Signal" value={teltonika.signal != null ? `${teltonika.signal}%` : "\u2014"} />
                <MC_Row label="WAN IP" value={teltonika.wan_ip || "\u2014"} />
                <MC_Row label="Firmware" value={teltonika.firmware || "\u2014"} />
                <MC_Row label="Temperature" value={teltonika.temperature != null ? `${teltonika.temperature} \u00b0C` : "\u2014"} />
                <MC_Row label="MAC" value={teltonika.mac || "\u2014"} last />
              </>
            ) : (
              <>
                <MC_Row label="Operator" value={telemetry.router_operator || "\u2014"} />
                <MC_Row label="Signal" value={telemetry.router_signal_percent != null ? `${fmt(telemetry.router_signal_percent, 0)}%` : "\u2014"} />
                <MC_Row label="WWAN IP" value={telemetry.router_wwan_ip || "\u2014"} />
                <MC_Row label="Firmware" value={telemetry.router_firmware || "\u2014"} last />
              </>
            )}
          </MC_Card>

          <MC_Card
            title="System Status"
            badge={ajaxHub ? { label: ajaxHub.online ? "Online" : "Offline", tone: ajaxHub.online ? "green" : "grey" } : undefined}
            testId="mission-control-card-system-status"
          >
            {ajaxHub ? (
              <>
                <MC_Row label="State" value={ajaxHub.state || "\u2014"} />
                <MC_Row label="Battery" value={ajaxHub.battery_level != null ? `${ajaxHub.battery_level}%` : "\u2014"} />
                <MC_Row label="GSM Signal" value={ajaxHub.gsm_signal_level != null ? `${ajaxHub.gsm_signal_level}%` : "\u2014"} />
                <MC_Row label="Firmware" value={ajaxHub.firmware_version || "\u2014"} last />
              </>
            ) : (
              <MC_NotLinked hint="Link this asset's Ajax hub to see live security-system status." />
            )}
          </MC_Card>
        </div>
      </div>

      {/* Bottom strip */}
      <div style={{
        marginTop: 20, background: "#15171C", border: "1px solid rgba(255,255,255,0.1)",
        padding: "18px 28px", display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 20,
      }}>
        <MC_StripStat label="Connectivity" value={teltonika ? (teltonika.connection_state || "\u2014") : "\u2014"} />
        <MC_StripStat label="GPS" value={teltonika && teltonika.latitude != null ? `${fmt(teltonika.latitude, 4)}, ${fmt(teltonika.longitude, 4)}` : "\u2014"} />
        <MC_StripStat label="Uptime" value={teltonika ? fmtUptime(teltonika.router_uptime) : "\u2014"} />
        <MC_StripStat label="Last Event" value="\u2014" />
        <MC_StripStat label="Alarms" value={ajaxHub ? (ajaxHub.state || "\u2014") : "\u2014"} />
      </div>
    </div>
  );
}

function MC_StripStat({ label, value }) {
  return (
    <div>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 9.5, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(255,255,255,0.4)", marginBottom: 6 }}>{label}</div>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "#fff", fontWeight: 500 }}>{value}</div>
    </div>
  );
}

function MC_NotLinked({ hint }) {
  return (
    <div style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "rgba(0,0,0,0.4)", lineHeight: 1.5 }}>{hint}</div>
  );
}

// ─────────────────────────── Shared primitives ───────────────────────────

function MC_Card({ title, badge, children, testId }) {
  return (
    <div data-testid={testId} style={{ background: "#fff", border: "1px solid rgba(0,0,0,0.15)", padding: "18px 18px 14px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
        <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 700, letterSpacing: "0.04em", textTransform: "uppercase", color: "#000" }}>{title}</div>
        {badge && <MC_Badge label={badge.label} tone={badge.tone} />}
      </div>
      {children}
    </div>
  );
}

function MC_Badge({ label, tone }) {
  const tones = {
    grey: { bg: "rgba(0,0,0,0.06)", fg: "rgba(0,0,0,0.45)" },
    blue: { bg: "#000", fg: "#fff" },
    green: { bg: "#000", fg: "#fff" },
  };
  const c = tones[tone] || tones.grey;
  return (
    <span style={{ background: c.bg, color: c.fg, fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase", padding: "4px 10px", borderRadius: 3 }}>{label}</span>
  );
}

function MC_BigValue({ children, small }) {
  return (
    <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: small ? 18 : 26, color: "#000", marginBottom: 10 }}>{children}</div>
  );
}

function MC_Row({ label, value, last }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "6px 0", borderBottom: last ? "none" : "1px solid rgba(0,0,0,0.1)", fontFamily: "var(--font-body)", fontSize: 12.5 }}>
      <span style={{ color: "rgba(0,0,0,0.45)" }}>{label}</span>
      <span style={{ color: "#000", fontWeight: 500 }}>{value}</span>
    </div>
  );
}

function MC_ComingSoon({ item }) {
  return (
    <div data-testid="mission-control-coming-soon" style={{
      background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.12)",
      padding: "60px 32px", textAlign: "center",
    }}>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(255,255,255,0.4)", marginBottom: 12, fontWeight: 500 }}>Coming soon</div>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, textTransform: "uppercase", color: "rgba(255,255,255,0.85)", marginBottom: 8 }}>{item ? item.label : ""}</div>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, color: "rgba(255,255,255,0.5)" }}>This part of Mission Control hasn't been built yet — it's on the roadmap.</div>
    </div>
  );
}

function MC_EmptyNote({ children }) {
  return (
    <div style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "rgba(255,255,255,0.5)", padding: "40px 0" }}>{children}</div>
  );
}

Object.assign(window, { MissionControlPage });
