(function(){
/* FORGE · Mittelstand · Station 2 traveler — Machine Shop CNC + dim inspect.
   Path /traveler/machine-shop · ScreenMittelstandMachineShop · agent #12 traveler-B.
   Spec mittelstand.md §8 station 2 + §9 ledger + §10 cool-gray palette.
   Multi-step flow: (1) CMM probe X/Y/Z bores → (2) Re-grind acceptance (ECO-MS-0017
   granite flatness ≤3 µm) → (3) PIN entry → (4) Sign-off + advance.
   Emits DIM_INSPECTED per dim + ROUTING_PASS per op. Babel-standalone, no imports. */

const { useState: uSMS, useEffect: uEMS, useMemo: uMMS } = React;

/* ────────────────────────────────────────────────────────────────────
   Style atoms · cool graphite palette (oklch hue band 240–260)
   Mirrors mittelstand.md §10 var block; inline fallback if vars missing.
   ──────────────────────────────────────────────────────────────────── */

const MS_BG          = "var(--mittel-bg, oklch(0.97 0.003 250))";
const MS_BG_2        = "var(--mittel-bg-2, oklch(0.92 0.004 250))";
const MS_BG_3        = "var(--mittel-bg-3, oklch(0.95 0.003 250))";
const MS_INK         = "var(--mittel-ink, oklch(0.18 0.01 250))";
const MS_INK_2       = "var(--mittel-ink-2, oklch(0.32 0.01 250))";
const MS_INK_3       = "var(--mittel-ink-3, oklch(0.48 0.01 250))";
const MS_INK_4       = "var(--mittel-ink-4, oklch(0.62 0.005 250))";
const MS_LINE        = "var(--mittel-line, oklch(0.82 0.005 250))";
const MS_LINE_SOFT   = "var(--mittel-line-soft, oklch(0.88 0.004 250))";
const MS_ACCENT      = "var(--mittel-accent, oklch(0.55 0.02 250))";
const MS_WARN        = "var(--mittel-accent-warn, oklch(0.62 0.13 60))";
const MS_BAD         = "var(--mittel-accent-bad, oklch(0.55 0.18 25))";
const MS_OK          = "oklch(0.55 0.13 150)";
const MS_FONT_MONO   = "var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace)";
const MS_FONT_UI     = "var(--font-ui, system-ui, -apple-system, Segoe UI, Roboto, sans-serif)";
const _MS_LBL = { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_4,
  letterSpacing: "0.06em", textTransform: "uppercase", marginBottom: 6 };

/* ────────────────────────────────────────────────────────────────────
   Tiny helpers (file-scoped — no collisions with pump/_a4_*)
   ──────────────────────────────────────────────────────────────────── */

function _ms_now() {
  const t = new Date();
  const p = (n) => String(n).padStart(2, "0");
  return p(t.getHours()) + ":" + p(t.getMinutes()) + ":" + p(t.getSeconds());
}

function _ms_today() {
  const t = new Date();
  const p = (n) => String(n).padStart(2, "0");
  return t.getFullYear() + "-" + p(t.getMonth() + 1) + "-" + p(t.getDate());
}

function _ms_initials(n) {
  if (!n) return "—";
  const parts = String(n).replace(/[^A-Za-z. ]/g, "").split(/\s+/).filter(Boolean);
  if (!parts.length) return "—";
  const a = parts[0][0] || "";
  const b = parts[1] ? parts[1][0] : (parts[0][1] || "");
  return (a + b).toUpperCase();
}

function _ms_emit(eventName, payload) {
  if (typeof window === "undefined") return;
  // Best-effort — listen target is the Mittelstand ledger (agent #18). We just
  // fire a CustomEvent on window; the ledger wires its handler when it loads.
  try {
    window.dispatchEvent(new CustomEvent("forge:ledger", {
      detail: { tenant: "mittelstand", event: eventName, ts: new Date().toISOString(), payload: payload }
    }));
  } catch (e) { /* swallow — defensive only */ }
}

/* Operator-grade button — used when global Btn primitive is not yet loaded.
   Mono, tall hit-target, cool palette. Variants: default, primary, danger, ghost. */
function _MSBtn(props) {
  const v = props.variant || "default";
  const sz = props.size || "md";
  const disabled = !!props.disabled;
  const padding = sz === "sm" ? "6px 10px" : sz === "lg" ? "12px 22px" : "9px 16px";
  const fontSize = sz === "sm" ? 11 : sz === "lg" ? 14 : 12.5;

  const m = { primary: [MS_INK, "#fff", MS_INK], danger: [MS_BAD, "#fff", MS_BAD],
              ghost: ["transparent", MS_INK_3, "transparent"], accent: [MS_ACCENT, "#fff", MS_ACCENT],
              default: [MS_BG, MS_INK_2, MS_LINE] }[v] || [MS_BG, MS_INK_2, MS_LINE];
  return React.createElement("button", {
    onClick: disabled ? undefined : props.onClick, title: props.title,
    style: { padding: padding, background: disabled ? MS_BG_2 : m[0], color: disabled ? MS_INK_4 : m[1],
             border: "1px solid " + (disabled ? MS_LINE : m[2]), borderRadius: 3,
             fontFamily: MS_FONT_MONO, fontSize: fontSize, letterSpacing: "0.04em",
             textTransform: "uppercase", fontWeight: 500,
             cursor: disabled ? "not-allowed" : "pointer", opacity: disabled ? 0.55 : 1,
             transition: "background 90ms ease",
             minHeight: sz === "sm" ? 26 : sz === "lg" ? 44 : 34 }
  }, props.children);
}

function _MSPill(props) {
  const T = { ok: MS_OK, warn: MS_WARN, bad: MS_BAD, accent: MS_ACCENT };
  const c = T[props.tone];
  const t = c
    ? { bg: "color-mix(in oklch, " + c + " 14%, " + MS_BG + ")", fg: c, bd: c }
    : { bg: MS_BG_3, fg: MS_INK_3, bd: MS_LINE };
  return React.createElement("span", {
    style: { display: "inline-flex", alignItems: "center", gap: 4, padding: "1px 7px",
             background: t.bg, color: t.fg, border: "1px solid " + t.bd, borderRadius: 3,
             fontFamily: MS_FONT_MONO, fontSize: 12, letterSpacing: "0.06em", textTransform: "uppercase" }
  }, props.children);
}

/* ────────────────────────────────────────────────────────────────────
   Seed — six CMM bores + one re-grind flatness check
   Every dimension carries µm-resolution target & spec band.
   ──────────────────────────────────────────────────────────────────── */

function _ms_initial_dims() {
  // Step 1 — CMM probe runs on X/Y/Z bores (Zeiss Crysta-Apex S, TP200 probe).
  // Step 2 — Re-grind acceptance per ECO-MS-0017 (Mahr LP1500 + Talyvel 6).
  // captured_um is signed deviation from nominal (or absolute when .absolute=true).
  const cmm = "Zeiss Crysta-Apex S · TP200 probe";
  const flat = "Mahr LP1500 granite + Taylor-Hobson Talyvel 6";
  return [
    { id: "x_bs_a", step: 1, axis: "X", label: "X-carriage ball-screw bore A",
      target_mm: 60.000, tol_um: 8,  target_disp: "Ø60.000 +0.008/-0 mm",
      captured_um: -2, gate: "QG-02", instrument: cmm, op: "OP-040" },
    { id: "x_bs_b", step: 1, axis: "X", label: "X-carriage ball-screw bore B",
      target_mm: 60.000, tol_um: 8,  target_disp: "Ø60.000 +0.008/-0 mm",
      captured_um:  4, gate: "QG-02", instrument: cmm, op: "OP-040" },
    { id: "y_lg_a", step: 1, axis: "Y", label: "Y-bridge linear-guide bore A",
      target_mm: 45.000, tol_um: 6,  target_disp: "Ø45.000 +0.006/-0 mm",
      captured_um:  1, gate: "QG-02", instrument: cmm, op: "OP-050" },
    { id: "y_lg_b", step: 1, axis: "Y", label: "Y-bridge linear-guide bore B",
      target_mm: 45.000, tol_um: 6,  target_disp: "Ø45.000 +0.006/-0 mm",
      captured_um:  3, gate: "QG-02", instrument: cmm, op: "OP-050" },
    { id: "z_ram",  step: 1, axis: "Z", label: "Z-ram counter-bore",
      target_mm: 80.000, tol_um: 10, target_disp: "Ø80.000 +0.010/-0 mm",
      captured_um:  5, gate: "QG-02", instrument: cmm, op: "OP-060" },
    { id: "z_squ",  step: 1, axis: "Z", label: "Z-ram squareness to X (TIR)",
      target_mm:  0.000, tol_um: 5,  target_disp: "≤5 µm TIR over 300 mm",
      captured_um:  3, gate: "QG-02", instrument: cmm + " · scan path", op: "OP-060", absolute: true },
    { id: "gran_top", step: 2, axis: "FLAT", label: "Granite-bed top flatness · post re-grind (10.01)",
      target_mm: 0.000, tol_um: 3,  target_disp: "≤3 µm flatness · ECO-MS-0017",
      captured_um:  2, gate: "QG-03", instrument: flat, op: "OP-RG-A", absolute: true },
    { id: "gran_xb",  step: 2, axis: "FLAT", label: "Cross-beam flatness · post re-grind (10.02)",
      target_mm: 0.000, tol_um: 3,  target_disp: "≤3 µm flatness · ECO-MS-0017",
      captured_um:  2, gate: "QG-03", instrument: flat, op: "OP-RG-B", absolute: true },
  ];
}

/* dim → pass test. For absolute dims the captured µm magnitude must be ≤ tol.
   For deviation dims the signed captured µm must lie in [-tol, +tol]. */
function _ms_dim_pass(d) {
  if (typeof d.captured_um !== "number" || isNaN(d.captured_um)) return false;
  if (d.absolute) return d.captured_um >= 0 && d.captured_um <= d.tol_um;
  return d.captured_um >= -d.tol_um && d.captured_um <= d.tol_um;
}

/* Header — cool palette mirror of pump _A4StationHeader. */
function _MSHeader(props) {
  const sBadge = { display: "inline-flex", alignItems: "center", justifyContent: "center",
    width: 36, height: 36, borderRadius: 3, background: MS_INK, color: "#fff",
    border: "1px solid " + MS_INK, fontFamily: MS_FONT_MONO, fontSize: 12, fontWeight: 600, letterSpacing: "0.04em" };
  return React.createElement("div", {
    style: { padding: "12px 18px", background: MS_BG_2, borderBottom: "1px solid " + MS_LINE,
             display: "flex", alignItems: "center", gap: 16 }
  },
    React.createElement("span", { style: sBadge }, _ms_initials(props.operator)),
    React.createElement("div", { style: { flex: 1, minWidth: 0 } },
      React.createElement("div", {
        style: { fontSize: 13, color: MS_INK, fontFamily: MS_FONT_UI, display: "flex", alignItems: "center", gap: 10 }
      },
        React.createElement("b", { style: { letterSpacing: "0.01em" } }, props.title),
        React.createElement("span", { style: { color: MS_INK_4 } }, "·"),
        React.createElement("span", { style: { color: MS_INK_2 } }, props.subtitle),
      ),
      React.createElement("div", {
        style: { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_4, marginTop: 2, letterSpacing: "0.03em" }
      }, props.meta),
    ),
    props.right
  );
}

/* Step indicator strip. */
function _MSSteps(props) {
  const steps = [
    { n: 1, label: "CMM probe · X/Y/Z bores" },
    { n: 2, label: "Re-grind acceptance" },
    { n: 3, label: "PIN attestation" },
    { n: 4, label: "Sign-off + advance" },
  ];
  return React.createElement("div", {
    style: { display: "flex", padding: "10px 18px", borderBottom: "1px solid " + MS_LINE, background: MS_BG }
  }, steps.map((s, i) => {
    const done = props.completed.indexOf(s.n) >= 0, active = props.current === s.n;
    const fg = done ? MS_OK : active ? MS_INK : MS_INK_4;
    const bd = done ? MS_OK : active ? MS_INK : MS_LINE;
    const bg = done ? "color-mix(in oklch, " + MS_OK + " 12%, " + MS_BG + ")" : active ? MS_BG_2 : "transparent";
    return React.createElement("div", {
      key: s.n,
      style: { flex: 1, padding: "8px 12px", background: bg, color: fg,
               border: "1px solid " + bd, borderRight: i === steps.length - 1 ? ("1px solid " + bd) : "none",
               display: "flex", alignItems: "center", gap: 10, fontFamily: MS_FONT_UI, fontSize: 12 }
    },
      React.createElement("span", {
        style: { display: "inline-flex", alignItems: "center", justifyContent: "center",
                 width: 22, height: 22, borderRadius: "50%",
                 background: done ? MS_OK : active ? MS_INK : "transparent",
                 color: (done || active) ? "#fff" : MS_INK_4,
                 border: "1px solid " + bd, fontFamily: MS_FONT_MONO, fontSize: 12, fontWeight: 600 }
      }, done ? "✓" : s.n),
      React.createElement("span", { style: { letterSpacing: "0.01em" } }, s.label),
    );
  }));
}

/* ────────────────────────────────────────────────────────────────────
   Main screen
   ──────────────────────────────────────────────────────────────────── */

function _MSMshopStep1Block({ dimsStep1, step1AllPass, photoCount, setPhotoCount, setDims, commitStep1, setDimUm, inspection_plan }) {
  return React.createElement(React.Fragment, null,
    _MSStepHeader("1", "CMM probe · X/Y/Z carriage bores",
      "Zeiss Crysta-Apex S, TP200 touch probe, inspection plan " + inspection_plan + ". Capture dimensional deviation in µm. Out-of-band auto-flags."),
    dimsStep1.map(d => _MSDimRow(d, setDimUm)),
    React.createElement("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 14, marginBottom: 10 } },
      _MSPhotoBlock(photoCount, setPhotoCount, "Snap probe contact + part marking. Auto-tags S/N, station, op."),
      _MSCmmDumpBlock()),
    _MSStepFooter(
      dimsStep1.filter(_ms_dim_pass).length + " / " + dimsStep1.length + " in tol",
      step1AllPass ? { tone: MS_OK, txt: "ready to commit" } : { tone: MS_WARN, txt: "resolve out-of-tol before commit" },
      [
        React.createElement(_MSBtn, { key: "rz", variant: "ghost", onClick: () => setDims(prev => {
            const seed = _ms_initial_dims();
            return prev.map(d => d.step !== 1 ? d : (Object.assign({}, d, { captured_um: (seed.find(x => x.id === d.id) || d).captured_um })));
          }) }, "re-zero step 1"),
        React.createElement(_MSBtn, { key: "go", variant: step1AllPass ? "primary" : "default",
          disabled: !step1AllPass, onClick: commitStep1 }, "commit step 1 ▸"),
      ],
    ),
  );
}

function _MSMshopStep2Block({ dimsStep2, step2AllPass, commitStep2, setStep, setDimUm }) {
  return React.createElement(React.Fragment, null,
    _MSStepHeader("2", "Re-grind acceptance · granite-bed flatness post-op",
      "ECO-MS-0017 tightens 10.01 + 10.02 flatness from ±5 µm to ≤3 µm. Two-pass lap, re-grind between rough and finish. Mahr LP1500 granite + Talyvel 6."),
    React.createElement("div", {
      style: { padding: 12, marginBottom: 12, fontSize: 12, color: MS_INK_2, lineHeight: 1.55,
               background: "color-mix(in oklch, " + MS_ACCENT + " 6%, " + MS_BG + ")",
               border: "1px solid " + MS_ACCENT, borderRadius: 3 }
    },
      React.createElement("div", { style: { color: MS_ACCENT, fontFamily: MS_FONT_MONO, fontSize: 12, letterSpacing: "0.06em", marginBottom: 4, textTransform: "uppercase" } },
        "ECO-MS-0017 · root cause"),
      "Three Rev-C field returns showed vibration > 0.8 mm/s RMS at 12k rpm contouring, traced to granite cross-beam flatness drift on S/N 0089–0094. Spec re-baselined ±5 µm → ≤3 µm; re-grind op added. Capture flatness post-finish-lap to clear gate QG-03.",
    ),
    dimsStep2.map(d => _MSDimRow(d, setDimUm)),
    _MSStepFooter(
      dimsStep2.filter(_ms_dim_pass).length + " / " + dimsStep2.length + " in tol",
      step2AllPass ? { tone: MS_OK, txt: "re-grind accepted" } : { tone: MS_BAD, txt: "re-grind reject — re-lap" },
      [
        React.createElement(_MSBtn, { key: "bk", variant: "ghost", onClick: () => setStep(1) }, "◂ back to step 1"),
        React.createElement(_MSBtn, { key: "go", variant: step2AllPass ? "primary" : "default",
          disabled: !step2AllPass, onClick: commitStep2 }, "commit step 2 ▸"),
      ],
    ),
  );
}

function _MSMshopStep3Block({ pin, setPin, pinError, setPinError, submitPin, setStep, operator }) {
  return React.createElement(React.Fragment, null,
    _MSStepHeader("3", "PIN attestation",
      "Operator badge PIN. Required to advance. PIN is not auth — it stamps the traveler with attribution."),
    React.createElement("div", {
      style: { maxWidth: 460, margin: "12px 0", padding: 18, border: "1px solid " + MS_LINE, borderRadius: 3, background: MS_BG_3 }
    },
      React.createElement("div", { style: { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_4, letterSpacing: "0.06em", textTransform: "uppercase", marginBottom: 6 } },
        "operator · " + operator),
      React.createElement("div", { style: { fontSize: 12, color: MS_INK_3, marginBottom: 14, lineHeight: 1.5 } },
        "Enter your 4-digit cell PIN. Captured measurements above will be hash-stamped to your badge."),
      React.createElement("div", { style: { display: "flex", gap: 8, alignItems: "center" } },
        React.createElement("input", {
          type: "password", inputMode: "numeric", maxLength: 4, value: pin, placeholder: "• • • •",
          onChange: e => { setPin(e.target.value.replace(/[^0-9]/g, "")); setPinError(""); },
          onKeyDown: e => { if (e.key === "Enter") submitPin(); },
          style: { flex: 1, padding: "12px 14px",
                   fontFamily: MS_FONT_MONO, fontSize: 22, letterSpacing: "0.5em", textAlign: "center",
                   background: MS_BG, color: MS_INK,
                   border: "1px solid " + (pinError ? MS_BAD : MS_LINE), borderRadius: 3, outline: "none" },
        }),
        React.createElement(_MSBtn, { variant: "primary", size: "lg", disabled: pin.length !== 4, onClick: submitPin }, "verify ▸"),
      ),
      pinError && React.createElement("div", { style: { color: MS_BAD, fontSize: 12, marginTop: 8, fontFamily: MS_FONT_MONO } }, pinError),
      React.createElement("div", { style: { fontSize: 12, color: MS_INK_4, marginTop: 14, fontFamily: MS_FONT_MONO, letterSpacing: "0.03em" } },
        "hint · demo PIN: any 4 digits"),
    ),
    React.createElement(_MSBtn, { variant: "ghost", onClick: () => setStep(2) }, "◂ back to step 2"),
  );
}

function _MSMshopActivityRail({ emitLog }) {
  return React.createElement("div", {
    style: { borderLeft: "1px solid " + MS_LINE, background: MS_BG_3,
             display: "flex", flexDirection: "column", minHeight: 0 }
  },
    React.createElement("div", {
      style: { padding: "10px 14px", borderBottom: "1px solid " + MS_LINE, background: MS_BG_2,
               fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_3,
               letterSpacing: "0.06em", textTransform: "uppercase",
               display: "flex", justifyContent: "space-between", alignItems: "center" }
    },
      React.createElement("span", null, "ledger emit · station 2"),
      React.createElement(_MSPill, null, emitLog.length + " evt"),
    ),
    React.createElement("div", { style: { flex: 1, overflow: "auto" } },
      emitLog.length === 0 && React.createElement("div", {
        style: { padding: 14, fontSize: 12, color: MS_INK_4, lineHeight: 1.5 }
      },
        "No events yet. Commit step 1 to emit ",
        React.createElement("span", { style: { fontFamily: MS_FONT_MONO } }, "DIM_INSPECTED"),
        " + ", React.createElement("span", { style: { fontFamily: MS_FONT_MONO } }, "ROUTING_PASS"), "."),
      emitLog.map((e, i) => React.createElement("div", {
        key: i,
        style: { padding: "9px 14px", borderBottom: "1px solid " + MS_LINE_SOFT, fontSize: 12, color: MS_INK_2 }
      },
        React.createElement("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: 3 } },
          React.createElement("span", { style: { fontFamily: MS_FONT_MONO, color: MS_ACCENT, fontWeight: 600 } }, e.name),
          React.createElement("span", { style: { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_4 } }, e.ts),
        ),
        React.createElement("div", {
          style: { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_4, lineHeight: 1.55, wordBreak: "break-word" }
        }, _ms_payload_summary(e.payload)),
      )),
    ),
    React.createElement("div", {
      style: { padding: "10px 14px", borderTop: "1px solid " + MS_LINE, background: MS_BG_2,
               fontSize: 12, color: MS_INK_4, lineHeight: 1.55 }
    },
      React.createElement("div", { style: Object.assign({}, _MS_LBL, { color: MS_INK_3, marginBottom: 4 }) }, "station notes"),
      "Mahr granite plate calibrated 2026-08-09 vs. PTB master · valid 12 mo. Talyvel 6 zeroed at 06:18 against ring std. Probe stylus M3 Ø3 mm ruby, run-out < 1 µm.",
    ),
  );
}

function ScreenMittelstandMachineShop() {
  const operator = "M. Schäfer";
  const operatorRole = "CNC operator · machine cell 03";
  const wo = "WO-MTL-2403";
  const part = "MTL-220.10.00";
  const inspection_plan = "INS-MTL-220-D-02";
  const eco = "ECO-MS-0017";

  const [step, setStep]           = uSMS(1);
  const [completed, setCompleted] = uSMS([]);
  const [dims, setDims]           = uSMS(_ms_initial_dims());
  const [photoCount, setPhotoCount] = uSMS(0);
  const [pin, setPin]             = uSMS("");
  const [pinAccepted, setPinAccepted] = uSMS(false);
  const [pinError, setPinError]   = uSMS("");
  const [signed, setSigned]       = uSMS(false);
  const [advanced, setAdvanced]   = uSMS(false);
  const [emitLog, setEmitLog]     = uSMS([]);

  // Reset on tenant flip — agent #2 fires forge:tenant-change.
  uEMS(() => {
    if (typeof window === "undefined") return undefined;
    const onTenant = () => {
      setStep(1); setCompleted([]); setDims(_ms_initial_dims());
      setPhotoCount(0); setPin(""); setPinAccepted(false); setPinError("");
      setSigned(false); setAdvanced(false); setEmitLog([]);
    };
    window.addEventListener("forge:tenant-change", onTenant);
    return () => window.removeEventListener("forge:tenant-change", onTenant);
  }, []);

  const dimsStep1 = useFilter(dims, d => d.step === 1);
  const dimsStep2 = useFilter(dims, d => d.step === 2);

  const step1AllPass = dimsStep1.every(_ms_dim_pass);
  const step2AllPass = dimsStep2.every(_ms_dim_pass);
  const allPass = step1AllPass && step2AllPass;

  function setDimUm(id, val) {
    const num = (val === "" || val === "-") ? val : Number(val);
    setDims(prev => prev.map(d => d.id === id ? { ...d, captured_um: (num === "" || num === "-") ? num : (isNaN(num) ? d.captured_um : num) } : d));
  }

  function emit(eventName, payload) {
    _ms_emit(eventName, payload);
    setEmitLog(prev => [{ ts: _ms_now(), name: eventName, payload: payload }, ...prev].slice(0, 12));
  }

  function _markDone(n) { setCompleted(prev => prev.indexOf(n) < 0 ? prev.concat(n) : prev); }

  function _commit(stepDims, opGroup, ecoTag) {
    stepDims.forEach(d => emit("DIM_INSPECTED", {
      wo: wo, part: part, dim: d.id, op: d.op, axis: d.axis,
      target_um: d.absolute ? d.tol_um : 0, captured_um: d.captured_um,
      tol_um: d.tol_um, instrument: d.instrument, pass: _ms_dim_pass(d),
    }));
    emit("ROUTING_PASS", {
      wo: wo, station: "machine-shop", op_group: opGroup, operator: operator,
      dims_count: stepDims.length, eco: ecoTag, plan: inspection_plan,
    });
  }

  function commitStep1() { _commit(dimsStep1, "OP-040..060 · X/Y/Z bores", null); _markDone(1); setStep(2); }
  function commitStep2() { _commit(dimsStep2, "OP-RG · re-grind granite", eco); _markDone(2); setStep(3); }

  function submitPin() {
    if (!/^\d{4}$/.test(pin)) { setPinError("PIN must be 4 digits."); return; }
    setPinError(""); setPinAccepted(true); _markDone(3); setStep(4);
  }

  function signAndAdvance() {
    if (!signed || !pinAccepted || !allPass) return;
    _markDone(4); setAdvanced(true);
    emit("ROUTING_PASS", { wo: wo, station: "machine-shop", op_group: "STATION-CLOSE",
      operator: operator, signed_at: _ms_now(), date: _ms_today(), next_station: "subassy" });
    if (typeof navigate === "function") setTimeout(() => navigate("/traveler/subassy"), 400);
  }

  /* ── Render ── */

  return React.createElement("div", {
    style: {
      display: "flex", flexDirection: "column",
      height: "100%", minHeight: 0,
      background: MS_BG, color: MS_INK,
      fontFamily: MS_FONT_UI,
    }
  },

    React.createElement(_MSHeader, {
      operator: operator,
      title: "Machine Shop · Station 2 · MTL-220 · CMM probe + Re-grind acceptance",
      subtitle: operatorRole,
      meta: wo + "  ·  part " + part + "  ·  plan " + inspection_plan + "  ·  " + eco + "  ·  shift A · " + _ms_now(),
      right: React.createElement("div", { style: { display: "flex", gap: 8, alignItems: "center" } },
        React.createElement(_MSPill, { tone: "accent" }, "ECO-MS-0017"),
        React.createElement(_MSPill, { tone: allPass ? "ok" : "warn" },
          allPass ? "all in tol" : (dims.filter(d => !_ms_dim_pass(d)).length + " out")),
      ),
    }),

    React.createElement(_MSSteps, { current: step, completed: completed }),

    /* Body grid: form column + activity rail */
    React.createElement("div", {
      style: { flex: 1, display: "grid", gridTemplateColumns: "1.65fr 320px", minHeight: 0 }
    },

      /* ── form column ── */
      React.createElement("div", {
        style: { overflow: "auto", padding: "18px 22px" }
      },

        /* Context strip */
        React.createElement("div", {
          style: {
            display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10,
            marginBottom: 16, padding: 12,
            border: "1px solid " + MS_LINE, borderRadius: 3,
            background: MS_BG_3,
          }
        },
          _MSKv("UNIT IN PROGRESS", "MTL-220 · S/N 0095", true),
          _MSKv("TRAVELER", "TRV-MS-0244", true),
          _MSKv("STATION", "2 / 4 · machine shop", false),
          _MSKv("CYCLE TARGET", "180 min · actual 168 min", true),
        ),

        step === 1 && React.createElement(_MSMshopStep1Block, { dimsStep1, step1AllPass, photoCount, setPhotoCount, setDims, commitStep1, setDimUm, inspection_plan }),

        step === 2 && React.createElement(_MSMshopStep2Block, { dimsStep2, step2AllPass, commitStep2, setStep, setDimUm }),

        step === 3 && React.createElement(_MSMshopStep3Block, { pin, setPin, pinError, setPinError, submitPin, setStep, operator }),

        /* ── Step 4 — Sign-off + advance ── */
        step === 4 && React.createElement(React.Fragment, null,
          _MSStepHeader("4", "Sign-off + advance to Station 3",
            "Confirm operator attestation, then release the unit to subassembly. Emits ROUTING_PASS · STATION-CLOSE."),

          React.createElement("div", { style: { border: "1px solid " + MS_LINE, borderRadius: 3, background: MS_BG_3, marginBottom: 14, overflow: "hidden" } },
            React.createElement("div", {
              style: { padding: "8px 14px", borderBottom: "1px solid " + MS_LINE, background: MS_BG_2,
                       display: "flex", alignItems: "center", justifyContent: "space-between",
                       fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_3,
                       letterSpacing: "0.06em", textTransform: "uppercase" }
            },
              "captured dimensions · " + dims.length,
              React.createElement(_MSPill, { tone: allPass ? "ok" : "bad" }, allPass ? "all green" : "review"),
            ),
            dims.map(d => _MSSummaryRow(d)),
          ),

          React.createElement("div", { style: { padding: 16, border: "1px solid " + MS_LINE, borderRadius: 3, background: MS_BG_3, marginBottom: 14 } },
            React.createElement("label", { style: { display: "flex", gap: 12, alignItems: "flex-start", cursor: "pointer" } },
              React.createElement("input", {
                type: "checkbox", checked: signed, onChange: e => setSigned(e.target.checked),
                style: { marginTop: 4, width: 18, height: 18, accentColor: MS_INK },
              }),
              React.createElement("div", null,
                React.createElement("div", { style: { fontSize: 12.5, color: MS_INK, fontWeight: 500, marginBottom: 4 } }, "Operator attestation"),
                React.createElement("div", { style: { fontSize: 12, color: MS_INK_2, lineHeight: 1.55 } },
                  "I, ", React.createElement("b", { style: { color: MS_INK } }, operator),
                  ", certify the captured dimensions above were taken on traveler TRV-MS-0244 against inspection plan ",
                  React.createElement("span", { style: { fontFamily: MS_FONT_MONO } }, inspection_plan),
                  ". The re-grind acceptance follows ECO-MS-0017 protocol. PIN verified at ",
                  React.createElement("span", { style: { fontFamily: MS_FONT_MONO } }, _ms_now()), "."),
              ),
            ),
          ),

          React.createElement("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 } },
            React.createElement("div", { style: { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_4, letterSpacing: "0.04em" } },
              "gate · ",
              _MSGateChip("dims", allPass), "  ·  ",
              _MSGateChip("PIN", pinAccepted), "  ·  ",
              _MSGateChip("signed", signed),
            ),
            React.createElement("div", { style: { display: "flex", gap: 6 } },
              React.createElement(_MSBtn, { variant: "ghost", onClick: () => setStep(3) }, "◂ back"),
              React.createElement(_MSBtn, { variant: "danger",
                onClick: () => emit("NCR_OPENED", { wo: wo, station: "machine-shop", reason: "operator hold", operator: operator })
              }, "hold for QC"),
              React.createElement(_MSBtn, { variant: "primary", size: "lg",
                disabled: !(allPass && pinAccepted && signed) || advanced, onClick: signAndAdvance,
              }, advanced ? "advancing…" : "next station ▸ subassy"),
            ),
          ),
        ),

      ),

      React.createElement(_MSMshopActivityRail, { emitLog: emitLog }),

    ),

  );
}

/* Sub-render helpers — kept below main for readability. */

function _MSStepHeader(num, title, body) {
  return React.createElement("div", {
    style: { display: "flex", alignItems: "flex-start", gap: 14,
             padding: "8px 0 14px", borderBottom: "1px solid " + MS_LINE_SOFT, marginBottom: 14 }
  },
    React.createElement("span", {
      style: { display: "inline-flex", alignItems: "center", justifyContent: "center",
               width: 32, height: 32, borderRadius: 3, background: MS_INK, color: "#fff",
               fontFamily: MS_FONT_MONO, fontSize: 14, fontWeight: 600, flexShrink: 0 }
    }, num),
    React.createElement("div", null,
      React.createElement("div", { style: { fontSize: 14, color: MS_INK, fontWeight: 500, marginBottom: 4 } }, title),
      React.createElement("div", { style: { fontSize: 12, color: MS_INK_3, lineHeight: 1.55, maxWidth: 620 } }, body),
    ),
  );
}

function _MSStepFooter(progressTxt, status, buttons) {
  return React.createElement("div", {
    style: { display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14, gap: 8 }
  },
    React.createElement("div", { style: { fontSize: 12, color: MS_INK_4, fontFamily: MS_FONT_MONO, letterSpacing: "0.04em" } },
      progressTxt + "  ·  ",
      React.createElement("span", { style: { color: status.tone } }, status.txt),
    ),
    React.createElement("div", { style: { display: "flex", gap: 6 } }, buttons),
  );
}

function _MSSummaryRow(d) {
  const p = _ms_dim_pass(d);
  return React.createElement("div", {
    key: d.id,
    style: { display: "grid", gridTemplateColumns: "1fr 90px 90px 70px",
             padding: "7px 14px", borderBottom: "1px solid " + MS_LINE_SOFT,
             alignItems: "center", fontSize: 12 }
  },
    React.createElement("span", { style: { color: MS_INK_2 } }, d.label),
    React.createElement("span", { style: { fontFamily: MS_FONT_MONO, color: MS_INK_3, fontSize: 12 } },
      "tol " + (d.absolute ? "≤" : "±") + d.tol_um + " µm"),
    React.createElement("span", {
      style: { fontFamily: MS_FONT_MONO, fontSize: 12, color: p ? MS_OK : MS_BAD, fontWeight: 600 }
    }, (d.captured_um >= 0 ? "+" : "") + d.captured_um + " µm"),
    React.createElement(_MSPill, { tone: p ? "ok" : "bad" }, p ? "pass" : "fail"),
  );
}

function _MSGateChip(label, ok) {
  return React.createElement("span", { style: { color: ok ? MS_OK : MS_BAD } }, ok ? (label + " OK") : (label + " missing"));
}

function _MSDimRow(d, setDimUm) {
  const p = _ms_dim_pass(d);
  const out = !p;
  const cap = (typeof d.captured_um === "number") ? d.captured_um : 0;
  const labelStyle = { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_4,
                      letterSpacing: "0.06em", textTransform: "uppercase", marginBottom: 3 };
  const eqMm = (d.target_mm + (typeof cap === "number" ? cap : 0) / 1000).toFixed(4);

  return React.createElement("div", {
    key: d.id,
    style: {
      display: "grid", gridTemplateColumns: "1.7fr 110px 130px 110px 100px", gap: 12,
      padding: 12, marginBottom: 8,
      border: "1px solid " + (out ? MS_BAD : MS_LINE), borderRadius: 3,
      background: out ? "color-mix(in oklch, " + MS_BAD + " 6%, " + MS_BG + ")" : MS_BG,
      alignItems: "center",
    }
  },
    React.createElement("div", null,
      React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 3 } },
        React.createElement("span", {
          style: { display: "inline-flex", alignItems: "center", justifyContent: "center",
                   width: 28, height: 18, borderRadius: 2, background: MS_INK_2, color: "#fff",
                   fontFamily: MS_FONT_MONO, fontSize: 12, fontWeight: 600, letterSpacing: "0.04em" }
        }, d.axis),
        React.createElement("span", { style: { fontSize: 12.5, color: MS_INK, fontWeight: 500 } }, d.label),
      ),
      React.createElement("div", { style: { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_4, letterSpacing: "0.03em" } },
        d.gate + " · " + d.op + " · target ",
        React.createElement("span", { style: { color: MS_INK_3 } }, d.target_disp),
      ),
    ),
    React.createElement("div", null,
      React.createElement("div", { style: labelStyle }, "nominal · mm"),
      React.createElement("span", { style: { fontFamily: MS_FONT_MONO, fontSize: 13, color: MS_INK_2 } }, d.target_mm.toFixed(3)),
    ),
    React.createElement("div", null,
      React.createElement("div", { style: labelStyle }, "captured · µm  →  " + eqMm + " mm"),
      React.createElement("input", {
        type: "number", step: "1", value: cap,
        onChange: e => setDimUm(d.id, e.target.value),
        style: { width: "100%", padding: "8px 10px",
                 fontFamily: MS_FONT_MONO, fontSize: 14, fontWeight: 600,
                 background: MS_BG_2, color: out ? MS_BAD : MS_INK,
                 border: "1px solid " + (out ? MS_BAD : MS_LINE), borderRadius: 3, outline: "none" },
      }),
    ),
    React.createElement("div", null,
      React.createElement("div", { style: labelStyle }, "tol · µm"),
      React.createElement("span", { style: { fontFamily: MS_FONT_MONO, fontSize: 12.5, color: MS_INK_2 } },
        (d.absolute ? "≤" : "±") + d.tol_um),
    ),
    React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-start" } },
      React.createElement(_MSPill, { tone: p ? "ok" : "bad" }, p ? "in tol" : "out"),
      out && React.createElement("span", {
        style: { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_BAD, letterSpacing: "0.04em" }
      }, "auto-NCR"),
    ),
  );
}

