(function(){
/* FORGE · Aetherion (Space) tenant — traveler station s2
   Subassembly bench + harness routing console.
   Single screen registered at /traveler/machine-shop. Babel-standalone,
   no ES imports / exports. Globals expected: React, navigate(),
   useActiveTenant() | getActiveTenant(), registerSpaceRoute() (preferred)
   or registerPumpRoute() (fallback while space registry is wiring up),
   plus UI primitive Btn (when present, else inline fallback).

   Wave A1 · Space · Agent #12 · traveler-B subassy.
   Source-of-truth: tenant-spec/space.md §8 station 2.
   Pattern: pump/act4-screens.jsx :: ScreenStationMachineShop. */

const { useState: uSAEBS, useEffect: uEAEBS } = React;

/* ── Local palette · Wave 12D · rebound to canonical light tokens ─── */
const _AC      = "#2D5BEA";
const _SLATE   = "var(--ink-3)";
const _LN      = "var(--line)";
const _MONO_C  = "var(--ink)";
const _BG0     = "var(--bg-0)";
const _BG1     = "var(--bg-1)";
const _BG2     = "var(--bg-2)";
const _OK      = "var(--ok)";
const _WARN    = "var(--warn)";
const _ERR     = "var(--err)";
const _FM      = "var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace)";

/* ── Style atoms (inline, scoped) ────────────────────────────────── */
const SLABEL = { fontSize: 12, letterSpacing: "0.08em", color: _SLATE, textTransform: "uppercase" };
const SMONO  = { fontFamily: _FM, color: _MONO_C };
const SCARD  = { padding: 12, border: "1px solid " + _LN, borderRadius: 4, background: _BG1 };
const SINPUT = (ok, danger) => ({
  width: "100%", padding: "6px 8px",
  fontFamily: _FM, fontSize: 14, fontWeight: 600,
  background: _BG0, border: "1px solid " + _LN, borderRadius: 3,
  color: ok ? "#fff" : danger,
});

// Hoisted style atoms — extracted from inline JSX for react-doctor compliance.
const _aebs_avatarBase = {
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  width: 32, height: 32, borderRadius: "50%",
  background: "color-mix(in oklch, " + _AC + " 16%, " + _BG2 + ")",
  color: _AC,
  border: "1px solid color-mix(in oklch, " + _AC + " 30%, " + _LN + ")",
  fontFamily: _FM, fontSize: 12, letterSpacing: "0.04em", fontWeight: 600,
};
const _aebs_btnBase = {
  padding: "5px 10px",
  borderRadius: 3, fontFamily: _FM, fontSize: 12, letterSpacing: "0.04em",
};
const _aebs_stepBtnBase = {
  width: "100%", textAlign: "left", padding: "10px 12px",
  borderBottom: "1px solid " + _LN,
  border: 0,
  cursor: "pointer",
};
const _aebs_checkBoxBase = {
  width: 14, height: 14, borderRadius: 2,
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  color: "var(--ink)", fontSize: 12, fontWeight: 700,
};
const _aebs_captureRowBase = {
  display: "grid", gridTemplateColumns: "1.4fr 1fr 0.6fr 1.2fr 90px",
  gap: 12, padding: 10, marginBottom: 6,
  borderRadius: 4,
  alignItems: "center",
};
const _aebs_captureStatusBase = {
  display: "inline-flex", alignItems: "center", gap: 4,
  fontFamily: _FM, fontSize: 12, letterSpacing: "0.06em",
  textTransform: "uppercase",
};

/* ── Tiny helpers ────────────────────────────────────────────────── */
function useTenant() {
  return useActiveTenant();
}
function _now() {
  const t = new Date(), p = n => String(n).padStart(2, "0");
  return p(t.getHours()) + ":" + p(t.getMinutes()) + ":" + p(t.getSeconds());
}
function _zulu() {
  return new Date().toISOString().replace(/\.\d{3}Z$/, "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();
}
function _dot(tone) {
  const map = { ok: _OK, warn: _WARN, err: _ERR, info: _AC, mute: _SLATE };
  const c = map[tone] || _SLATE;
  return (
    <span style={{
      display: "inline-block", width: 7, height: 7, borderRadius: "50%",
      background: c, boxShadow: "0 0 0 2px color-mix(in oklch, " + c + " 18%, transparent)",
      flexShrink: 0,
    }} />
  );
}
function _avatar(name) {
  return (
    <span style={_aebs_avatarBase}>{_initials(name)}</span>
  );
}
function _AEBSBtn({ children, onClick, variant, icon, disabled }) {
  if (typeof Btn === "function" && !disabled) {
    return React.createElement(Btn, { onClick, variant, icon }, children);
  }
  const primary = variant === "primary";
  return (
    <button
      onClick={disabled ? undefined : onClick}
      style={{
        ..._aebs_btnBase,
        background: primary ? _AC : _BG1, color: primary ? "#FFFFFF" : _MONO_C,
        border: "1px solid " + (primary ? _AC : _LN),
        cursor: disabled ? "not-allowed" : "pointer", opacity: disabled ? 0.45 : 1,
      }}>{children}</button>
  );
}
function _emit(type, payload) {
  try {
    if (typeof window === "undefined") return;
    const detail = Object.assign({ type, ts: _zulu(), tenant: "aetherion", mode: "forge" }, payload || {});
    window.dispatchEvent(new CustomEvent("forge:ledger", { detail }));
    window.dispatchEvent(new CustomEvent("forge:" + type.toLowerCase(), { detail }));
  } catch (_) { /* noop */ }
}

/* ════════════════════════════════════════════════════════════════════
   ScreenAetherionSubassy
   /traveler/machine-shop  (s2 of the four-station Aetherion line)
   ──────────────────────────────────────────────────────────────────── */

const _STEPS = [
  { id: "install",    seq: 1, title: "Subassembly install",      detail: "Mount EPS, OBC, ADCS deck, payload optical bench onto the laser-aligned trace board.", gate: "QG-AET-06", wi: "WI-AET-S2-01 rev B" },
  { id: "harness",    seq: 2, title: "Harness routing per BOM",  detail: "Route HRD-AET-001 trunk to MIL-DTL-38999 series III mating points. Strap every 80 mm.", gate: "QG-AET-08", wi: "WI-AET-S2-02 rev C" },
  { id: "torque",     seq: 3, title: "Torque verification",      detail: "Cross-pattern fastener seat per HRD-AET-001 §4.2. Capture each value in Nm.",            gate: "QG-AET-10", wi: "WI-AET-S2-03 rev A" },
  { id: "continuity", seq: 4, title: "Continuity test",          detail: "ESD continuity + harness end-to-end resistance via Fluke 287. Record meter readings.",  gate: "QG-AET-12", wi: "WI-AET-S2-04 rev A" },
  { id: "signoff",    seq: 5, title: "Sign-off",                 detail: "Operator attestation + supervisor counter-sign. Emits SUBASSY_BENCH_COMPLETED.",        gate: "QG-AET-14", wi: "WI-AET-S2-99 rev A" },
];

const _TORQUE_INIT = [
  { id: "tq-eps-1", point: "EPS deck · M3 fastener #1",    target: 0.60, tol: 0.05, instrument: "Atlas Copco STR21-005", captured: 0.60 },
  { id: "tq-eps-2", point: "EPS deck · M3 fastener #2",    target: 0.60, tol: 0.05, instrument: "Atlas Copco STR21-005", captured: 0.58 },
  { id: "tq-obc-1", point: "OBC mount · M2.5 fastener #1", target: 0.45, tol: 0.04, instrument: "Atlas Copco STR21-005", captured: 0.46 },
  { id: "tq-obc-2", point: "OBC mount · M2.5 fastener #2", target: 0.45, tol: 0.04, instrument: "Atlas Copco STR21-005", captured: 0.44 },
  { id: "tq-pl-1",  point: "Payload bench · M3 hex #1",    target: 0.80, tol: 0.06, instrument: "Norbar NorTorque 60",   captured: 0.81 },
  { id: "tq-pl-2",  point: "Payload bench · M3 hex #2",    target: 0.80, tol: 0.06, instrument: "Norbar NorTorque 60",   captured: 0.79 },
];

const _CONT_INIT = [
  { id: "ct-bond",    point: "Chassis bond (deck → frame)", target: "≤ 2.5 mΩ",   spec: { lo: 0,     hi: 2.5   }, unit: "mΩ", captured: 1.8,   instrument: "Megger DLRO-10" },
  { id: "ct-eps-pwr", point: "EPS PWR rail end-to-end",     target: "0.18 Ω ±5%", spec: { lo: 0.171, hi: 0.189 }, unit: "Ω",  captured: 0.182, instrument: "Fluke 287" },
  { id: "ct-obc-can", point: "OBC CAN-A loop",              target: "120 Ω ±2",   spec: { lo: 118,   hi: 122   }, unit: "Ω",  captured: 120.2, instrument: "Fluke 287" },
  { id: "ct-pl-sig",  point: "Payload SpaceWire pair",      target: "100 Ω ±5",   spec: { lo: 95,    hi: 105   }, unit: "Ω",  captured: 99.8,  instrument: "Fluke 287" },
];

const _DIM_INIT = {
  install:    { value: 0, label: "Bench-deck planarity (µm)", units: "µm",   target: "≤ 25 µm" },
  harness:    { value: 0, label: "Trunk run length (mm)",     units: "mm",   target: "1842 ±10 mm" },
  torque:     { value: 0, label: "Witness-mark offset (deg)", units: "deg",  target: "≤ 5 deg" },
  continuity: { value: 0, label: "Bond gap measured (mm)",    units: "mm",   target: "≤ 0.05 mm" },
  signoff:    { value: 0, label: "Supervisor PIN length",     units: "char", target: "6 char" },
};

function ScreenAetherionSubassy() {
  const T = useTenant() || {};
  const operator = (T.people && T.people.subassy) || "Ananya P.";

  const [serial, setSerial] = uSAEBS("AET-K3-0007");
  const [activeStep, setActiveStep] = uSAEBS("install");
  const [photoCounts, setPhotoCounts] = uSAEBS({ install: 0, harness: 0, torque: 0, continuity: 0, signoff: 0 });
  const [dimensions, setDimensions] = uSAEBS(_DIM_INIT);
  const [torque, setTorque] = uSAEBS(_TORQUE_INIT.map(r => ({ ...r })));
  const [continuity, setContinuity] = uSAEBS(_CONT_INIT.map(r => ({ ...r })));
  const [signed, setSigned] = uSAEBS(false);
  const [supSigned, setSupSigned] = uSAEBS(false);
  const [emittedAt, setEmittedAt] = uSAEBS(null);
  const [autoNCR, setAutoNCR] = uSAEBS([]);
  const [toast, setToast] = uSAEBS(null);

  // Tenant-switch reset (mirror pump/act4-screens.jsx convention)
  uEAEBS(() => {
    const onTenant = () => {
      setSerial("AET-K3-0007"); setActiveStep("install");
      setPhotoCounts({ install: 0, harness: 0, torque: 0, continuity: 0, signoff: 0 });
      setDimensions(_DIM_INIT);
      setTorque(_TORQUE_INIT.map(r => ({ ...r })));
      setContinuity(_CONT_INIT.map(r => ({ ...r })));
      setSigned(false); setSupSigned(false); setEmittedAt(null); setAutoNCR([]);
      setToast(null);
    };
    window.addEventListener("forge:tenant-change", onTenant);
    return () => window.removeEventListener("forge:tenant-change", onTenant);
  }, []);

  function _flashToast(kind, msg) {
    setToast({ kind, msg });
    setTimeout(() => setToast(null), 3200);
  }

  // Auto-NCR on torque-out-of-spec
  uEAEBS(() => {
    const failing = torque.filter(r => {
      const lo = r.target - r.tol, hi = r.target + r.tol;
      return !(r.captured >= lo && r.captured <= hi);
    });
    setAutoNCR(failing.map(r => ({
      id: "NCR-AET-" + r.id.toUpperCase(),
      point: r.point, captured: r.captured, target: r.target, tol: r.tol,
      raised_at: _now(),
    })));
  }, [torque]);

  const passTorque = r => r.captured >= (r.target - r.tol) && r.captured <= (r.target + r.tol);
  const passCont   = r => r.captured >= r.spec.lo && r.captured <= r.spec.hi;

  const allTorqueOk = torque.every(passTorque);
  const allContOk = continuity.every(passCont);
  const canSignOff = allTorqueOk && allContOk;
  const canEmit = canSignOff && signed && supSigned && !emittedAt;

  const setTorqueValue = (id, v) => setTorque(prev => prev.map(r => r.id === id ? { ...r, captured: Number(v) || 0 } : r));
  const setContValue   = (id, v) => setContinuity(prev => prev.map(r => r.id === id ? { ...r, captured: Number(v) || 0 } : r));
  const setDimValue    = (sid, v) => setDimensions(prev => Object.assign({}, prev, { [sid]: Object.assign({}, prev[sid], { value: Number(v) || 0 }) }));
  const bumpPhoto      = sid => setPhotoCounts(prev => Object.assign({}, prev, { [sid]: (prev[sid] || 0) + 1 }));

  function emitCompletion() {
    if (!canEmit) return;
    const stamp = _zulu();
    setEmittedAt(stamp);
    _emit("SUBASSY_BENCH_COMPLETED", {
      serial, station: "s2", operator, gate: "QG-AET-14",
      torque_pass: allTorqueOk, continuity_pass: allContOk,
      photo_counts: photoCounts,
      torque_rows:     torque.map(r => ({ id: r.id, point: r.point, target: r.target, captured: r.captured, in_tol: passTorque(r) })),
      continuity_rows: continuity.map(r => ({ id: r.id, point: r.point, target: r.target, captured: r.captured, unit: r.unit, in_tol: passCont(r) })),
      ncr_count: autoNCR.length,
      summary: "Subassembly + harness sign-off · " + serial,
    });

    // Wave 14C — server persistence. Mirrors pump/act4-screens.jsx:2477
    // and the receiving-station wiring. CustomEvent dispatch above stays
    // for the in-tab ledger panel; the server call drives the durable
    // traveler row + SSE fan-out to other tabs.
    if (typeof window !== "undefined"
        && window.forgeApi && window.forgeApi.traveler
        && typeof window.forgeApi.traveler.checkin === "function") {
      const actor = (typeof window.__forgeCurrentUser !== "undefined"
                       && window.__forgeCurrentUser
                       && window.__forgeCurrentUser.name) || operator || "—";
      window.forgeApi.traveler.checkin(serial, {
        station: "subassy",
        status: "completed",
        actor: actor,
        signed_by_pin: supSigned ? "supervisor-counter-signed" : (signed ? "operator-signed" : null),
      }).then(function () {
        _flashToast("ok", serial + " → subassy completed (server confirmed)");
      }).catch(function (e) {
        const msg = (e && e.message) || "persist failed";
        if (typeof console !== "undefined") console.warn("[aet-subassy] checkin persist failed", e);
        _flashToast("err", serial + " · " + msg);
      });
    }
  }

  return (
    <div data-tenant="aetherion" style={{
      display: "flex", flexDirection: "column", height: "100%", minHeight: 0,
      background: _BG0, color: _MONO_C, fontFamily: "var(--font-ui, system-ui, sans-serif)",
    }}>
      {/* Header */}
      <div style={{ padding: "10px 14px", background: _BG2, borderBottom: "1px solid " + _LN, display: "flex", alignItems: "center", gap: 14 }}>
        {_avatar(operator)}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, color: _MONO_C, display: "flex", alignItems: "center", gap: 8 }}>
            <b style={{ color: "#fff" }}>{operator}</b>
            <span style={{ color: _SLATE }}>·</span>
            <span>Subassembly bench + harness routing (s2)</span>
            <span style={{ marginLeft: 6, padding: "1px 6px", border: "1px solid " + _LN, borderRadius: 3, fontSize: 12, color: _SLATE, fontFamily: _FM }}>seq 02 / 04</span>
          </div>
          <div style={{ fontSize: 12, color: _SLATE, marginTop: 2, fontFamily: _FM }}>
            WO-AET-001 · KESTREL-3 · Aperture Earth · 1u FFP
          </div>
        </div>
        <span style={{ color: _SLATE, fontSize: 12, fontFamily: _FM }}>cycle target 92m · actual 88.5m</span>
      </div>

      {/* Traveler band */}
      <div style={{ padding: "10px 14px", background: _BG1, borderBottom: "1px solid " + _LN, display: "flex", alignItems: "center", gap: 14 }}>
        <div style={{
          padding: "6px 12px", border: "1px solid " + _AC, borderRadius: 4,
          background: "color-mix(in oklch, " + _AC + " 8%, " + _BG0 + ")",
        }}>
          <div style={Object.assign({}, SLABEL, { color: _AC })}>UNIT IN PROGRESS</div>
          <div style={{ fontSize: 14, color: "#fff", fontFamily: _FM, letterSpacing: "0.04em" }}>{serial}</div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 14, flex: 1 }}>
          {["s1","s2","s3","s4"].map((s, i) => {
            const active = i < 1, here = i === 1;
            return (
              <div key={s} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                <div style={{
                  width: 18, height: 18, borderRadius: "50%",
                  background: active ? _OK : here ? _AC : _BG2,
                  border: "1px solid " + (active ? _OK : here ? _AC : _LN),
                  boxShadow: here ? "0 0 0 4px color-mix(in oklch, " + _AC + " 18%, transparent)" : "none",
                }} />
                <span style={{ fontSize: 12, color: here ? "#fff" : _SLATE, fontFamily: _FM, letterSpacing: "0.04em" }}>{s.toUpperCase()}</span>
              </div>
            );
          })}
        </div>
        <_AEBSBtn icon="Diff">View prior unit (AET-K3-0006)</_AEBSBtn>
        <_AEBSBtn icon="File">Open HRD-AET-001</_AEBSBtn>
      </div>

      {/* Body grid */}
      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "260px 1fr 280px", minHeight: 0 }}>

        {/* Step rail */}
        <div style={{ borderRight: "1px solid " + _LN, background: _BG1, display: "flex", flexDirection: "column", minHeight: 0 }}>
          <div style={Object.assign({ padding: "8px 12px", borderBottom: "1px solid " + _LN }, SLABEL)}>STEPS · 5</div>
          <div style={{ flex: 1, overflow: "auto" }}>
            {_STEPS.map(s => {
              const isActive = s.id === activeStep;
              const photos = photoCounts[s.id] || 0;
              return (
                <button key={s.id} onClick={() => setActiveStep(s.id)} style={{
                  ..._aebs_stepBtnBase,
                  background: isActive ? "color-mix(in oklch, " + _AC + " 10%, " + _BG1 + ")" : _BG1,
                  color: isActive ? "#fff" : _MONO_C,
                  borderLeft: isActive ? "3px solid " + _AC : "3px solid transparent",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontFamily: _FM, fontSize: 12, color: _SLATE, width: 18, textAlign: "right" }}>{String(s.seq).padStart(2, "0")}</span>
                    <span style={{ fontSize: 12.5 }}>{s.title}</span>
                  </div>
                  <div style={{ marginTop: 4, paddingLeft: 26, fontSize: 12, color: _SLATE, fontFamily: _FM, display: "flex", gap: 8 }}>
                    <span>{s.gate}</span><span>·</span><span>{photos} photo{photos === 1 ? "" : "s"}</span>
                  </div>
                </button>
              );
            })}
          </div>
          <div style={{ padding: "10px 12px", borderTop: "1px solid " + _LN, fontSize: 12, color: _SLATE, lineHeight: 1.5 }}>
            ESD continuity logged on entry · <span style={SMONO}>{_now()}</span>
          </div>
        </div>

        {/* Center pane */}
        <div style={{ overflow: "auto", padding: 16 }}>
          {(() => {
            const step = _STEPS.find(s => s.id === activeStep);
            const dim = dimensions[activeStep];
            const photos = photoCounts[activeStep] || 0;
            return (
              <>
                <div style={Object.assign({ marginBottom: 6 }, SLABEL)}>STEP {String(step.seq).padStart(2, "0")} · {step.gate} · {step.wi}</div>
                <div style={{ fontSize: 16, color: "#fff", marginBottom: 6 }}>{step.title}</div>
                <div style={{ fontSize: 12, color: _MONO_C, lineHeight: 1.5, marginBottom: 14 }}>{step.detail}</div>

                {/* Photo + dimension */}
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  <div style={Object.assign({}, SCARD, { border: "1px dashed " + _LN, textAlign: "center" })}>
                    <div style={Object.assign({ marginBottom: 6 }, SLABEL)}>PHOTO CAPTURE</div>
                    <div style={{ fontSize: 12, color: _MONO_C, marginBottom: 8, lineHeight: 1.5 }}>
                      Auto-tags <span style={Object.assign({}, SMONO, { color: "#fff" })}>{serial}</span> · step {step.id} · timestamp.
                    </div>
                    <_AEBSBtn icon="Plus" onClick={() => bumpPhoto(step.id)}>+ Add photo</_AEBSBtn>
                    <div style={{ fontSize: 12, color: _SLATE, marginTop: 6, fontFamily: _FM }}>
                      {photos} captured · {photos < 2 ? (photos + " of 2 required") : "minimum met"}
                    </div>
                  </div>
                  <div style={SCARD}>
                    <div style={Object.assign({ marginBottom: 6 }, SLABEL)}>DIMENSION CAPTURE</div>
                    <div style={{ fontSize: 12, color: _MONO_C, marginBottom: 4 }}>{dim.label}</div>
                    <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                      <input id="ae-trav-subassy-f1" name="ae-trav-subassy-f1" type="number" step="0.001" value={dim.value}
                        onChange={e => setDimValue(step.id, e.target.value)}
                        style={SINPUT(true, _ERR)} />
                      <span style={{ fontFamily: _FM, fontSize: 12, color: _SLATE }}>{dim.units}</span>
                    </div>
                    <div style={{ marginTop: 6, fontSize: 12, color: _SLATE, fontFamily: _FM }}>
                      target <span style={{ color: _MONO_C }}>{dim.target}</span>
                    </div>
                  </div>
                </div>

                {/* Step bodies */}
                {activeStep === "install" && <_InstallChecklist />}
                {activeStep === "harness" && <_HarnessRouting />}
                {activeStep === "torque" && (
                  <_CaptureTable
                    title="TORQUE CAPTURE · 6 POINTS · Nm"
                    rows={torque} setValue={setTorqueValue} pass={passTorque}
                    failTone={_ERR}
                    rowSubLabel={r => "target " + r.target.toFixed(2) + " ±" + r.tol.toFixed(2) + " Nm"}
                    inputStep="0.01" unit="Nm"
                    okLabel="in tol" failLabel="out of tol"
                    extraOnFail={() => <span style={{ fontFamily: _FM, fontSize: 12, color: _ERR }}>auto-NCR raised</span>}
                  />
                )}
                {activeStep === "continuity" && (
                  <_CaptureTable
                    title="CONTINUITY METER · 4 NETS"
                    rows={continuity} setValue={setContValue} pass={passCont}
                    failTone={_WARN}
                    rowSubLabel={r => "target " + r.target}
                    inputStep="0.001" unit={r => r.unit}
                    captureLabel="reading"
                    okLabel="pass" failLabel="review"
                  />
                )}
                {activeStep === "signoff" && (
                  <_SignoffPane
                    operator={operator} serial={serial}
                    canSignOff={canSignOff} signed={signed} setSigned={setSigned}
                    supSigned={supSigned} setSupSigned={setSupSigned}
                    canEmit={canEmit} emittedAt={emittedAt} onEmit={emitCompletion}
                    autoNCR={autoNCR}
                  />
                )}
              </>
            );
          })()}
        </div>

        {/* Right rail · auto-NCR + emit status */}
        <div style={{ borderLeft: "1px solid " + _LN, background: _BG1, display: "flex", flexDirection: "column", minHeight: 0 }}>
          <div style={Object.assign({ padding: "8px 12px", borderBottom: "1px solid " + _LN }, SLABEL)}>AUTO-NCR · {autoNCR.length}</div>
          <div style={{ flex: 1, overflow: "auto" }}>
            {autoNCR.length === 0 && (
              <div style={{ padding: "10px 12px", fontSize: 12, color: _SLATE, lineHeight: 1.5 }}>
                No torque values outside spec. NCR queue is clean for this unit.
              </div>
            )}
            {autoNCR.map(n => (
              <div key={n.id} style={{
                padding: "10px 12px", borderBottom: "1px solid " + _LN,
                background: "color-mix(in oklch, " + _ERR + " 6%, " + _BG1 + ")",
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
                  {_dot("err")}
                  <span style={{ fontFamily: _FM, fontSize: 12, color: _ERR, letterSpacing: "0.04em" }}>{n.id}</span>
                </div>
                <div style={{ fontSize: 12, color: _MONO_C, marginBottom: 2 }}>{n.point}</div>
                <div style={{ fontFamily: _FM, fontSize: 12, color: _SLATE }}>
                  captured <span style={{ color: _ERR }}>{n.captured.toFixed(2)} Nm</span>
                  {" · target "}
                  <span style={{ color: _MONO_C }}>{n.target.toFixed(2)} ±{n.tol.toFixed(2)} Nm</span>
                </div>
                <div style={{ fontFamily: _FM, fontSize: 12, color: _SLATE, marginTop: 2 }}>raised {n.raised_at} · auto</div>
              </div>
            ))}
          </div>
          <div style={{ padding: "10px 12px", borderTop: "1px solid " + _LN, fontSize: 12, color: _SLATE, lineHeight: 1.5 }}>
            <div style={Object.assign({ marginBottom: 4 }, SLABEL)}>EMIT STATUS</div>
            {emittedAt
              ? <span style={{ fontFamily: _FM, color: _OK }}>SUBASSY_BENCH_COMPLETED · {emittedAt}</span>
              : canEmit
                ? <span style={{ fontFamily: _FM, color: _AC }}>ready · awaiting emit</span>
                : <span style={{ fontFamily: _FM, color: _SLATE }}>
                    blocked · {!allTorqueOk ? "torque" : !allContOk ? "continuity" : !signed ? "operator sign" : "supervisor sign"}
                  </span>}
          </div>
        </div>
      </div>

      {/* Footer pass-out band */}
      <div style={{ padding: "10px 14px", background: _BG2, borderTop: "1px solid " + _LN, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
        <div style={{ fontSize: 12, color: _SLATE, fontFamily: _FM }}>
          QG-AET-06..14 · gate-in to s3 (Integration + alignment) on emit.
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <_AEBSBtn onClick={() => setActiveStep("install")}>Restart at install</_AEBSBtn>
          <_AEBSBtn>Hold for QC</_AEBSBtn>
          <_AEBSBtn variant="primary" disabled={!emittedAt}
            onClick={() => { if (emittedAt && typeof navigate === "function") navigate("/traveler/integration"); }}>
            {emittedAt ? "Pass to Integration ▸" : "Emit to advance"}
          </_AEBSBtn>
        </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" ? _ERR : _MONO_C,
          color: toast.kind === "err" ? "#fff" : _BG0,
          fontFamily: _FM, fontSize: 12, letterSpacing: "0.02em",
          boxShadow: "0 6px 20px rgba(0,0,0,0.18)",
        }}>{toast.msg}</div>
      )}
    </div>
  );
}

