(function(){
/* FORGE · mittelstand tenant — Station 3 traveler console
   Subassembly + spindle alignment (`/traveler/motor-assy`).
   Babel-standalone in-browser. NO ES imports / exports.
   Globals: React, Btn, I, navigate(), registerMittelstandRoute() (agent #3).

   Per tenant-spec/mittelstand.md §8 Station 3:
     · spindle (50.01) ↔ A/C tilting head (50.00) mate
     · harness routing for Heidenhain TNC 640 + LC 415 encoder
     · ATC carousel (60.00) index to spindle nose
     · Faro Vantage S laser tracker run-out @ 24,000 rpm
     · auto-NCR > 4 µm TIR · emits SUBASSY_COMPLETED on close

   Palette: cool anthracite/steel/graphite via --mittel-* with safe
   fallbacks to global --ink/--bg/--accent stack.
*/

const { useState: uSMS3, useEffect: uEMS3 } = React;

/* style tokens — cool gray, fallbacks let this render before agent #8 */
const _BG     = "var(--mittel-bg, var(--bg-0))";
const _BG2    = "var(--mittel-bg-2, var(--bg-2))";
const _BG3    = "var(--mittel-bg-3, var(--bg-1))";
const _INK    = "var(--mittel-ink, var(--ink))";
const _INK2   = "var(--mittel-ink-2, var(--ink-2))";
const _INK3   = "var(--mittel-ink-3, var(--ink-3))";
const _INK4   = "var(--mittel-ink-4, var(--ink-4))";
const _LINE   = "var(--mittel-line, var(--line))";
const _LINES  = "var(--mittel-line-soft, var(--line-soft))";
const _ACCENT = "var(--mittel-accent, var(--accent))";
const _WARN   = "var(--mittel-accent-warn, var(--warn))";
const _BAD    = "var(--mittel-accent-bad, var(--err))";
const _OK     = "var(--ok)";

/* tiny atoms — local; does not depend on pump _A4 helpers */
function _initials(n) {
  if (!n) return "—";
  const p = String(n).replace(/[^A-Za-z. ]/g, "").split(/\s+/).filter(Boolean);
  if (!p.length) return "—";
  return ((p[0][0] || "") + (p[1] ? p[1][0] : (p[0][1] || ""))).toUpperCase();
}

function _dot(tone) {
  const map = { ok: _OK, warn: _WARN, err: _BAD, info: _ACCENT, mute: _INK4 };
  const c = map[tone] || tone || _INK4;
  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 _kvRow(k, v) {
  return (
    <div key={k} style={{
      display: "flex", justifyContent: "space-between", alignItems: "baseline",
      padding: "5px 10px", borderBottom: "1px dashed " + _LINES, fontSize: 12,
    }}>
      <span className="label" style={{ color: _INK4, letterSpacing: "0.04em" }}>{k}</span>
      <span className="mono tnum" style={{ color: _INK2 }}>{v}</span>
    </div>
  );
}

/* Extracted styles (react-doctor: no-inline-exhaustive-style). */
function _msStatStyle(pass) {
  return {
    display: "inline-flex", alignItems: "center", gap: 4,
    fontFamily: "var(--font-mono)", fontSize: 12,
    letterSpacing: "0.06em", textTransform: "uppercase",
    color: pass ? _OK : _BAD,
  };
}
const _MS_HEADER_AVATAR_STYLE = {
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  width: 32, height: 32, borderRadius: "50%",
  background: "color-mix(in oklch, " + _ACCENT + " 16%, " + _BG2 + ")",
  color: _ACCENT,
  border: "1px solid color-mix(in oklch, " + _ACCENT + " 30%, " + _LINE + ")",
  fontFamily: "var(--font-mono)", fontSize: 12,
  letterSpacing: "0.04em", fontWeight: 600,
};
function _msStepNumStyle(stepBad, sealed) {
  return {
    flexShrink: 0, width: 22, height: 22, borderRadius: "50%",
    background: stepBad ? _BAD : sealed ? _OK : _ACCENT, color: "#fff",
    display: "inline-flex", alignItems: "center", justifyContent: "center",
    fontSize: 12, fontFamily: "var(--font-mono)", fontWeight: 600,
  };
}
function _msPhotoChipStyle(active) {
  return {
    padding: "3px 8px", borderRadius: 3,
    border: "1px solid " + (active ? _OK : _LINE),
    background: active ? "color-mix(in oklch, " + _OK + " 10%, transparent)" : "transparent",
    fontSize: 12, fontFamily: "var(--font-mono)",
    color: active ? _OK : _INK4, letterSpacing: "0.04em",
  };
}
const _MS_LEDGER_FOOTER_STYLE = {
  padding: "8px 14px", borderTop: "1px solid " + _LINE, background: _BG3,
  display: "flex", justifyContent: "space-between", alignItems: "center",
  fontSize: 12, color: _INK4,
};

function _Stat({ pass, label }) {
  return (
    <span style={_msStatStyle(pass)}>
      {_dot(pass ? "ok" : "err")}<span>{label || (pass ? "pass" : "fail")}</span>
    </span>
  );
}

/* ledger emit — degrades silently if agent #18 hasn't bound the sink */
function _emit(kind, payload) {
  try {
    const ev = { kind, ts: new Date().toISOString(), payload };
    if (typeof window !== "undefined") {
      if (typeof window.appendForgeLedger === "function") window.appendForgeLedger(ev);
      else if (Array.isArray(window.MITTELSTAND_LEDGER)) window.MITTELSTAND_LEDGER.push(ev);
      window.dispatchEvent(new CustomEvent("forge:ledger", { detail: ev }));
    }
  } catch (e) { /* no-op */ }
}

/* ════════════════════════════════════════════════════════════════════
   ScreenMittelstandSubassy — Station 3 of 4
   /traveler/motor-assy   (path reused; tenant registry resolves)
   ──────────────────────────────────────────────────────────────────── */

function _MSSubassyStepList({ steps, stepsDone, ncrTrip, photoCount, signed, snapPhoto, signStep, operator }) {
  return (
    <div style={{ borderRight: "1px solid " + _LINE, display: "flex", flexDirection: "column", minHeight: 0 }}>
      <div style={{
        padding: "10px 14px", borderBottom: "1px solid " + _LINES,
        display: "flex", justifyContent: "space-between", alignItems: "center",
      }}>
        <div className="label" style={{ color: _INK3, letterSpacing: "0.04em" }}>
          SUBASSEMBLY SEQUENCE · 5 STEPS
        </div>
        <span className="mono" style={{ fontSize: 12, color: _INK3 }}>
          {stepsDone} / {steps.length} signed
        </span>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: "10px 14px" }}>
        {steps.map((s, i) => {
          const stepBad = s.id === "runout-check" && ncrTrip;
          const photos = photoCount[s.id] || 0;
          const sealed = !!signed[s.id];
          return (
            <div key={s.id} style={{
              padding: 12, marginBottom: 10,
              border: "1px solid " + (stepBad ? _BAD : sealed ? _OK : _LINE),
              borderLeft: "3px solid " + (stepBad ? _BAD : sealed ? _OK : _ACCENT),
              borderRadius: 3, background: _BG,
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10 }}>
                <div style={{ display: "flex", alignItems: "flex-start", gap: 10, minWidth: 0 }}>
                  <span style={_msStepNumStyle(stepBad, sealed)}>{i + 1}</span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13, color: _INK, fontWeight: 500 }}>{s.label}</div>
                    <div className="mono" style={{ fontSize: 12, color: _INK3, marginTop: 2, letterSpacing: "0.02em" }}>{s.part}</div>
                  </div>
                </div>
                <_Stat pass={sealed && !stepBad} label={stepBad ? "ncr" : sealed ? "sealed" : "open"} />
              </div>
              <div style={{ fontSize: 12, color: _INK2, marginTop: 8, lineHeight: 1.5 }}>{s.detail}</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 80px", gap: 10, marginTop: 8, fontSize: 12 }}>
                <div>
                  <div className="label" style={{ color: _INK4 }}>tool</div>
                  <span className="mono" style={{ color: _INK2 }}>{s.tool}</span>
                </div>
                <div>
                  <div className="label" style={{ color: _INK4 }}>target</div>
                  <span className="mono" style={{ color: _INK2 }}>{s.target}</span>
                </div>
                <div>
                  <div className="label" style={{ color: _INK4 }}>cycle</div>
                  <span className="mono" style={{ color: _INK3 }}>{s.cycle}</span>
                </div>
              </div>
              <div style={{
                marginTop: 10, paddingTop: 10,
                borderTop: "1px dashed " + _LINES,
                display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10,
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
                  {s.photoLabels.map((lbl, j) => (
                    <span key={j} style={_msPhotoChipStyle(photos > j)}>{photos > j ? "✓ " : ""}{lbl}</span>
                  ))}
                  <Btn size="sm" icon="Camera" onClick={() => snapPhoto(s.id)}>+ snap ({photos}/2)</Btn>
                </div>
                <Btn size="sm"
                     variant={sealed ? "" : "primary"}
                     icon={sealed ? "Check" : "Edit"}
                     onClick={() => signStep(s.id)}
                     title={photos < 2 ? "snap both photos first" : undefined}>
                  {sealed ? "signed · " + operator : "Sign step"}
                </Btn>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function _MSSubassyFaroPanel({ runoutTIR, setRunoutTIR, ncrTrip }) {
  return (
    <div style={{ padding: "10px 14px", borderBottom: "1px solid " + _LINES }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
        <div className="label" style={{ color: _INK3, letterSpacing: "0.04em" }}>
          FARO VANTAGE S · LASER TRACKER
        </div>
        <span className="mono" style={{
          padding: "2px 6px", border: "1px solid " + _LINE, borderRadius: 3,
          fontSize: 12, color: _INK3, letterSpacing: "0.04em",
        }}>CAM2 2025 · SMR 1.5″</span>
      </div>
      <_RunoutTrace tir={runoutTIR} ncr={ncrTrip} />
      <div style={{ marginTop: 8, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, fontSize: 12 }}>
        <div><div className="label" style={{ color: _INK4 }}>spindle</div><span className="mono" style={{ color: _INK2 }}>HSK-A63 24k</span></div>
        <div><div className="label" style={{ color: _INK4 }}>rpm</div><span className="mono" style={{ color: _INK }}>24,000</span></div>
        <div>
          <div className="label" style={{ color: _INK4 }}>TIR (max)</div>
          <span className="mono" style={{ color: ncrTrip ? _BAD : _OK, fontWeight: 600 }}>{runoutTIR.toFixed(2)} µm</span>
        </div>
        <div><div className="label" style={{ color: _INK4 }}>limit</div><span className="mono" style={{ color: _INK3 }}>≤ 4.00 µm</span></div>
      </div>
      <div style={{
        marginTop: 10, padding: 10,
        border: "1px solid " + _LINE, borderRadius: 3, background: _BG3,
        fontSize: 12, color: _INK3,
      }}>
        <div className="label" style={{ marginBottom: 6, color: _INK4 }}>RE-SPIN · max-of-three sweeps</div>
        <input id="ms-trav-subassy-f1" name="ms-trav-subassy-f1" type="range" min="0.5" max="6.5" step="0.1"
               value={runoutTIR} onChange={e => setRunoutTIR(Number(e.target.value))}
               style={{ width: "100%", accentColor: ncrTrip ? _BAD : _ACCENT }} />
        <div className="mono tnum" style={{
          display: "flex", justifyContent: "space-between", marginTop: 4,
          fontSize: 12, color: _INK4,
        }}>
          <span>0.5 µm</span>
          <span style={{ color: ncrTrip ? _BAD : _INK3 }}>capture · {runoutTIR.toFixed(2)} µm</span>
          <span>6.5 µm</span>
        </div>
      </div>
    </div>
  );
}

function _MSSubassyStationClose({ okToClose, ncrTrip, runoutTIR, steps, stepsDone, photoCount, emitted, closeStation }) {
  return (
    <div style={{
      padding: "12px 14px", marginTop: "auto",
      borderTop: "1px solid " + _LINES, background: _BG3,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10 }}>
        <div style={{ minWidth: 0 }}>
          <div className="label" style={{ color: _INK3, letterSpacing: "0.04em" }}>STATION CLOSE</div>
          <div style={{ fontSize: 12, color: _INK2, marginTop: 4, lineHeight: 1.5 }}>
            {okToClose
              ? <>5 / 5 steps signed · run-out within tol · all photos captured. Emit <span className="mono">SUBASSY_COMPLETED</span> and advance to FAI station.</>
              : ncrTrip
                ? <>Run-out {runoutTIR.toFixed(2)} µm TIR exceeds 4 µm limit; close is blocked until NCR is dispositioned or re-mate brings TIR within tol.</>
                : <>{steps.length - stepsDone} step(s) unsigned · {steps.reduce((a, s) => a + Math.max(0, 2 - (photoCount[s.id] || 0)), 0)} photo(s) outstanding.</>}
          </div>
        </div>
        <Btn variant={okToClose ? "primary" : ""}
             icon={emitted ? "Check" : "ArrowRight"}
             onClick={closeStation}
             title={!okToClose ? "complete all steps · run-out ≤ 4 µm · 2 photos / step" : undefined}>
          {emitted ? "Sent to FAI ▸" : "Close + emit SUBASSY_COMPLETED"}
        </Btn>
      </div>
    </div>
  );
}

function ScreenMittelstandSubassy() {
  const operator = "M. Hofer";
  const stationName = "Subassembly + spindle alignment (s3)";

  const [serial, setSerial] = uSMS3("MTL-220.S/N 0095");
  const [photoCount, setPhotoCount] = uSMS3({});
  const [signed, setSigned] = uSMS3({});
  const [runoutTIR, setRunoutTIR] = uSMS3(2.7); // µm TIR @ 24k rpm
  const [emitted, setEmitted] = uSMS3(false);

  uEMS3(() => {
    const onTenant = () => {
      setSerial("MTL-220.S/N 0095");
      setPhotoCount({}); setSigned({}); setRunoutTIR(2.7); setEmitted(false);
    };
    window.addEventListener("forge:tenant-change", onTenant);
    return () => window.removeEventListener("forge:tenant-change", onTenant);
  }, []);

  const steps = [
    {
      id: "spindle-install", label: "Spindle install",
      part: "MTL-220.50.01 · GMN HSK-A63 24k rpm",
      detail: "Mount spindle to A/C tilting head (50.00). Seat torque 220 Nm cross-pattern, taper-clean before mate.",
      tool: "Atlas Copco Tensor STR · 220 Nm ±5%",
      target: "torque captured · taper Ra ≤ 0.4 µm",
      cycle: "8 min",
      photoLabels: ["HSK-A63 taper · pre-mate", "Spindle seated in head"],
    },
    {
      id: "harness-routing", label: "Harness routing",
      part: "TNC 640 motor cable + LC 415 encoder loom",
      detail: "Route Heidenhain control harness through C-axis cable carrier. Min bend radius 90 mm, no chafing on cast rib.",
      tool: "ESD-safe ferrule kit · DIN 46228",
      target: "no chafing · bend ≥ 90 mm · ferrules crimped",
      cycle: "11 min",
      photoLabels: ["Cable carrier exit", "Connector torque seal"],
    },
    {
      id: "atc-mate", label: "ATC carousel mate",
      part: "MTL-220.60.00 · DMG Mori 24-pocket carousel",
      detail: "Index ATC carousel to spindle nose. Pocket 1 to HSK-A63 nose within 0.02 mm centerline shift.",
      tool: "Indicator base + Mahr 1003 dial · 0.001 mm",
      target: "centerline shift ≤ 0.02 mm",
      cycle: "9 min",
      photoLabels: ["Carousel index home", "Pocket 1 ↔ nose dial"],
    },
    {
      id: "runout-check", label: "Run-out check @ 24k rpm",
      part: "Faro Vantage laser tracker · SMR mount on test arbor",
      detail: "Spin-up to 24,000 rpm, capture TIR over 30 s window. Auto-NCR if TIR > 4 µm. Three sweeps, max-of-three.",
      tool: "Faro Vantage S · CAM2 2025 · SMR 1.5″",
      target: "≤ 4 µm TIR @ 24,000 rpm",
      cycle: "6 min",
      photoLabels: ["Faro head + arbor", "TIR trace screenshot"],
    },
    {
      id: "calibration-log", label: "Calibration log",
      part: "C-axis rotary alignment — 0.005° to spindle nose",
      detail: "Lock-and-log C-axis zero. Bind FAR-V trace + indicator delta to traveler. Sign and stamp.",
      tool: "Heidenhain TNC kinematics calibration cycle 451",
      target: "C-axis ↔ spindle ≤ 0.005° · log binds to S/N",
      cycle: "5 min",
      photoLabels: ["TNC 451 result", "Stamped subassy tag"],
    },
  ];

  const ncrTrip = runoutTIR > 4.0;
  const stepsDone = steps.filter(s => signed[s.id]).length;
  const allPhotos = steps.every(s => (photoCount[s.id] || 0) >= 2);
  const okToClose = stepsDone === steps.length && !ncrTrip && allPhotos;
  const cycleCaptured = [8, 11, 9, 6, 5].slice(0, stepsDone).reduce((a, b) => a + b, 0);

  function snapPhoto(id) {
    setPhotoCount(prev => ({ ...prev, [id]: Math.min(2, (prev[id] || 0) + 1) }));
  }
  function signStep(id) {
    setSigned(prev => ({ ...prev, [id]: !prev[id] }));
  }
  function closeStation() {
    if (!okToClose || emitted) return;
    _emit("SUBASSY_COMPLETED", {
      serial, station: "s3",
      runout_tir_um: runoutTIR, runout_rpm: 24000,
      tracker: "Faro Vantage S", operator,
    });
    setEmitted(true);
    if (typeof navigate === "function") navigate("/traveler/test");
  }

  return (
    <div style={{
      display: "flex", flexDirection: "column", height: "100%", minHeight: 0,
      background: _BG, color: _INK, fontFamily: "var(--font-ui)",
    }}>

      {/* ── Station header ─────────────────────────────────────── */}
      <div style={{
        padding: "10px 14px", background: _BG2,
        borderBottom: "1px solid " + _LINE,
        display: "flex", alignItems: "center", gap: 14,
      }}>
        <span style={_MS_HEADER_AVATAR_STYLE}>{_initials(operator)}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, color: _INK, display: "flex", alignItems: "center", gap: 8 }}>
            <b>{operator}</b>
            <span style={{ color: _INK4 }}>·</span>
            <span style={{ color: _INK2 }}>{stationName}</span>
            <span className="mono" style={{
              marginLeft: 6, padding: "1px 6px",
              border: "1px solid " + _LINE, borderRadius: 3,
              fontSize: 12, color: _INK3, letterSpacing: "0.04em",
            }}>seq 03 / 04</span>
          </div>
          <div className="mono" style={{ fontSize: 12, color: _INK4, marginTop: 2 }}>
            WO-MTL-2401 · MTL-220 Rev D · MAHLE 24-mill batch
          </div>
        </div>
        <span className="mono" style={{ color: _INK3, fontSize: 12, letterSpacing: "0.04em" }}>
          cycle target 39 min · captured {cycleCaptured} min
        </span>
      </div>

      {/* ── Traveler band: serial + 4-station progress ────────── */}
      <div style={{
        padding: "10px 14px", background: _BG3,
        borderBottom: "1px solid " + _LINE,
        display: "flex", alignItems: "center", gap: 14,
      }}>
        <div style={{
          padding: "6px 12px",
          border: "1px solid " + _ACCENT, borderRadius: 4,
          background: "color-mix(in oklch, " + _ACCENT + " 8%, " + _BG + ")",
        }}>
          <div className="label" style={{ color: _ACCENT, letterSpacing: "0.04em" }}>UNIT IN PROGRESS</div>
          <div className="mono" style={{ fontSize: 14, color: _INK, letterSpacing: "0.04em" }}>{serial}</div>
        </div>
        <div style={{ flex: 1, display: "flex", gap: 14, alignItems: "center", justifyContent: "center" }}>
          {[
            { id: "s1", lbl: "RECEIVING" },
            { id: "s2", lbl: "MACHINE-SHOP" },
            { id: "s3", lbl: "SUBASSY" },
            { id: "s4", lbl: "FAI" },
          ].map((s, i) => {
            const active = i < 2, here = i === 2;
            return (
              <div key={s.id} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                <div style={{
                  width: 18, height: 18, borderRadius: "50%",
                  background: active ? _OK : here ? _ACCENT : _BG2,
                  border: "1px solid " + (active ? _OK : here ? _ACCENT : _LINE),
                  boxShadow: here ? "0 0 0 4px color-mix(in oklch, " + _ACCENT + " 18%, transparent)" : "none",
                }} />
                <span className="mono" style={{
                  fontSize: 12, color: here ? _INK : _INK4, letterSpacing: "0.04em",
                }}>{s.lbl}</span>
              </div>
            );
          })}
        </div>
        <Btn icon="File" onClick={() => window.forgeToast && window.forgeToast("Subassy spec opened — wired in v2")}>Subassy spec · SAS-MTL-220-rD</Btn>
      </div>

      {/* ── Auto-NCR alert ────────────────────────────────────── */}
      {ncrTrip && (
        <div style={{
          padding: "10px 14px",
          background: "color-mix(in oklch, " + _BAD + " 12%, " + _BG + ")",
          borderBottom: "1px solid " + _BAD,
          display: "flex", alignItems: "center", gap: 12,
        }}>
          {_dot("err")}
          <div style={{ flex: 1 }}>
            <div className="mono" style={{ fontSize: 12, fontWeight: 600, color: _BAD, letterSpacing: "0.04em" }}>
              AUTO-NCR · run-out {runoutTIR.toFixed(2)} µm TIR @ 24,000 rpm exceeds 4 µm limit
            </div>
            <div style={{ fontSize: 12, color: _INK3, marginTop: 2 }}>
              Spindle assembly held. CAPA opened, S. Klein notified · spindle re-mate + bearing pre-load review.
              Station cannot close until TIR returns within tol or NCR is dispositioned.
            </div>
          </div>
          <span className="mono" style={{
            padding: "3px 8px", border: "1px solid " + _BAD, borderRadius: 3,
            fontSize: 12, color: _BAD, letterSpacing: "0.04em",
          }}>NCR-MS-{String(102 + Math.round(runoutTIR * 10)).padStart(4, "0")}</span>
        </div>
      )}

      {/* ── Body: two columns ─────────────────────────────────── */}
      <div style={{
        flex: 1, display: "grid", gridTemplateColumns: "1.05fr 1fr",
        minHeight: 0, overflow: "hidden",
      }}>

        {/* LEFT — step list with photo + signoff */}
        <_MSSubassyStepList steps={steps} stepsDone={stepsDone} ncrTrip={ncrTrip} photoCount={photoCount} signed={signed} snapPhoto={snapPhoto} signStep={signStep} operator={operator} />

        <div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>
          <_MSSubassyFaroPanel runoutTIR={runoutTIR} setRunoutTIR={setRunoutTIR} ncrTrip={ncrTrip} />
          <div style={{ padding: "10px 14px", borderBottom: "1px solid " + _LINES }}>
            <div className="label" style={{ marginBottom: 6, color: _INK3, letterSpacing: "0.04em" }}>
              ALIGNMENT SUMMARY · MTL-220.50
            </div>
            <div style={{ border: "1px solid " + _LINE, borderRadius: 3, background: _BG }}>
              {[
                ["Spindle ↔ head taper",  "HSK-A63 · seat torque 220 Nm ±5%"],
                ["C-axis ↔ spindle nose", "0.004° captured · target ≤ 0.005°"],
                ["ATC pocket-1 ↔ nose",   "0.018 mm centerline · ≤ 0.02 mm"],
                ["TNC kinematics cycle",  "Heidenhain 451 · log bound to S/N"],
                ["Encoder feedback",      "LC 415 · paired, 0.001 mm resolution"],
                ["Lap stones consumed",   "2 of 3 · re-grind cell within tol"],
              ].map(([k, v]) => _kvRow(k, v))}
            </div>
          </div>
          <_MSSubassyStationClose okToClose={okToClose} ncrTrip={ncrTrip} runoutTIR={runoutTIR} steps={steps} stepsDone={stepsDone} photoCount={photoCount} emitted={emitted} closeStation={closeStation} />
        </div>
      </div>

      {/* ── Footer ledger preview ─────────────────────────────── */}
      <div style={_MS_LEDGER_FOOTER_STYLE}>
        <span className="mono" style={{ letterSpacing: "0.04em" }}>
          ledger · {emitted
            ? "SUBASSY_COMPLETED · " + serial + " · TIR " + runoutTIR.toFixed(2) + " µm @ 24k rpm"
            : "pending · awaits station close"}
        </span>
        <span className="mono" style={{ letterSpacing: "0.04em" }}>
          IATF 16949 §8.5.6 · ISO 230-1 · Faro Vantage cert 2026-04
        </span>
      </div>
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────
   _RunoutTrace — synthetic Faro tracker trace, 30 s window, 3 sweeps.
   Sweep 3's amplitude tracks the live TIR slider. 4 µm marked as auto-NCR.
   ──────────────────────────────────────────────────────────────────── */

function _RunoutTrace({ tir, ncr }) {
  const W = 460, H = 140, padL = 36, padB = 22, padT = 10, padR = 8;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const yMax = 6;
  const sx = t => padL + (t / 30) * innerW;
  const sy = u => padT + innerH - (u / yMax) * innerH;

  function sweep(amp, phase) {
    const out = [];
    for (let i = 0; i <= 60; i++) {
      const t = (i / 60) * 30;
      const noise = Math.sin(i * 0.71 + phase) * 0.08 + Math.sin(i * 1.13 + phase * 0.6) * 0.05;
      const u = Math.max(0.05, amp * (0.55 + 0.45 * Math.sin(i * 0.42 + phase)) + noise * amp * 0.6);
      out.push("L" + sx(t) + "," + sy(u));
    }
    out[0] = "M" + out[0].slice(1);
    return out.join(" ");
  }

  return (
    <svg viewBox={"0 0 " + W + " " + H} width="100%" height={H}
         style={{ background: _BG, border: "1px solid " + _LINE, borderRadius: 3 }}>
      {[0, 1, 2, 3, 4, 5, 6].map(u => (
        <g key={"u" + u}>
          <line x1={padL} y1={sy(u)} x2={W - padR} y2={sy(u)}
                stroke={u === 4 ? _BAD : _LINES}
                strokeWidth={u === 4 ? 1 : 0.5}
                strokeDasharray={u === 4 ? "4 3" : "none"} />
          <text x={padL - 5} y={sy(u) + 3.5} fontSize="9" textAnchor="end"
                fontFamily="var(--font-mono)" fill={u === 4 ? _BAD : _INK4}>{u}</text>
        </g>
      ))}
      {[0, 5, 10, 15, 20, 25, 30].map(t => (
        <g key={"t" + t}>
          <line x1={sx(t)} y1={padT} x2={sx(t)} y2={H - padB} stroke={_LINES} strokeWidth="0.5" />
          <text x={sx(t)} y={H - padB + 11} fontSize="9" textAnchor="middle"
                fontFamily="var(--font-mono)" fill={_INK4}>{t}s</text>
        </g>
      ))}
      <text x="6" y="12" fontSize="9.5" fontFamily="var(--font-mono)" fill={_INK3}>µm TIR</text>
      <text x={W - padR - 4} y={H - 4} fontSize="9.5" textAnchor="end"
            fontFamily="var(--font-mono)" fill={_INK3}>30 s window · 24,000 rpm</text>

      <rect x={padL} y={padT} width={innerW} height={sy(4) - padT} fill={_BAD} opacity="0.06" />

      <path d={sweep(2.4, 0.0)} stroke={_INK4} strokeWidth="1" fill="none" opacity="0.55" />
      <path d={sweep(2.6, 1.4)} stroke={_INK3} strokeWidth="1" fill="none" opacity="0.7" />
      <path d={sweep(tir, 2.7)} stroke={ncr ? _BAD : _ACCENT} strokeWidth="1.6" fill="none" />

      <g transform={"translate(" + (W - 168) + ", " + (padT + 4) + ")"}>
        <rect x="0" y="0" width="160" height="46" fill={_BG} stroke={_LINES} rx="2" />
        <line x1="6" y1="12" x2="22" y2="12" stroke={_INK4} strokeWidth="1" />
        <text x="28" y="15" fontSize="9.5" fontFamily="var(--font-mono)" fill={_INK3}>sweep 1 · 2.4 µm</text>
        <line x1="6" y1="24" x2="22" y2="24" stroke={_INK3} strokeWidth="1" />
        <text x="28" y="27" fontSize="9.5" fontFamily="var(--font-mono)" fill={_INK3}>sweep 2 · 2.6 µm</text>
        <line x1="6" y1="36" x2="22" y2="36" stroke={ncr ? _BAD : _ACCENT} strokeWidth="1.6" />
        <text x="28" y="39" fontSize="9.5" fontFamily="var(--font-mono)" fill={ncr ? _BAD : _INK2}>
          sweep 3 · {tir.toFixed(2)} µm {ncr ? "· NCR" : ""}
        </text>
      </g>
    </svg>
  );
}

/* route registration — agent #3 owns registerMittelstandRoute; we
   register only when bound, so this file is safe to load before it ships */
if (typeof registerMittelstandRoute === "function") {
  registerMittelstandRoute({
    path: "/traveler/motor-assy",
    mode: "traveler",
    title: "Subassembly + spindle alignment",
    renderer: () => React.createElement(ScreenMittelstandSubassy),
  });
}

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