function _MSKv(label, value, mono) {
  return React.createElement("div", null,
    React.createElement("div", { style: Object.assign({}, _MS_LBL, { marginBottom: 3 }) }, label),
    React.createElement("div", { style: { fontFamily: mono ? MS_FONT_MONO : MS_FONT_UI, fontSize: 12.5, color: MS_INK } }, value),
  );
}

function _MSPhotoBlock(count, setCount, hint) {
  return React.createElement("div", {
    style: { padding: 14, border: "1px dashed " + MS_LINE, borderRadius: 3, background: MS_BG_3, textAlign: "center" }
  },
    React.createElement("div", { style: _MS_LBL }, "photo capture · 2 required"),
    React.createElement("div", { style: { fontSize: 12, color: MS_INK_3, marginBottom: 10, lineHeight: 1.5 } }, hint),
    React.createElement(_MSBtn, { onClick: () => setCount(c => c + 1) }, "+ add photo"),
    React.createElement("div", { style: { fontFamily: MS_FONT_MONO, fontSize: 12, color: MS_INK_4, marginTop: 8 } },
      count + " captured · " + (count >= 2 ? "ready" : (2 - count) + " more required")),
  );
}

function _MSCmmDumpBlock() {
  return React.createElement("div", {
    style: { padding: 14, border: "1px solid " + MS_LINE, borderRadius: 3, background: MS_BG_3 }
  },
    React.createElement("div", { style: _MS_LBL }, "DMIS dump · paste optional"),
    React.createElement("textarea", {
      placeholder: "# Zeiss Crysta-Apex S · DMIS export\nFEAT-X-BS-A   Ø60.000   dev -2 µm   TIR 0.004\nFEAT-X-BS-B   Ø60.000   dev +4 µm   TIR 0.005\nFEAT-Z-RAM    Ø80.000   dev +5 µm   TIR 0.006\n…",
      style: { width: "100%", height: 96, padding: 8,
               background: MS_BG, border: "1px solid " + MS_LINE, borderRadius: 3,
               color: MS_INK_2, fontFamily: MS_FONT_MONO, fontSize: 12, resize: "none", outline: "none" },
    }),
  );
}