/* ════════════════════════════════════════════════════════════════════
   Sub-panels
   ──────────────────────────────────────────────────────────────────── */

function _InstallChecklist() {
  const items = [
    { k: "EPS deck seated · 4 captive screws engaged",        done: true  },
    { k: "OBC mounted · ESD wrist-strap continuity verified", done: true  },
    { k: "ADCS deck shimmed to 0.05 mm flatness",             done: true  },
    { k: "Payload optical bench placed · kinematic mount",    done: false },
    { k: "Trace-board laser alignment witnessed",             done: false },
  ];
  return (
    <div style={Object.assign({ marginTop: 14 }, SCARD)}>
      <div style={Object.assign({ marginBottom: 8 }, SLABEL)}>INSTALL CHECKLIST · 5</div>
      {items.map((it, i) => (
        <div key={it.k} style={{
          display: "flex", alignItems: "center", gap: 10, padding: "6px 4px",
          borderBottom: i === items.length - 1 ? 0 : "1px dashed " + _LN,
        }}>
          <span style={{
            ..._aebs_checkBoxBase,
            border: "1px solid " + (it.done ? _OK : _LN),
            background: it.done ? _OK : "transparent",
          }}>{it.done ? "✓" : ""}</span>
          <span style={{ fontSize: 12, color: it.done ? _MONO_C : _SLATE }}>{it.k}</span>
        </div>
      ))}
    </div>
  );
}

