(function(){
/* FORGE · Aetherion (Space) tenant — Traveler Station 1: Receiving + Incoming Inspection
   Wave A1 / Space / Agent #11 (traveler-A) · mounts at /traveler/receiving for aetherion.

   Mirrors pump ScreenStationReceiving (act4-screens.jsx:1496) but adapts for spaceflight:
     · TID radiation dose verification (ECSS-Q-ST-70 derating)
     · MIL-DTL-38999 III connector N₂ bag-and-purge gating (>12h)
     · Heritage docs (TRL-9 · ISS-6Y) chain-of-custody check
     · Mass weighing in grams (±2.0g vs declared)
     · COC hash on every accepted lot
     · Photo capture (auto-tagged: kit · WO · station)
     · PASS / HOLD / REJECT / NCR operator-grade buttons
     · Right rail: WO-AET-001 context, ITAR data hold marker, KESTREL-3 mission timeline
     · Emits RECEIVING_LOGGED on PASS with mass + heritage payload

   Babel-standalone, in-browser, no imports / exports.
   Globals expected: React, getActiveTenant(), navigate(),
   registerPumpRoute() OR registerSpaceRoute(), Pill, Btn (optional fallbacks below). */

const { useState: uSST, useEffect: uEST, useMemo: uMST, useRef: uRST } = React;

/* Light-theme palette (Wave 12D) — every alias resolves to the canonical
   tokens.css `[data-theme="light"]` block. The traveler station now reads
   as a sibling of dashboard.jsx (cream surface, dark ink). Accent stays a
   saturated blue (#2D5BEA) that reads on cream. */
const SP_INK = "var(--bg-0)";              // page bg (cream)
const SP_ACCENT = "#2D5BEA";               // mission blue on cream
const SP_SLATE = "var(--ink-3)";           // muted labels
const SP_LINE = "var(--line)";             // hairline divider
const SP_MONO = "var(--ink)";              // mono digit text (dark)
const SP_BG0 = "var(--bg-0)";
const SP_BG1 = "var(--bg-1)";
const SP_BG2 = "var(--bg-2)";
const SP_INK0 = "var(--ink)";
const SP_INK2 = "var(--ink-2)";
const SP_INK3 = "var(--ink-3)";
const SP_INK4 = "var(--ink-4)";
const SP_OK = "var(--ok)";
const SP_WARN = "var(--warn)";
const SP_ERR = "var(--err)";

const _label = { fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.10em", textTransform: "uppercase", color: SP_INK3 };

// Hoisted style atoms — extracted from inline JSX for react-doctor compliance.
const _str_avatarBase = {
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  borderRadius: "50%",
  background: "color-mix(in oklch, " + SP_ACCENT + " 18%, " + SP_BG2 + ")",
  color: SP_ACCENT,
  border: "1px solid color-mix(in oklch, " + SP_ACCENT + " 36%, " + SP_LINE + ")",
  fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.04em", fontWeight: 600,
};
const _str_pillBase = {
  display: "inline-flex", alignItems: "center",
  padding: "1px 7px", borderRadius: 3,
  fontFamily: "var(--font-mono)", fontSize: 12,
  letterSpacing: "0.05em", textTransform: "uppercase",
};
const _str_btnBase = {
  borderRadius: 3,
  fontFamily: "var(--font-ui)",
  cursor: "pointer", letterSpacing: "0.02em",
};
const _str_headerBase = {
  padding: "12px 16px",
  background: "color-mix(in oklch, " + SP_INK + " 92%, " + SP_BG2 + ")",
  color: SP_MONO, borderBottom: "1px solid " + SP_LINE,
  display: "flex", alignItems: "center", gap: 14,
};
const _str_kitTableHeaderBase = {
  display: "grid", gridTemplateColumns: "1.2fr 1.4fr 1fr 80px 90px 80px 110px",
  padding: "6px 12px", borderBottom: "1px solid var(--line, " + SP_LINE + ")",
  background: SP_BG2, position: "sticky", top: 0, zIndex: 2,
};
const _str_kitRowBase = {
  display: "grid", gridTemplateColumns: "1.2fr 1.4fr 1fr 80px 90px 80px 110px",
  padding: "9px 12px", borderBottom: "1px solid var(--line-soft, #E2E8F2)",
  alignItems: "center", fontSize: 12, cursor: "pointer",
  transition: "background 120ms ease",
};
const _str_kitHeadingBandBase = {
  display: "flex", alignItems: "center", gap: 12,
  marginBottom: 14, padding: 12,
  background: "color-mix(in oklch, " + SP_ACCENT + " 5%, " + SP_BG1 + ")",
  border: "1px solid " + SP_LINE, borderRadius: 4,
};
const _str_massWeighRowBase = {
  display: "flex", alignItems: "center", gap: 12,
  marginBottom: 16, padding: 12,
  border: "1px solid var(--line, " + SP_LINE + ")",
  borderRadius: 3, background: SP_BG1,
};
const _str_massInputBase = {
  flex: 1, padding: "8px 12px",
  fontFamily: "var(--font-mono)",
  fontSize: 18, fontWeight: 600,
  borderRadius: 3, outline: "0 solid transparent",
  textAlign: "right", letterSpacing: "0.02em",
};
const _str_opSelectStyle = {
  background: "color-mix(in oklch, " + SP_INK + " 75%, " + SP_BG1 + ")",
  color: SP_MONO,
  border: "1px solid " + SP_LINE, borderRadius: 3,
  fontFamily: "var(--font-mono)",
  fontSize: 12, padding: "4px 8px",
  outline: "0 solid transparent", cursor: "pointer",
};

/* ── helpers ─────────────────────────────────────────────────────────── */
function _now() {
  const t = new Date(), p = (n) => String(n).padStart(2, "0");
  return p(t.getHours()) + ":" + p(t.getMinutes()) + ":" + p(t.getSeconds());
}
function _iso() { return new Date().toISOString().slice(0, 19) + "Z"; }
function _initials(n) {
  if (!n) return "—";
  const parts = String(n).replace(/[^A-Za-z. ]/g, "").split(/\s+/).filter(Boolean);
  if (!parts.length) return "—";
  return ((parts[0][0] || "") + (parts[1] ? parts[1][0] : (parts[0][1] || ""))).toUpperCase();
}
/* SHA-256-shaped demo hash from input. Not cryptographic; deterministic. */
function _coc(seed) {
  const s = String(seed || ""); let h1 = 0x811c9dc5, h2 = 0xdeadbeef;
  for (let i = 0; i < s.length; i++) {
    const c = s.charCodeAt(i);
    h1 = Math.imul(h1 ^ c, 2654435761); h2 = Math.imul(h2 ^ c, 1597334677);
  }
  h1 = (h1 ^ (h1 >>> 16)) >>> 0; h2 = (h2 ^ (h2 >>> 13)) >>> 0;
  const part = (h1.toString(16) + h2.toString(16)).padStart(16, "0");
  return (part + part + part + part).slice(0, 64);
}
function _Avatar({ name, size = 32 }) {
  return <span style={{ ..._str_avatarBase, width: size, height: size }}>{_initials(name)}</span>;
}

/* Fallback Pill / Btn — defer to globals if registered, otherwise self-render. */
function _Pill({ tone, children }) {
  if (typeof Pill === "function") return React.createElement(Pill, { tone }, children);
  const map = {
    ok: { bg: "color-mix(in oklch, " + SP_OK + " 14%, transparent)", fg: SP_OK },
    warn: { bg: "color-mix(in oklch, " + SP_WARN + " 14%, transparent)", fg: SP_WARN },
    err: { bg: "color-mix(in oklch, " + SP_ERR + " 14%, transparent)", fg: SP_ERR },
    danger: { bg: "color-mix(in oklch, " + SP_ERR + " 14%, transparent)", fg: SP_ERR },
    accent: { bg: "color-mix(in oklch, " + SP_ACCENT + " 14%, transparent)", fg: SP_ACCENT },
  };
  const t = map[tone] || { bg: SP_BG2, fg: SP_INK3 };
  return <span style={{ ..._str_pillBase, background: t.bg, color: t.fg }}>{children}</span>;
}
function _Btn({ children, onClick, variant, size, tone }) {
  if (typeof Btn === "function") return React.createElement(Btn, { onClick, variant, size }, children);
  const sm = size === "sm";
  const tones = {
    pass: { fg: "#fff", bg: SP_OK, bd: SP_OK },
    hold: { fg: SP_INK0, bg: SP_BG2, bd: SP_LINE },
    reject: { fg: "#fff", bg: SP_ERR, bd: SP_ERR },
    ncr: { fg: "#fff", bg: SP_ACCENT, bd: SP_ACCENT },
  };
  const c = tones[tone] || (variant === "primary"
    ? { fg: "#fff", bg: SP_ACCENT, bd: SP_ACCENT }
    : { fg: SP_INK2, bg: "transparent", bd: SP_LINE });
  return <button onClick={onClick} style={{
    ..._str_btnBase,
    height: sm ? 24 : 30, padding: sm ? "0 9px" : "0 12px",
    background: c.bg, border: "1px solid " + c.bd, color: c.fg,
    fontSize: sm ? 11 : 12,
    fontWeight: variant === "primary" || tone ? 600 : 500,
  }}>{children}</button>;
}

/* Station header — operator dropdown, station label, ITAR class rating, mission clock. */
function _Header({ operator, onOp, ops, station, classRating, wo, missionT }) {
  const opt = { background: SP_INK, color: SP_MONO };
  return (
    <div style={_str_headerBase}>
      <_Avatar name={operator} size={34} />
      <div style={{ minWidth: 0 }}>
        <div style={{ ..._label, color: SP_SLATE, marginBottom: 2 }}>operator on station</div>
        <select id="ae-trav-receiving-f1" name="ae-trav-receiving-f1" value={operator} onChange={e => onOp(e.target.value)} style={_str_opSelectStyle}>
          {ops.map(o => <option key={o.id} value={o.name} style={opt}>{o.name} · {o.role}</option>)}
        </select>
      </div>
      <div style={{ flex: 1, minWidth: 0, paddingLeft: 18, borderLeft: "1px solid " + SP_LINE }}>
        <div style={{ fontSize: 13.5, color: SP_MONO, display: "flex", alignItems: "center", gap: 10, fontWeight: 500 }}>
          <span style={{ letterSpacing: "0.02em" }}>{station}</span>
          <span style={{ color: SP_SLATE }}>·</span>
          <span className="mono" style={{
            padding: "1px 7px", border: "1px solid " + SP_LINE,
            background: "color-mix(in oklch, " + SP_ACCENT + " 8%, transparent)",
            color: SP_ACCENT, borderRadius: 3, fontSize: 12, letterSpacing: "0.04em",
          }}>{classRating}</span>
        </div>
        <div className="mono" style={{ fontSize: 12, color: SP_SLATE, marginTop: 3, letterSpacing: "0.04em" }}>
          {wo} · station 1 of 4
        </div>
      </div>
      <div style={{ textAlign: "right" }}>
        <div style={{ ..._label, color: SP_SLATE }}>mission clock</div>
        <div className="mono tnum" style={{ fontSize: 18, color: SP_ACCENT, fontWeight: 600, marginTop: 2 }}>{missionT}</div>
      </div>
      <div style={{ paddingLeft: 14, borderLeft: "1px solid " + SP_LINE, textAlign: "right" }}>
        <div style={{ ..._label, color: SP_SLATE }}>shift A · UTC</div>
        <div className="mono tnum" style={{ fontSize: 13, color: SP_MONO, marginTop: 2 }}>{_now()}</div>
      </div>
    </div>
  );
}

/* ── Main screen ─────────────────────────────────────────────────────── */
function ScreenAetherionReceiving() {
  const tenant = (typeof getActiveTenant === "function") ? getActiveTenant() : (window.AETHERION_TENANT || {});

  const ops = [
    { id: "op-mss", name: "M. Sato",     role: "Mech Lead · ITAR-cleared (US)" },
    { id: "op-rkh", name: "R. Khanna",   role: "Receiving Tech · AS9100 lvl-2" },
    { id: "op-jvg", name: "J. Vega",     role: "Q&MA Inspector · NDT lvl-3" },
    { id: "op-tlu", name: "T. Lundberg", role: "Cleanroom Lead · Class 7" },
  ];
  const [operator, setOperator] = uSST(ops[1].name);

  /* Incoming kits — kit-level intake for KESTREL-3. */
  const seedKits = [
    { id: "KIT-AET-2026-0509-A", part: "KESTREL-3.20.01", part_name: "AAC Clyde Sirius OBC",
      supplier: "AAC Clyde Space", qty: 1, mass_g: 420.0, heritage: "TRL-9 · ISS-6Y",
      tid_dose: "32 krad(Si)", tid_cert: "ECSS-Q-ST-70-15B · 2026-04-30",
      connector: "MIL-DTL-38999 III · 19-35", n2_purge: "14h 22m",
      coc: "COC-AAC-2026-04-30-018", grn_iso: "2026-05-09T08:14Z", state: "awaiting", note: null },
    { id: "KIT-AET-2026-0509-B", part: "KESTREL-3.30.01", part_name: "Sodern Auriga CP star tracker",
      supplier: "Sodern", qty: 1, mass_g: 340.0, heritage: "TRL-8",
      tid_dose: "30 krad(Si)", tid_cert: "ECSS-Q-ST-70-15B · 2026-04-22",
      connector: "Glenair micro-D 21", n2_purge: "—",
      coc: "COC-SOD-2026-04-22-007", grn_iso: "2026-05-09T09:02Z", state: "awaiting", note: null },
    { id: "KIT-AET-2026-0509-C", part: "KESTREL-3.60.HG", part_name: "Honeybee solar-array hinge sub (rev C)",
      supplier: "Honeybee Robotics", qty: 4, mass_g: 268.4, heritage: "TRL-9 · Mars 2020",
      tid_dose: "—", tid_cert: "n/a (mech)", connector: "—", n2_purge: "—",
      coc: "COC-HBR-2026-05-05-021", grn_iso: "2026-05-09T10:48Z", state: "awaiting",
      note: "ECO-AET-0042 rev C · A286 + Belleville stack" },
    { id: "KIT-AET-2026-0508-D", part: "KESTREL-3.30.02", part_name: "Blue Canyon RWp050 reaction wheel",
      supplier: "Blue Canyon", qty: 3, mass_g: 270.0, heritage: "TRL-8",
      tid_dose: "30 krad(Si)", tid_cert: "ECSS-Q-ST-70-15B · 2026-04-15",
      connector: "MIL-DTL-38999 III · 11-35", n2_purge: "13h 04m",
      coc: "COC-BCT-2026-04-15-009", grn_iso: "2026-05-08T16:30Z", state: "passed",
      note: "PASS · 14h N₂ purge verified · COC chain ok" },
    { id: "KIT-AET-2026-0508-E", part: "KESTREL-3.10.01", part_name: "ISIS 12U structure base",
      supplier: "ISIS", qty: 1, mass_g: 1740.0, heritage: "TRL-9 · ISS-6Y",
      tid_dose: "—", tid_cert: "n/a (struct)", connector: "—", n2_purge: "—",
      coc: "COC-ISI-2026-05-02-014", grn_iso: "2026-05-08T11:22Z", state: "passed",
      note: "PASS · mass 1740.0g vs CAD 1740 ±2g · heritage ok" },
    { id: "KIT-AET-2026-0507-F", part: "KESTREL-3.20.02", part_name: "AAC Clyde Starbuck EPS",
      supplier: "AAC Clyde Space", qty: 1, mass_g: 760.0, heritage: "TRL-9 · ISS-6Y",
      tid_dose: "32 krad(Si)", tid_cert: "ECSS-Q-ST-70-15B · 2026-04-12",
      connector: "MIL-DTL-38999 III · 15-35", n2_purge: "11h 48m",
      coc: "COC-AAC-2026-04-12-006", grn_iso: "2026-05-07T14:55Z", state: "held",
      note: "HOLD · N₂ purge 11h 48m < 12h gate · re-bag scheduled" },
    { id: "KIT-AET-2026-0506-G", part: "KESTREL-3.80.01", part_name: "Glenair MIL-DTL-38999 harness loom",
      supplier: "Glenair", qty: 1, mass_g: 582.0, heritage: "TRL-9",
      tid_dose: "—", tid_cert: "n/a (passive)", connector: "MIL-DTL-38999 III · multi", n2_purge: "—",
      coc: "COC-GLN-2026-05-01-031", grn_iso: "2026-05-06T09:40Z", state: "rejected",
      note: "REJECT · over-braid pinhole at 0.42m · returned to Glenair" },
  ];

  const [kits, setKits] = uSST(seedKits);
  const [selectedId, setSelected] = uSST(seedKits[0].id);
  const [actLog, setActLog] = uSST([]);
  const [photoCount, setPhotos] = uSST(0);
  const [massInput, setMass] = uSST("");
  const [highlight, setHL] = uSST(null);
  const _hlRef = uRST(null);
  const [toast, setToast] = uSST(null);
  const _toastRef = uRST(null);
  const _emptyChecks = () => ({ coc_chain: false, heritage_doc: false, tid_cert: false, n2_purge: false, pkg_intact: false, surface_clean: false });
  const [checks, setChecks] = uSST(_emptyChecks());

  uEST(() => {
    const onTenant = () => {
      setKits(seedKits); setSelected(seedKits[0].id); setActLog([]);
      setPhotos(0); setMass(""); setChecks(_emptyChecks()); setToast(null);
      if (_hlRef.current) { clearTimeout(_hlRef.current); _hlRef.current = null; }
      if (_toastRef.current) { clearTimeout(_toastRef.current); _toastRef.current = null; }
    };
    if (typeof window !== "undefined") window.addEventListener("forge:tenant-change", onTenant);
    return () => {
      if (typeof window !== "undefined") window.removeEventListener("forge:tenant-change", onTenant);
      if (_hlRef.current) clearTimeout(_hlRef.current);
      if (_toastRef.current) clearTimeout(_toastRef.current);
    };
  }, []);

  function flashToast(kind, msg) {
    setToast({ kind, msg });
    if (_toastRef.current) clearTimeout(_toastRef.current);
    _toastRef.current = setTimeout(() => { setToast(null); _toastRef.current = null; }, 3200);
  }

  uEST(() => { setChecks(_emptyChecks()); setMass(""); setPhotos(0); }, [selectedId]);

  const selectedKit = uMST(() => kits.find(k => k.id === selectedId) || kits[0], [kits, selectedId]);
  const allChecksPass = uMST(() => Object.values(checks).every(Boolean), [checks]);
  const massCaptured = uMST(() => { const v = parseFloat(massInput); return isFinite(v) && v > 0 ? v : null; }, [massInput]);
  const massInTol = uMST(() => selectedKit && massCaptured != null && Math.abs(massCaptured - selectedKit.mass_g) <= 2.0, [selectedKit, massCaptured]);

  function actOn(kitId, action) {
    const kit = kits.find(k => k.id === kitId); if (!kit) return;
    let nextState = kit.state, note = kit.note;
    const stamp = _iso(), cocHash = _coc(kit.id + "·" + (kit.coc || "") + "·" + stamp);

    // Wave 14C — server persistence (mirror pump/act4-screens.jsx:2477).
    // Fire the traveler check-in, then surface a toast on success/failure.
    // The optimistic local mutation below still runs so the UI updates
    // immediately; the server reconciles via the existing SSE refetch.
    if (typeof window !== "undefined"
        && window.forgeApi && window.forgeApi.traveler
        && typeof window.forgeApi.traveler.checkin === "function") {
      const serverStatus = action === "pass"   ? "passed-receiving"
                         : action === "hold"   ? "hold"
                         : action === "reject" ? "rejected"
                         :                       "ncr-raised";
      const actor = (typeof window.__forgeCurrentUser !== "undefined"
                       && window.__forgeCurrentUser
                       && window.__forgeCurrentUser.name) || operator || "—";
      window.forgeApi.traveler.checkin(kit.id, {
        status: serverStatus,
        hold_reason: action === "hold" ? (kit.note || null) : null,
        dispo_path: action === "ncr" ? "ncr-raised" : null,
        station: "receiving",
        actor: actor,
        measurement_notes: kit.note || null,
      }).then(function () {
        flashToast("ok", kit.id + " → " + action + " (server confirmed)");
      }).catch(function (e) {
        const msg = (e && e.message) || "persist failed";
        if (typeof console !== "undefined") console.warn("[aet-receiving] checkin persist failed", e);
        flashToast("err", kit.id + " → " + action + " · " + msg);
      });
    }

    if (action === "pass") {
      nextState = "passed";
      const m = massCaptured != null ? massCaptured : kit.mass_g;
      note = "PASS · " + m.toFixed(1) + " g · heritage " + kit.heritage + " · COC " + cocHash.slice(0, 12);
      const evt = {
        event_id: "E-AET-RCV-" + Math.floor(Date.now() % 100000).toString().padStart(5, "0"),
        ts: stamp, type: "RECEIVING_LOGGED", mode: "traveler", actor: operator,
        ref: { wo: "WO-AET-001", kit: kit.id, part: kit.part, station: "s1" },
        summary: "Receiving · " + kit.part_name + " · " + m.toFixed(1) + " g · " + kit.heritage,
        payload: {
          kit_id: kit.id, part: kit.part, part_name: kit.part_name, supplier: kit.supplier, qty: kit.qty,
          mass_g: Number(m.toFixed(1)), mass_unit: "g", heritage: kit.heritage,
          tid_dose: kit.tid_dose, tid_cert: kit.tid_cert, connector: kit.connector, n2_purge: kit.n2_purge,
          coc_source: kit.coc, coc_hash: cocHash, itar: true,
          checklist: Object.assign({}, checks), photos: photoCount,
          station: "s1", wo: "WO-AET-001", program: "KESTREL-3",
        },
      };
      if (tenant && Array.isArray(tenant.ledger)) tenant.ledger.push(evt);
      if (typeof window !== "undefined" && typeof window.dispatchEvent === "function") {
        try {
          window.dispatchEvent(new CustomEvent("forge:event", { detail: evt }));
          window.dispatchEvent(new CustomEvent("forge:ledger:append", { detail: evt }));
          window.dispatchEvent(new CustomEvent("aetherion:receiving:logged", { detail: evt }));
        } catch (e) { /* old browser */ }
      }
      setActLog(p => [{ ts: _now(), msg: "PASS · " + kit.id + " · " + m.toFixed(1) + "g · " + kit.heritage + " · COC " + cocHash.slice(0, 8) + "…", tone: "ok" }, ...p].slice(0, 10));
    } else if (action === "hold") {
      nextState = "held"; note = "HOLD · awaiting full inspection · " + operator;
      setActLog(p => [{ ts: _now(), msg: "HOLD · " + kit.id, tone: "warn" }, ...p].slice(0, 10));
    } else if (action === "reject") {
      nextState = "rejected"; note = "REJECT · returned to " + kit.supplier + " · " + operator;
      setActLog(p => [{ ts: _now(), msg: "REJECT · " + kit.id, tone: "err" }, ...p].slice(0, 10));
    } else if (action === "ncr") {
      nextState = "ncr"; note = "NCR raised by " + operator + " · routed to Q&MA";
      setActLog(p => [{ ts: _now(), msg: "NCR · " + kit.id + " · routed to Q&MA", tone: "err" }, ...p].slice(0, 10));
    }
    setKits(p => p.map(k => k.id === kitId ? { ...k, state: nextState, note } : k));
    setHL(kitId);
    if (_hlRef.current) clearTimeout(_hlRef.current);
    _hlRef.current = setTimeout(() => setHL(null), 2400);
  }

  /* Mission timeline — KESTREL-3 (T-124d to launch). */
  const timeline = [
    { code: "SRR",    date: "2025-03-04", state: "passed",    label: "SRR closed" },
    { code: "PDR",    date: "2025-06-18", state: "passed",    label: "PDR closed" },
    { code: "CDR",    date: "2025-10-22", state: "passed",    label: "CDR closed" },
    { code: "FAB-A",  date: "2026-01-30", state: "passed",    label: "FAB-A complete" },
    { code: "ASSY",   date: "2026-02-14", state: "in-flight", label: "ASSY · I&T" },
    { code: "FAB-B",  date: "2026-05-05", state: "in-flight", label: "FAB-B re-issue (ECO-0042)" },
    { code: "TVAC-R", date: "2026-05-28", state: "upcoming",  label: "TVAC partial re-test" },
    { code: "ACC",    date: "2026-07-15", state: "upcoming",  label: "Flight acceptance" },
    { code: "LAUNCH", date: "2026-09-10", state: "upcoming",  label: "Falcon 9 Transporter-15" },
  ];

  const counts = uMST(() => {
    const c = { awaiting: 0, passed: 0, held: 0, rejected: 0, ncr: 0 };
    for (let i = 0; i < kits.length; i++) { const s = kits[i].state; if (c[s] != null) c[s]++; }
    return c;
  }, [kits]);

  const stateBg = (s) => s === "passed" ? "transparent"
    : s === "rejected" ? "color-mix(in oklch, " + SP_ERR + " 6%, transparent)"
    : s === "ncr"      ? "color-mix(in oklch, " + SP_ERR + " 8%, transparent)"
    : s === "held"     ? "color-mix(in oklch, " + SP_WARN + " 6%, transparent)"
    : "transparent";
  const stateTone = (s) => s === "passed" ? "ok" : s === "rejected" ? "err" : s === "ncr" ? "danger" : s === "held" ? "warn" : "accent";

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", minHeight: 0, background: SP_BG0, color: SP_INK0 }}>

      <_Header
        operator={operator} onOp={setOperator} ops={ops}
        station="Receiving"
        classRating="ISO 14644-1 Class 7 · KESTREL-3 · WO-AET-001"
        wo="KESTREL-3.00.00 rev D · 12U bus + payload · qty 1"
        missionT="T-124d"
      />

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1.7fr 1fr", minHeight: 0 }}>

        {/* ═══ LEFT — kit table + inspection form ═══ */}
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0, borderRight: "1px solid var(--line, " + SP_LINE + ")" }}>

          {/* Kit table */}
          <div style={{ flex: "0 0 36%", overflow: "auto", borderBottom: "1px solid var(--line, " + SP_LINE + ")" }}>
            <div style={{ ..._str_kitTableHeaderBase, ..._label }}>
              <div>Kit ID</div><div>Part</div><div>Supplier</div>
              <div style={{ textAlign: "right" }}>Mass (g)</div>
              <div>Heritage</div><div>State</div><div>GRN (UTC)</div>
            </div>
            {kits.map(k => {
              const isSel = k.id === selectedId, hl = highlight === k.id;
              return (
                <div key={k.id} role="button" tabIndex={0} onClick={() => setSelected(k.id)} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setSelected(k.id); } }} style={{
                  ..._str_kitRowBase,
                  borderLeft: isSel ? "3px solid " + SP_ACCENT : "3px solid transparent",
                  background: hl ? "color-mix(in oklch, " + SP_ACCENT + " 14%, transparent)"
                    : isSel ? "color-mix(in oklch, " + SP_ACCENT + " 6%, transparent)" : stateBg(k.state),
                }}>
                  <div className="mono" style={{ color: SP_INK3, fontSize: 12, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{k.id}</div>
                  <div>
                    <div style={{ color: SP_INK0, fontSize: 12 }}>{k.part_name}</div>
                    <div className="mono" style={{ fontSize: 12, color: SP_INK4 }}>{k.part}</div>
                  </div>
                  <div style={{ color: SP_INK2, fontSize: 12, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{k.supplier}</div>
                  <div className="mono tnum" style={{ color: SP_INK2, textAlign: "right" }}>
                    {k.mass_g.toFixed(1)}<span style={{ color: SP_INK4, marginLeft: 3 }}>g</span>
                  </div>
                  <div className="mono" style={{ fontSize: 12, color: SP_INK3, letterSpacing: "0.02em" }}>{k.heritage}</div>
                  <div><_Pill tone={stateTone(k.state)}>{k.state === "ncr" ? "NCR" : k.state}</_Pill></div>
                  <div className="mono" style={{ fontSize: 12, color: SP_INK3, letterSpacing: "0.02em" }}>{k.grn_iso.slice(11, 16)}Z</div>
                </div>
              );
            })}
          </div>

          {/* Inspection form */}
          <div style={{ flex: 1, overflow: "auto", padding: 16 }}>
            {selectedKit && <>

              {/* Heading band */}
              <div style={_str_kitHeadingBandBase}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ ..._label, color: SP_ACCENT }}>kit under inspection</div>
                  <div className="mono" style={{ fontSize: 14, color: SP_INK0, fontWeight: 600, marginTop: 2 }}>{selectedKit.id}</div>
                  <div style={{ fontSize: 12, color: SP_INK2, marginTop: 4 }}>
                    {selectedKit.part_name} <span className="mono" style={{ color: SP_INK4, marginLeft: 4 }}>· {selectedKit.part}</span>
                  </div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ ..._label, color: SP_INK4 }}>declared mass</div>
                  <div className="mono tnum" style={{ fontSize: 18, color: SP_ACCENT, fontWeight: 600, marginTop: 2 }}>
                    {selectedKit.mass_g.toFixed(1)}<span style={{ fontSize: 12, color: SP_INK3, marginLeft: 4 }}>g</span>
                  </div>
                  <div className="mono" style={{ fontSize: 12, color: SP_INK4, marginTop: 2 }}>qty {selectedKit.qty} · {selectedKit.supplier}</div>
                </div>
              </div>

              {/* Incoming inspection — TID, connectors, heritage, COC */}
              <div style={{ ..._label, marginBottom: 8 }}>incoming inspection</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 16 }}>
                {[
                  { lab: "TID dose · radiation",   v: selectedKit.tid_dose,  sub: "cert: " + selectedKit.tid_cert },
                  { lab: "MIL-spec connector",     v: selectedKit.connector, sub: "N₂ purge: " + selectedKit.n2_purge },
                  { lab: "flight heritage",        v: selectedKit.heritage,  sub: "qual file: AS9100 §8.4.3 ok" },
                  { lab: "certificate of conformity", v: selectedKit.coc,    sub: "hash: " + _coc(selectedKit.id + "·" + selectedKit.coc).slice(0, 32) + "…" },
                ].map((c, i) => (
                  <div key={c.lab} style={{ padding: 10, border: "1px solid var(--line, " + SP_LINE + ")", borderRadius: 3, background: SP_BG1 }}>
                    <div style={{ ..._label, fontSize: 12, color: SP_INK4, marginBottom: 4 }}>{c.lab}</div>
                    <div className="mono" style={{ fontSize: i === 3 ? 11 : 13, color: SP_INK0, fontWeight: 600 }}>{c.v}</div>
                    <div className="mono" style={{ fontSize: i === 3 ? 9.5 : 10, color: i === 3 ? SP_INK4 : SP_INK3, marginTop: 3, wordBreak: "break-all", lineHeight: 1.35 }}>{c.sub}</div>
                  </div>
                ))}
              </div>

              {/* Mass weighing */}
              <div style={{ ..._label, marginBottom: 8 }}>mass weighing · scale METTLER ME-3002</div>
              <div style={_str_massWeighRowBase}>
                <div style={{ flex: 1 }}>
                  <div style={{ ..._label, fontSize: 12, color: SP_INK4, marginBottom: 4 }}>captured mass</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <input id="ae-trav-receiving-f2" name="ae-trav-receiving-f2" type="number" step="0.1" placeholder={selectedKit.mass_g.toFixed(1)}
                      value={massInput} onChange={e => setMass(e.target.value)}
                      style={{
                        ..._str_massInputBase,
                        background: SP_BG0,
                        color: massCaptured == null ? SP_INK4 : massInTol ? SP_INK0 : SP_ERR,
                        border: "1px solid " + (massCaptured == null ? SP_LINE : massInTol ? SP_OK : SP_ERR),
                      }} />
                    <span className="mono" style={{ fontSize: 16, color: SP_INK3, fontWeight: 600 }}>g</span>
                  </div>
                </div>
                <div style={{ minWidth: 180 }}>
                  <div style={{ ..._label, fontSize: 12, color: SP_INK4, marginBottom: 4 }}>tolerance vs declared</div>
                  <div className="mono" style={{
                    fontSize: 12, fontWeight: 600,
                    color: massCaptured == null ? SP_INK4 : massInTol ? SP_OK : SP_ERR,
                  }}>
                    {massCaptured == null ? "—"
                      : (massInTol ? "in tol · Δ " : "out of tol · Δ ")
                        + (massCaptured - selectedKit.mass_g).toFixed(2) + " g"}
                  </div>
                  <div className="mono" style={{ fontSize: 12, color: SP_INK4, marginTop: 3 }}>gate ±2.0 g</div>
                </div>
              </div>

              {/* Photo + visual checklist */}
              <div style={{ display: "grid", gridTemplateColumns: "0.8fr 1.2fr", gap: 10, marginBottom: 16 }}>
                <div style={{
                  padding: 14, border: "1px dashed var(--line, " + SP_LINE + ")",
                  borderRadius: 3, background: SP_BG1, textAlign: "center",
                }}>
                  <div style={{ ..._label, marginBottom: 6 }}>photo capture</div>
                  <div style={{ fontSize: 12, color: SP_INK3, marginBottom: 8, lineHeight: 1.5 }}>
                    Snap COC label + connector pins + scale reading.
                    Auto-tags <span className="mono">{selectedKit.id}</span> · station s1.
                  </div>
                  <_Btn onClick={() => setPhotos(c => c + 1)}>+ Add photo</_Btn>
                  <div className="mono" style={{ fontSize: 12, color: SP_INK4, marginTop: 6 }}>
                    {photoCount} captured · {photoCount >= 3 ? "≥3 ok" : photoCount + " of 3 required"}
                  </div>
                </div>
                <div style={{ padding: 12, border: "1px solid var(--line, " + SP_LINE + ")", borderRadius: 3, background: SP_BG1 }}>
                  <div style={{ ..._label, marginBottom: 8 }}>visual inspection · QG-AET-01..05</div>
                  {[
                    ["coc_chain",     "QG-AET-01 · COC chain unbroken from supplier"],
                    ["heritage_doc",  "QG-AET-02 · heritage docs match BOM line"],
                    ["tid_cert",      "QG-AET-03 · TID radiation cert valid (≥30 krad Si)"],
                    ["n2_purge",      "QG-AET-04 · N₂ bag-and-purge ≥12h (if MIL-DTL-38999)"],
                    ["pkg_intact",    "QG-AET-05 · ESD packaging intact, no pinholes"],
                    ["surface_clean", "Surface clean · no FOD, no contamination"],
                  ].map(([k, l]) => (
                    <label key={k} style={{
                      display: "flex", alignItems: "center", gap: 8, padding: "5px 0",
                      cursor: "pointer", borderBottom: "1px dashed var(--line-soft, #E2E8F2)",
                    }}>
                      <input id="ae-trav-receiving-f3" name="ae-trav-receiving-f3" type="checkbox" checked={checks[k]}
                        onChange={e => setChecks(p => ({ ...p, [k]: e.target.checked }))}
                        style={{ accentColor: SP_ACCENT, cursor: "pointer" }} />
                      <span style={{
                        fontSize: 12, fontFamily: "var(--font-mono)", letterSpacing: "0.02em",
                        color: checks[k] ? SP_INK0 : SP_INK3,
                      }}>{l}</span>
                    </label>
                  ))}
                  <div className="mono" style={{ fontSize: 12, color: allChecksPass ? SP_OK : SP_INK4, marginTop: 6 }}>
                    {allChecksPass ? "✓ all 5 gates clear" : Object.values(checks).filter(Boolean).length + " of 6 confirmed"}
                  </div>
                </div>
              </div>

              {/* Action row — PASS / HOLD / REJECT / NCR */}
              <div style={{
                display: "flex", alignItems: "center", justifyContent: "space-between", padding: 12,
                border: "1px solid var(--line, " + SP_LINE + ")", borderRadius: 3,
                background: "color-mix(in oklch, " + SP_INK + " 4%, " + SP_BG1 + ")",
              }}>
                <div>
                  <div style={{ ..._label, marginBottom: 3 }}>operator decision</div>
                  <div style={{ fontSize: 12, color: SP_INK3 }}>
                    <b style={{ color: SP_INK2 }}>{operator}</b> attests this kit per ISO 14644-1 + AS9100 §8.7.
                  </div>
                </div>
                <div style={{ display: "flex", gap: 8 }}>
                  <_Btn tone="pass"   onClick={() => actOn(selectedKit.id, "pass")}>PASS</_Btn>
                  <_Btn tone="hold"   onClick={() => actOn(selectedKit.id, "hold")}>HOLD</_Btn>
                  <_Btn tone="reject" onClick={() => actOn(selectedKit.id, "reject")}>REJECT</_Btn>
                  <_Btn tone="ncr"    onClick={() => actOn(selectedKit.id, "ncr")}>NCR</_Btn>
                </div>
              </div>

              {selectedKit.note && (
                <div className="mono" style={{
                  fontSize: 12, color: SP_INK4, marginTop: 8, padding: "6px 10px",
                  background: SP_BG1, borderLeft: "2px solid " + SP_LINE, lineHeight: 1.45,
                }}>{selectedKit.note}</div>
              )}
            </>}
          </div>
        </div>

        {/* ═══ RIGHT — WO + ITAR + mission timeline + counts + activity ═══ */}
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0, background: SP_BG1 }}>

          {/* WO context */}
          <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--line, " + SP_LINE + ")", background: SP_BG2 }}>
            <div style={{ ..._label }}>work order</div>
            <div className="mono" style={{ fontSize: 14, color: SP_INK0, fontWeight: 600, marginTop: 3, letterSpacing: "0.02em" }}>WO-AET-001</div>
            <div style={{ fontSize: 12, color: SP_INK2, marginTop: 3 }}>
              KESTREL-3 · 12U bus + payload · qty 1 · Aperture Earth FFP {(window.forgeI18n && window.forgeI18n.formatMoneyMinor && window.forgeI18n.formatMoneyMinor("420000000", "USD")) || "$4.2M"}
            </div>
          </div>

          {/* ITAR data hold marker */}
          <div style={{
            margin: "10px 12px", padding: "10px 12px", border: "1px solid " + SP_ACCENT,
            borderLeft: "4px solid " + SP_ACCENT, borderRadius: 3,
            background: "color-mix(in oklch, " + SP_ACCENT + " 6%, " + SP_BG0 + ")",
          }}>
            <div style={{ ..._label, color: SP_ACCENT, marginBottom: 4 }}>⚠ ITAR data hold · plane: aetherion-itar</div>
            <div style={{ fontSize: 12, color: SP_INK2, lineHeight: 1.55 }}>
              All <span className="mono">traveler://</span> requests on this station carry <span className="mono">itar=true</span>.
              US-persons only · US-domiciled S3 · no MCP egress · no AI-call egress.
            </div>
            <div className="mono" style={{ fontSize: 12, color: SP_INK3, marginTop: 4 }}>
              cleared: {operator} · ITAR plane verified
            </div>
          </div>

          {/* Mission timeline */}
          <div style={{ padding: "8px 14px 4px", borderBottom: "1px solid var(--line-soft, #E2E8F2)" }}>
            <div style={{ ..._label }}>mission timeline · KESTREL-3</div>
            <div className="mono" style={{ fontSize: 12, color: SP_INK4, marginTop: 2 }}>
              T-124d to launch · target 2026-09-10 (Falcon 9 Transporter-15)
            </div>
          </div>
          <div style={{ flex: 1, overflow: "auto", padding: "4px 0" }}>
            {timeline.map((m) => {
              const bg = m.state === "passed" ? SP_OK : m.state === "in-flight" ? SP_ACCENT : SP_INK4;
              return (
                <div key={m.code} style={{
                  display: "grid", gridTemplateColumns: "12px 70px 1fr 90px",
                  alignItems: "center", gap: 8, padding: "6px 14px",
                  borderBottom: "1px dashed var(--line-soft, #E2E8F2)", fontSize: 12,
                }}>
                  <span style={{
                    width: 10, height: 10, borderRadius: "50%", background: bg,
                    boxShadow: m.state === "in-flight" ? "0 0 0 4px color-mix(in oklch, " + SP_ACCENT + " 22%, transparent)" : "none",
                  }} />
                  <span className="mono" style={{ fontSize: 12, color: SP_INK0, fontWeight: 600, letterSpacing: "0.04em" }}>{m.code}</span>
                  <span style={{ color: SP_INK2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.label}</span>
                  <span className="mono" style={{ fontSize: 12, color: SP_INK3, textAlign: "right" }}>{m.date}</span>
                </div>
              );
            })}
          </div>

          {/* Counts */}
          <div style={{ padding: "10px 14px", borderTop: "1px solid var(--line, " + SP_LINE + ")", background: SP_BG2 }}>
            <div style={{ ..._label, marginBottom: 6 }}>shift A · receiving counts</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 6 }}>
              {[
                { k: "awaiting", v: counts.awaiting, c: SP_ACCENT },
                { k: "passed",   v: counts.passed,   c: SP_OK },
                { k: "held",     v: counts.held,     c: SP_WARN },
                { k: "rejected", v: counts.rejected, c: SP_ERR },
                { k: "ncr",      v: counts.ncr,      c: SP_ERR },
              ].map(s => (
                <div key={s.k} style={{
                  padding: "6px 8px", border: "1px solid var(--line-soft, #E2E8F2)",
                  borderRadius: 3, background: SP_BG0, textAlign: "center",
                }}>
                  <div className="mono tnum" style={{ fontSize: 16, color: s.c, fontWeight: 600 }}>{s.v}</div>
                  <div className="mono" style={{ fontSize: 12, color: SP_INK4, letterSpacing: "0.06em", textTransform: "uppercase", marginTop: 2 }}>{s.k}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Activity */}
          <div style={{
            borderTop: "1px solid var(--line, " + SP_LINE + ")", padding: "10px 14px",
            maxHeight: 180, overflow: "auto", background: SP_BG0,
          }}>
            <div style={{ ..._label, marginBottom: 6 }}>activity · last 10 events</div>
            {actLog.length === 0 && <div className="mono" style={{ fontSize: 12, color: SP_INK4 }}>no events captured this shift</div>}
            {actLog.map((a) => {
              const tone = a.tone === "ok" ? SP_OK : a.tone === "warn" ? SP_WARN : a.tone === "err" ? SP_ERR : SP_INK3;
              return (
                <div key={a.ts + "·" + a.msg} style={{
                  display: "flex", gap: 8, padding: "3px 0",
                  borderBottom: "1px dashed var(--line-soft, #E2E8F2)", fontSize: 12,
                }}>
                  <span className="mono" style={{ color: SP_INK4, minWidth: 60 }}>{a.ts}</span>
                  <span className="mono" style={{ color: tone, lineHeight: 1.4, wordBreak: "break-all" }}>{a.msg}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Server check-in toast — Wave 14C */}
      {toast && (
        <div role="status" style={{
          position: "fixed", bottom: 24, right: 24, zIndex: 60,
          padding: "8px 14px", borderRadius: 4,
          background: toast.kind === "err" ? SP_ERR : SP_INK,
          color: toast.kind === "err" ? "#fff" : SP_BG0,
          fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.02em",
          boxShadow: "0 6px 20px rgba(0,0,0,0.18)",
        }}>{toast.msg}</div>
      )}
    </div>
  );
}

/* ── Route registration ──────────────────────────────────────────────── */
/* Prefer registerSpaceRoute() if the space registry has loaded; otherwise
   fall back to registerPumpRoute() so this screen mounts in either order. */
(function _spr_register() {
  const route = {
    path: "/traveler/receiving", mode: "traveler", title: "Receiving · Aetherion",
    tenant: "aetherion", renderer: () => React.createElement(ScreenAetherionReceiving),
  };
  if (typeof registerSpaceRoute === "function") registerSpaceRoute(route);
  else if (typeof registerPumpRoute === "function") registerPumpRoute(route);
  else if (typeof window !== "undefined") {
    window.SPACE_PENDING_ROUTES = window.SPACE_PENDING_ROUTES || [];
    window.SPACE_PENDING_ROUTES.push(route);
  }
})();

if (typeof window !== "undefined") window.ScreenAetherionReceiving = ScreenAetherionReceiving;
})();