function _ms_payload_summary(p) {
  if (!p || typeof p !== "object") return "";
  const keys = ["dim", "op", "axis", "captured_um", "tol_um", "pass", "op_group", "station", "operator", "next_station", "reason"];
  const parts = [];
  keys.forEach(k => {
    if (p[k] !== undefined && p[k] !== null) {
      let v = p[k];
      if (typeof v === "number") v = (k.indexOf("_um") >= 0 ? ((v >= 0 ? "+" : "") + v + "µm") : String(v));
      if (typeof v === "boolean") v = v ? "✓" : "✗";
      parts.push(k + "=" + v);
    }
  });
  return parts.slice(0, 4).join("  ");
}

/* tiny array filter wrapper to keep main component readable */
function useFilter(arr, fn) {
  return uMMS(() => arr.filter(fn), [arr]);
}

/* Route registration · defensive (registerMittelstandRoute is owned by agent #3). */
(function registerMS() {
  if (typeof window === "undefined") return;
  const route = {
    path: "/traveler/machine-shop", mode: "traveler", title: "Machine shop",
    renderer: function() { return React.createElement(ScreenMittelstandMachineShop); },
  };
  if (typeof window.registerMittelstandRoute === "function") {
    window.registerMittelstandRoute(route); return;
  }
  if (!Array.isArray(window.MITTELSTAND_ROUTES)) window.MITTELSTAND_ROUTES = [];
  if (!window.MITTELSTAND_ROUTES.some(function(r) { return r && r.path === route.path; })) {
    window.MITTELSTAND_ROUTES.push(route);
  }
  window.ScreenMittelstandMachineShop = ScreenMittelstandMachineShop;
})();
})();