function _HarnessRouting() {
  const segments = [
    { id: "H-01", from: "EPS deck",  to: "OBC mount",     length_mm: 412, conn: "MIL-DTL-38999 III · shell 11" },
    { id: "H-02", from: "OBC mount", to: "ADCS deck",     length_mm: 268, conn: "MIL-DTL-38999 III · shell 09" },
    { id: "H-03", from: "ADCS deck", to: "Payload bench", length_mm: 354, conn: "MIL-DTL-38999 III · shell 13" },
    { id: "H-04", from: "EPS deck",  to: "Payload bench", length_mm: 808, conn: "MIL-DTL-38999 III · shell 15" },
  ];
  const cols = "60px 1fr 1fr 100px 1.4fr";
  return (
    <div style={Object.assign({ marginTop: 14 }, SCARD)}>
      <div style={Object.assign({ marginBottom: 8 }, SLABEL)}>HRD-AET-001 · 4 SEGMENTS</div>
      <div style={{
        display: "grid", gridTemplateColumns: cols, gap: 10, padding: "4px 0",
        borderBottom: "1px solid " + _LN,
        ...SLABEL,
      }}>
        <span>id</span><span>from</span><span>to</span><span>length</span><span>connector</span>
      </div>
      {segments.map(s => (
        <div key={s.id} style={{
          display: "grid", gridTemplateColumns: cols, gap: 10, padding: "8px 0",
          fontSize: 12, color: _MONO_C, borderBottom: "1px dashed " + _LN,
        }}>
          <span style={Object.assign({}, SMONO, { color: "#fff" })}>{s.id}</span>
          <span>{s.from}</span><span>{s.to}</span>
          <span style={SMONO}>{s.length_mm} mm</span>
          <span style={{ color: _SLATE }}>{s.conn}</span>
        </div>
      ))}
      <div style={{ marginTop: 10, fontSize: 12, color: _SLATE, lineHeight: 1.5 }}>
        N₂ bag-and-purge &gt; 12 h applied to every connector before mate. CofC on file.
      </div>
    </div>
  );
}

/* Shared capture table — torque (Nm) and continuity (mΩ/Ω) reuse it. */
function _CaptureTable({ title, rows, setValue, pass, failTone, rowSubLabel,
                        inputStep, unit, captureLabel, okLabel, failLabel, extraOnFail }) {
  const captureLbl = captureLabel || "captured";
  return (
    <div style={{ marginTop: 14 }}>
      <div style={Object.assign({ marginBottom: 6 }, SLABEL)}>{title}</div>
      {rows.map(r => {
        const p = pass(r);
        const u = typeof unit === "function" ? unit(r) : unit;
        return (
          <div key={r.id} style={{
            ..._aebs_captureRowBase,
            border: "1px solid " + (p ? _LN : failTone),
            background: p ? _BG1 : "color-mix(in oklch, " + failTone + " 6%, " + _BG1 + ")",
          }}>
            <div>
              <div style={{ fontSize: 12, color: "#fff", fontWeight: 500 }}>{r.point}</div>
              <div style={{ fontFamily: _FM, fontSize: 12, color: _SLATE, marginTop: 2 }}>{rowSubLabel(r)}</div>
            </div>
            <div>
              <div style={Object.assign({ marginBottom: 3 }, SLABEL)}>{captureLbl}</div>
              <input id="ae-trav-subassy-f2" name="ae-trav-subassy-f2" type="number" step={inputStep} value={r.captured}
                onChange={e => setValue(r.id, e.target.value)}
                style={SINPUT(p, failTone)} />
            </div>
            <div>
              <div style={Object.assign({ marginBottom: 3 }, SLABEL)}>units</div>
              <span style={SMONO}>{u}</span>
            </div>
            <div>
              <div style={Object.assign({ marginBottom: 3 }, SLABEL)}>instrument</div>
              <span style={{ fontSize: 12, color: _MONO_C }}>{r.instrument}</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-start" }}>
              <span style={{ ..._aebs_captureStatusBase, color: p ? _OK : failTone }}>
                {_dot(p ? "ok" : (failTone === _WARN ? "warn" : "err"))}
                <span>{p ? okLabel : failLabel}</span>
              </span>
              {!p && extraOnFail ? extraOnFail(r) : null}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function _SignoffPane({ operator, serial, canSignOff, signed, setSigned, supSigned, setSupSigned, canEmit, emittedAt, onEmit, autoNCR }) {
  return (
    <div style={{ marginTop: 14 }}>
      {!canSignOff && (
        <div style={{
          padding: 12, border: "1px solid " + _WARN, borderRadius: 4,
          background: "color-mix(in oklch, " + _WARN + " 8%, " + _BG1 + ")",
          color: _WARN, fontSize: 12, marginBottom: 10,
        }}>
          Sign-off blocked · clear all torque + continuity gates first.
          {autoNCR.length > 0 ? " " + autoNCR.length + " auto-NCR pending." : ""}
        </div>
      )}

      <div style={Object.assign({ marginBottom: 10 }, SCARD)}>
        <div style={Object.assign({ marginBottom: 6 }, SLABEL)}>OPERATOR ATTESTATION</div>
        <div style={{ fontSize: 12, color: _MONO_C, marginBottom: 8, lineHeight: 1.5 }}>
          I, <b style={{ color: "#fff" }}>{operator}</b>, certify the captured measurements
          and harness routing on unit{" "}
          <span style={Object.assign({}, SMONO, { color: "#fff" })}>{serial}</span> conform to HRD-AET-001.
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          {signed
            ? (<>
                <span style={{ fontFamily: _FM, fontSize: 12, color: _OK }}>signed · {_now()}</span>
                <_AEBSBtn onClick={() => setSigned(false)}>Reset</_AEBSBtn>
              </>)
            : <_AEBSBtn variant="primary" onClick={() => setSigned(true)} disabled={!canSignOff}>Sign with PIN</_AEBSBtn>}
        </div>
      </div>

      <div style={Object.assign({ marginBottom: 10 }, SCARD)}>
        <div style={Object.assign({ marginBottom: 6 }, SLABEL)}>SUPERVISOR COUNTER-SIGN</div>
        <div style={{ fontSize: 12, color: _MONO_C, marginBottom: 8, lineHeight: 1.5 }}>
          AS9100 §8.5 · second-party witness required before ledger emit.
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          {supSigned
            ? (<>
                <span style={{ fontFamily: _FM, fontSize: 12, color: _OK }}>witnessed · Devansh A. · {_now()}</span>
                <_AEBSBtn onClick={() => setSupSigned(false)}>Reset</_AEBSBtn>
              </>)
            : <_AEBSBtn variant="primary" onClick={() => setSupSigned(true)} disabled={!signed}>Counter-sign</_AEBSBtn>}
        </div>
      </div>

      <div style={{
        padding: 12, border: "1px solid " + (emittedAt ? _OK : _AC), borderRadius: 4,
        background: "color-mix(in oklch, " + (emittedAt ? _OK : _AC) + " 6%, " + _BG1 + ")",
      }}>
        <div style={Object.assign({ marginBottom: 6 }, SLABEL, { color: emittedAt ? _OK : _AC })}>
          LEDGER · SUBASSY_BENCH_COMPLETED
        </div>
        <div style={{ fontSize: 12, color: _MONO_C, marginBottom: 8, lineHeight: 1.5 }}>
          Emit signs the receipt to the Aetherion auditor ledger and gates entry to s3.
          ITAR-flagged routing notes attach automatically.
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <_AEBSBtn variant="primary" disabled={!canEmit} onClick={onEmit}>
            {emittedAt ? "Emitted" : "Emit SUBASSY_BENCH_COMPLETED"}
          </_AEBSBtn>
          {emittedAt && <span style={{ fontFamily: _FM, fontSize: 12, color: _OK }}>{emittedAt}</span>}
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════════════
   Route registration. Prefer the space registry; fall back to pump
   registry while task #12 (space/registry-index.jsx) is in flight.
   Otherwise park on a window queue for the eventual registry to drain.
   ──────────────────────────────────────────────────────────────────── */

(function _aebs_register() {
  const route = {
    path: "/traveler/machine-shop",
    mode: "traveler",
    title: "Aetherion · Subassembly bench",
    tenant: "aetherion",
    renderer: function () { return React.createElement(ScreenAetherionSubassy); },
  };
  if (typeof window === "undefined") return;
  if (typeof window.registerSpaceRoute === "function") { window.registerSpaceRoute(route); return; }
  if (typeof window.registerPumpRoute === "function")  { window.registerPumpRoute(route);  return; }
  window.PENDING_AETHERION_ROUTES = window.PENDING_AETHERION_ROUTES || [];
  window.PENDING_AETHERION_ROUTES.push(route);
})();

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