(function(){
/* FORGE · Mittelstand tenant — Traveler Station 1 (Receiving + granite blank QC)
   Single screen; registered at /traveler/receiving for tenant.id === "mittelstand".
   No imports / no exports — Babel-standalone, globals only.
   Required globals: React, useActiveTenant()/getActiveTenant(), navigate(),
                     registerMittelstandRoute() (preferred) or registerPumpRoute() (fallback),
                     Pill, Btn, I, Panel, MSCard/MSPill/MSBtn (preferred — fall back to Pill/Btn).
   Spec: forge-web/demo/tenant-spec/mittelstand.md §8 station 1, §9 ledger event RECEIVING_LOGGED.
*/

const { useState: uSMR, useEffect: uEMR, useMemo: uMMR, useRef: uRMR } = React;

/* ────────────────────────────────────────────────────────────────────
   Atoms · prefer Mittelstand cross-cutting (MSCard/MSBtn/MSPill) when
   shipped by agent #8; fall back to forge-web/client/ui.jsx primitives.
   ──────────────────────────────────────────────────────────────────── */

function _msCard(props)  { return (typeof MSCard === "function") ? React.createElement(MSCard, props)  : React.createElement(Panel, props); }
function _msBtn(props)   { return (typeof MSBtn  === "function") ? React.createElement(MSBtn,  props)  : React.createElement(Btn,   props); }
function _msPill(props)  { return (typeof MSPill === "function") ? React.createElement(MSPill, props)  : React.createElement(Pill,  props); }

/* Color tokens — written so they pick up agent #8's palette swap once shipped,
   but render correctly today against the global token set.                  */
const _MS = {
  bg0:    "var(--mittel-bg, var(--bg-0))",
  bg1:    "var(--mittel-bg-2, var(--bg-1))",
  bg2:    "var(--mittel-bg-3, var(--bg-2))",
  ink:    "var(--mittel-ink, var(--ink))",
  ink2:   "var(--mittel-ink-2, var(--ink-2))",
  ink3:   "var(--mittel-ink-3, var(--ink-3))",
  ink4:   "var(--mittel-ink-4, var(--ink-4))",
  line:   "var(--mittel-line, var(--line))",
  lineS:  "var(--mittel-line-soft, var(--line-soft))",
  accent: "var(--mittel-accent, var(--accent))",
  warn:   "var(--mittel-accent-warn, var(--warn))",
  bad:    "var(--mittel-accent-bad, var(--err))",
};

/* ────────────────────────────────────────────────────────────────────
   Helpers
   ──────────────────────────────────────────────────────────────────── */

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

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

function _mr_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();
}

/* Extracted styles (react-doctor: no-inline-exhaustive-style). */
function _mrAvatarStyle(s) {
  return {
    display: "inline-flex", alignItems: "center", justifyContent: "center",
    width: s, height: s, borderRadius: "50%",
    background: "color-mix(in oklch, " + _MS.accent + " 14%, " + _MS.bg1 + ")",
    color: _MS.accent,
    border: "1px solid color-mix(in oklch, " + _MS.accent + " 30%, " + _MS.line + ")",
    fontFamily: "var(--font-mono)", fontSize: 12,
    letterSpacing: "0.04em", fontWeight: 600,
  };
}
const _MR_SELECT_STYLE = {
  width: "100%", padding: "10px 12px", fontSize: 14,
  background: _MS.bg0, color: _MS.ink,
  border: "1px solid " + _MS.line, borderRadius: 3,
  fontFamily: "var(--font-ui)",
};
const _MR_SERIAL_INPUT_STYLE = {
  width: "100%", padding: "10px 12px", fontSize: 14,
  background: _MS.bg0, color: _MS.ink,
  border: "1px solid " + _MS.line, borderRadius: 3,
  fontFamily: "var(--font-mono)", letterSpacing: "0.02em",
};
function _mrPhotoBtnStyle(captured) {
  return {
    width: "100%", padding: "10px 12px", fontSize: 13,
    background: captured ? "color-mix(in oklch, " + _MS.accent + " 14%, " + _MS.bg0 + ")" : _MS.bg0,
    color: captured ? _MS.accent : _MS.ink2,
    border: "1px solid " + (captured ? _MS.accent : _MS.line),
    borderRadius: 3, cursor: "pointer",
    display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
    fontFamily: "var(--font-ui)",
  };
}
function _mrCocInputStyle(valid) {
  return {
    flex: 1, padding: "10px 12px", fontSize: 12,
    background: _MS.bg0, color: _MS.ink,
    border: "1px solid " + (valid ? _MS.accent : _MS.line),
    borderRadius: 3,
    fontFamily: "var(--font-mono)", letterSpacing: "0.04em",
  };
}
const _MR_AUTO_BTN_STYLE = {
  padding: "10px 14px", fontSize: 12,
  background: _MS.bg1, color: _MS.ink2,
  border: "1px solid " + _MS.line, borderRadius: 3,
  cursor: "pointer", fontFamily: "var(--font-ui)",
};
function _mrFlatInputStyle(overReject, overTarget) {
  return {
    width: "100%", padding: "14px 16px", fontSize: 28,
    background: _MS.bg0,
    color: overReject ? _MS.bad : overTarget ? _MS.warn : _MS.ink,
    border: "1px solid " + (overReject ? _MS.bad : overTarget ? _MS.warn : _MS.line),
    borderRadius: 3,
    fontFamily: "var(--font-mono)",
    fontWeight: 600, letterSpacing: "0.02em",
  };
}
function _mrFlatMarkerStyle(flatnessNum, overReject, overTarget) {
  return {
    position: "absolute",
    left: Math.min(100, Math.max(0, (flatnessNum / 10) * 100)) + "%",
    top: -4, transform: "translateX(-50%)",
    width: 3, height: 18,
    background: overReject ? _MS.bad : overTarget ? _MS.warn : _MS.accent,
    borderRadius: 1.5,
    boxShadow: "0 0 0 2px " + _MS.bg0,
  };
}
const _MR_LEDGER_PRE_STYLE = {
  margin: 0, padding: "10px 12px",
  background: _MS.bg0, color: _MS.ink2,
  border: "1px solid " + _MS.lineS, borderRadius: 3,
  fontSize: 12, lineHeight: 1.55,
  overflow: "auto", maxHeight: 180,
};
const _MR_LOG_HEADER_STYLE = {
  display: "grid",
  gridTemplateColumns: "90px 100px 1.4fr 1fr 90px 90px 1.6fr",
  padding: "7px 14px",
  background: _MS.bg1,
  borderBottom: "1px solid " + _MS.line,
  position: "sticky", top: 0, zIndex: 2,
  fontSize: 12, color: _MS.ink3,
  textTransform: "uppercase", letterSpacing: "0.06em",
  fontFamily: "var(--font-ui)",
};
function _mrLogRowStyle(highlight) {
  return {
    display: "grid",
    gridTemplateColumns: "90px 100px 1.4fr 1fr 90px 90px 1.6fr",
    padding: "8px 14px",
    borderBottom: "1px solid " + _MS.lineS,
    fontSize: 12, alignItems: "center",
    background: highlight ? "color-mix(in oklch, " + _MS.accent + " 6%, transparent)" : "transparent",
  };
}
function _mrDecisionBtnStyle(disabled, bg, fg, border) {
  return {
    padding: "18px 12px",
    fontSize: 16, fontWeight: 600, letterSpacing: "0.05em",
    background: disabled ? _MS.bg1 : bg,
    color: disabled ? _MS.ink4 : fg,
    border: "1px solid " + (disabled ? _MS.lineS : border),
    borderRadius: 3,
    cursor: disabled ? "not-allowed" : "pointer",
    fontFamily: "var(--font-ui)",
    textTransform: "uppercase",
    transition: "background .12s, border-color .12s",
  };
}

function _mr_avatar(name, size) {
  const s = size || 28;
  return (
    <span style={_mrAvatarStyle(s)}>
      {_mr_initials(name)}
    </span>
  );
}

function useMrTenant() {
  return useActiveTenant();
}

/* SHA-256-ish synthetic hash for COC stamp display (deterministic for demo).
   Real provenance hashing is owned by the ledger agent; this is just visual. */
function _mr_synthHash(seed) {
  let h = 0xdeadbeef ^ String(seed || "").length;
  for (let i = 0; i < (seed || "").length; i++) {
    h = Math.imul(h ^ seed.charCodeAt(i), 2654435761);
  }
  const hex = (h >>> 0).toString(16).padStart(8, "0");
  return ("a3f" + hex + "9c14e22b07d518f9").slice(0, 24);
}

/* Emit a ledger receipt envelope — wired to window.forgeLedgerEmit when
   agent #18 lands; otherwise dispatches a CustomEvent the registry can pick up. */
function _mr_emitReceipt(eventType, payload) {
  const env = {
    event: eventType,
    ts: new Date().toISOString(),
    tenant: "mittelstand",
    wo: payload && payload.wo,
    payload: payload || {},
  };
  if (typeof window !== "undefined") {
    if (typeof window.forgeLedgerEmit === "function") {
      try { window.forgeLedgerEmit(env); } catch (e) { /* swallow */ }
    }
    try {
      window.dispatchEvent(new CustomEvent("forge:ledger-emit", { detail: env }));
    } catch (e) { /* older browsers */ }
  }
  return env;
}

/* ════════════════════════════════════════════════════════════════════
   ScreenMittelstandReceiving · /traveler/receiving
   Granite blank QC — surface-plate flatness probe @ 5 µm reject threshold.
   ──────────────────────────────────────────────────────────────────── */

const MR_OPERATORS = [
  "Andreas Brunner",   // shop-floor lead, granite cell
  "Klaus Steinmetz",   // metrology lead
  "Markus Hofer",      // receiving line
  "Ralf Drechsler",    // QC inspector
  "Sven Götz",         // night-shift cover
];

const MR_BLANK_SUPPLIERS = [
  "Diabas Granitwerke GmbH (Bayern)",
  "Kuhmichel Abrasiv (NRW)",
  "Bavaria Stone Quarries AG",
];

const MR_INITIAL_LOG = [
  { ts: "08:14:22", date: "2026-05-08", op: "Klaus Steinmetz",  sn: "GB-2401-001", flatness: 2.4, action: "PASS",   note: "Routed → lapping cell" },
  { ts: "09:02:11", date: "2026-05-08", op: "Andreas Brunner",  sn: "GB-2401-002", flatness: 2.9, action: "PASS",   note: "Routed → lapping cell" },
  { ts: "10:48:55", date: "2026-05-08", op: "Andreas Brunner",  sn: "GB-2401-003", flatness: 4.6, action: "HOLD",   note: "Within tol but >3 µm — held for re-grind decision" },
  { ts: "13:22:08", date: "2026-05-08", op: "Klaus Steinmetz",  sn: "GB-2401-004", flatness: 5.7, action: "REJECT", note: "Auto-NCR · supplier RTV" },
  { ts: "14:15:30", date: "2026-05-08", op: "Markus Hofer",     sn: "GB-2401-005", flatness: 2.1, action: "PASS",   note: "Routed → lapping cell" },
  { ts: "15:51:47", date: "2026-05-08", op: "Ralf Drechsler",   sn: "GB-2401-006", flatness: 3.3, action: "PASS",   note: "Routed → CMM inspection" },
];

function ScreenMittelstandReceiving() {
  const T = useMrTenant() || {};
  const woId = "WO-MTL-2401";
  const partNo = "MTL-220.10.01";
  const partRev = "Rev D";
  const stationName = "Receiving · Station 1";

  // Form state
  const [operator, setOperator]   = uSMR(MR_OPERATORS[0]);
  const [supplier, setSupplier]   = uSMR(MR_BLANK_SUPPLIERS[0]);
  const [serial, setSerial]       = uSMR("GB-2401-007");
  const [cocHash, setCocHash]     = uSMR("");
  const [flatness, setFlatness]   = uSMR("2.8");      // µm reading from surface plate
  const [photoCaptured, setPhotoCaptured] = uSMR(false);
  const [decision, setDecision]   = uSMR(null);       // "PASS" | "HOLD" | "REJECT" | "NCR" | null
  const [eventEmitted, setEventEmitted] = uSMR(null); // ledger envelope or null
  const [log, setLog]             = uSMR(MR_INITIAL_LOG);

  // ECO-MS-0017 raises the granite flatness from ±5 µm (Rev C) to ±3 µm (Rev D).
  // Reject is set at >5 µm per the spec; >3 µm targets the new tightened band.
  const TARGET_UM   = 3.0;   // §6, ECO-MS-0017 spec after
  const REJECT_UM   = 5.0;   // §8, station 1 reject threshold

  const flatnessNum = Number(flatness);
  const flatnessValid = !Number.isNaN(flatnessNum) && flatness !== "";
  const overReject  = flatnessValid && flatnessNum > REJECT_UM;
  const overTarget  = flatnessValid && flatnessNum > TARGET_UM && !overReject;
  const cocValid    = cocHash.trim().length >= 6;

  // Reset on tenant flip
  uEMR(() => {
    function onTenant() {
      setOperator(MR_OPERATORS[0]);
      setSupplier(MR_BLANK_SUPPLIERS[0]);
      setSerial("GB-2401-007");
      setCocHash("");
      setFlatness("2.8");
      setPhotoCaptured(false);
      setDecision(null);
      setEventEmitted(null);
      setLog(MR_INITIAL_LOG);
    }
    if (typeof window !== "undefined") {
      window.addEventListener("forge:tenant-change", onTenant);
      return () => window.removeEventListener("forge:tenant-change", onTenant);
    }
  }, []);

  // Auto-NCR when the probe reading busts the reject threshold, on PASS attempt.
  function decide(action) {
    let resolved = action;
    if (action === "PASS" && overReject) {
      resolved = "NCR"; // auto-promote to NCR
    }

    const env = _mr_emitReceipt("RECEIVING_LOGGED", {
      wo: woId,
      part: partNo,
      rev: partRev,
      sn: serial,
      supplier,
      operator,
      coc_hash: cocHash || _mr_synthHash(serial + supplier),
      flatness_um: flatnessNum,
      target_um: TARGET_UM,
      reject_um: REJECT_UM,
      photo_captured: photoCaptured,
      decision: resolved,
    });

    setDecision(resolved);
    setEventEmitted(env);

    setLog(prev => [{
      ts: _mr_now(),
      date: _mr_today(),
      op: operator,
      sn: serial,
      flatness: flatnessNum,
      action: resolved,
      note: resolved === "PASS"   ? "Routed → CMM inspection" :
            resolved === "HOLD"   ? "Held for engineering review" :
            resolved === "REJECT" ? "Returned to supplier · RTV" :
            resolved === "NCR"    ? "Auto-NCR · CAPA opened" : "—",
    }, ...prev].slice(0, 12));
  }

  function captureCoc() {
    setCocHash(_mr_synthHash(serial + supplier + _mr_now()));
  }

  return (
    <div style={{
      display: "flex", flexDirection: "column",
      height: "100%", minHeight: 0,
      background: _MS.bg0,
      color: _MS.ink,
    }}>

      {/* Station header — operator-grade */}
      <div style={{
        padding: "12px 18px",
        background: _MS.bg2,
        borderBottom: "1px solid " + _MS.line,
        display: "flex", alignItems: "center", gap: 14,
      }}>
        {_mr_avatar(operator, 36)}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, color: _MS.ink, display: "flex", alignItems: "center", gap: 10 }}>
            <b>{stationName}</b>
            <span style={{ color: _MS.ink4 }}>·</span>
            <span className="mono" style={{ color: _MS.ink2, fontSize: 12 }}>{partNo} {partRev}</span>
            <span style={{ color: _MS.ink4 }}>·</span>
            <span className="mono" style={{ color: _MS.ink2, fontSize: 12 }}>{woId}</span>
          </div>
          <div className="mono" style={{ fontSize: 12, color: _MS.ink3, marginTop: 3 }}>
            Mittelstand-pilot Werkzeugbau · Stuttgart · Shift A · {_mr_now()}
          </div>
        </div>
        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          {_msPill({ tone: "warn", children: "ECO-MS-0017 active" })}
          {_msPill({ tone: "", children: "IATF 16949 · PPAP L3" })}
        </div>
      </div>

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

        {/* ─── Left: capture form ──────────────────────────────────── */}
        <div style={{
          display: "flex", flexDirection: "column", minHeight: 0,
          borderRight: "1px solid " + _MS.line,
          overflow: "auto",
        }}>

          {/* Operator + supplier row */}
          <div style={{ padding: 16, borderBottom: "1px solid " + _MS.lineS, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div>
              <div className="label" style={{ marginBottom: 6, color: _MS.ink3 }}>OPERATOR</div>
              <select id="ms-trav-receiving-f1" name="ms-trav-receiving-f1"
                value={operator}
                onChange={e => setOperator(e.target.value)}
                style={_MR_SELECT_STYLE}>
                {MR_OPERATORS.map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
            <div>
              <div className="label" style={{ marginBottom: 6, color: _MS.ink3 }}>FOUNDRY · SUPPLIER</div>
              <select id="ms-trav-receiving-f2" name="ms-trav-receiving-f2"
                value={supplier}
                onChange={e => setSupplier(e.target.value)}
                style={_MR_SELECT_STYLE}>
                {MR_BLANK_SUPPLIERS.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </div>
          </div>

          {/* Serial + photo capture */}
          <div style={{ padding: 16, borderBottom: "1px solid " + _MS.lineS, display: "grid", gridTemplateColumns: "1fr 220px", gap: 14, alignItems: "end" }}>
            <div>
              <div className="label" style={{ marginBottom: 6, color: _MS.ink3 }}>BLANK SERIAL</div>
              <input id="ms-trav-receiving-f3" name="ms-trav-receiving-f3"
                value={serial}
                onChange={e => setSerial(e.target.value)}
                placeholder="GB-2401-007"
                style={_MR_SERIAL_INPUT_STYLE} />
            </div>
            <div>
              <div className="label" style={{ marginBottom: 6, color: _MS.ink3 }}>FOUNDRY PHOTO</div>
              <button
                onClick={() => setPhotoCaptured(true)}
                style={_mrPhotoBtnStyle(photoCaptured)}>
                {photoCaptured ? "✓ photo captured · 2.4 MB" : "📷 capture blank photo"}
              </button>
            </div>
          </div>

          {/* COC hash */}
          <div style={{ padding: 16, borderBottom: "1px solid " + _MS.lineS }}>
            <div className="label" style={{ marginBottom: 6, color: _MS.ink3 }}>
              CERTIFICATE OF CONFORMITY · HASH
              <span style={{ marginLeft: 6, color: _MS.ink3, fontWeight: 400 }}>(SHA-256, supplier-stamped)</span>
            </div>
            <div style={{ display: "flex", gap: 8 }}>
              <input id="ms-trav-receiving-f4" name="ms-trav-receiving-f4"
                value={cocHash}
                onChange={e => setCocHash(e.target.value)}
                placeholder="paste 64-char hex stamp from supplier COC PDF…"
                style={_mrCocInputStyle(cocValid)} />
              <button
                onClick={captureCoc}
                style={_MR_AUTO_BTN_STYLE}>auto-derive</button>
            </div>
            {cocValid && (
              <div className="mono" style={{ marginTop: 6, fontSize: 12, color: _MS.accent }}>
                ✓ stamp valid · ledger envelope will carry hash
              </div>
            )}
          </div>

          {/* Surface-plate flatness probe — primary measurement */}
          <div style={{ padding: 16, borderBottom: "1px solid " + _MS.lineS, background: _MS.bg1 }}>
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 10 }}>
              <div className="label" style={{ color: _MS.ink3 }}>SURFACE-PLATE FLATNESS PROBE</div>
              <div className="mono" style={{ fontSize: 12, color: _MS.ink3 }}>
                Mahr MarSurf · target ±{TARGET_UM.toFixed(1)} µm · reject &gt;{REJECT_UM.toFixed(1)} µm
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{ flex: 1 }}>
                <input id="ms-trav-receiving-f5" name="ms-trav-receiving-f5"
                  type="number"
                  step="0.1"
                  min="0"
                  value={flatness}
                  onChange={e => setFlatness(e.target.value)}
                  style={_mrFlatInputStyle(overReject, overTarget)} />
              </div>
              <div className="mono" style={{ fontSize: 22, color: _MS.ink3 }}>µm</div>
              <div style={{ minWidth: 110 }}>
                {overReject && _msPill({ tone: "err", children: "AUTO-NCR" })}
                {overTarget && _msPill({ tone: "warn", children: "ABOVE TARGET" })}
                {!overReject && !overTarget && flatnessValid && _msPill({ tone: "ok", children: "WITHIN TOL" })}
              </div>
            </div>

            {/* Visual scale — clear operator-grade range bar */}
            <div style={{ marginTop: 14, padding: "10px 12px", background: _MS.bg0, border: "1px dashed " + _MS.line, borderRadius: 3 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: _MS.ink3, marginBottom: 4 }} className="mono">
                <span>0 µm</span><span>{TARGET_UM.toFixed(1)} µm target</span><span>{REJECT_UM.toFixed(1)} µm reject</span><span>10 µm</span>
              </div>
              <div style={{ position: "relative", height: 10, background: "linear-gradient(90deg, color-mix(in oklch, " + _MS.accent + " 18%, transparent) 0%, color-mix(in oklch, " + _MS.warn + " 18%, transparent) 30%, color-mix(in oklch, " + _MS.bad + " 30%, transparent) 50%, color-mix(in oklch, " + _MS.bad + " 60%, transparent) 100%)", borderRadius: 5, border: "1px solid " + _MS.lineS }}>
                {flatnessValid && (
                  <div style={_mrFlatMarkerStyle(flatnessNum, overReject, overTarget)} />
                )}
              </div>
            </div>

            {overReject && (
              <div style={{
                marginTop: 12, padding: "10px 12px",
                background: "color-mix(in oklch, " + _MS.bad + " 10%, " + _MS.bg0 + ")",
                border: "1px solid " + _MS.bad, borderRadius: 3,
                fontSize: 12, color: _MS.ink2,
              }}>
                <b style={{ color: _MS.bad }}>Reading exceeds {REJECT_UM} µm reject threshold.</b>{" "}
                PASS will auto-promote to NCR with CAPA link, returning blank to supplier under RTV.
              </div>
            )}
          </div>

          {/* Decision row — operator-grade large buttons */}
          <div style={{ padding: 16, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
            <_MR_DecisionBtn label="PASS"   tone="ok"   active={decision === "PASS"}   onClick={() => decide("PASS")}   disabled={!cocValid || !photoCaptured} />
            <_MR_DecisionBtn label="HOLD"   tone="warn" active={decision === "HOLD"}   onClick={() => decide("HOLD")}   disabled={!cocValid} />
            <_MR_DecisionBtn label="REJECT" tone="err"  active={decision === "REJECT"} onClick={() => decide("REJECT")} disabled={!cocValid} />
            <_MR_DecisionBtn label="NCR"    tone="err"  active={decision === "NCR"}    onClick={() => decide("NCR")}    disabled={!cocValid} primary />
          </div>

          {/* Outcome panel — appears post-decision */}
          {decision && eventEmitted && (() => {
            const cMap = { PASS: _MS.accent, HOLD: _MS.warn, REJECT: _MS.bad, NCR: _MS.bad };
            const mMap = {
              PASS:   ["✓ Granite blank routed to CMM inspection.", <>SN <span className="mono">{serial}</span> moves to Station 2.</>],
              HOLD:   ["⏸ Blank held for engineering review.", "R. Vogt notified · re-grind decision pending."],
              REJECT: ["✗ Blank rejected · returned to supplier under RTV.", "Supplier on-time % to be debited."],
              NCR:    ["⚠ NCR opened · CAPA chain initiated.", "S. Klein (Quality Lead) routed · IATF 16949 §10.2 deviation logged."],
            };
            const c = cMap[decision]; const [head, body] = mMap[decision];
            return (
              <div style={{ padding: 16, borderTop: "1px solid " + _MS.lineS, background: _MS.bg1 }}>
                <div style={{ marginBottom: 10, padding: "10px 14px", background: "color-mix(in oklch, " + c + " 12%, " + _MS.bg0 + ")", border: "1px solid " + c, borderRadius: 3, fontSize: 13, color: _MS.ink }}>
                  <b style={{ color: c }}>{head}</b> <span style={{ color: _MS.ink3 }}>{body}</span>
                </div>
                <div className="label" style={{ color: _MS.ink3, marginBottom: 6 }}>LEDGER ENVELOPE EMITTED</div>
                <pre className="mono" style={_MR_LEDGER_PRE_STYLE}>{JSON.stringify(eventEmitted, null, 2)}</pre>
              </div>
            );
          })()}
        </div>

        {/* ─── Right: WO context + supplier panel ─────────────────── */}
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0, overflow: "auto" }}>

          {/* WO context block */}
          <div style={{ padding: 16, borderBottom: "1px solid " + _MS.lineS }}>
            <div className="label" style={{ marginBottom: 8, color: _MS.ink3 }}>WORK ORDER CONTEXT</div>
            <_MR_KV k="WO ID"          v={woId}                        mono />
            <_MR_KV k="Customer"       v="MAHLE Industriebeteiligungen GmbH" />
            <_MR_KV k="Program"        v="MTL-220 · 5-axis bridge mill" />
            <_MR_KV k="Batch"          v="Batch 1 of 2 · 12 mills · FY split" />
            <_MR_KV k="Frame contract" v="24 units · annual call-off" />
            <_MR_KV k="Customer due"   v="2026-12-18 · ship-acceptance" mono />
            <_MR_KV k="FAI target"     v="2026-08-14"                   mono />
            <_MR_KV k="Std applicable" v="ISO 9001 · IATF 16949 · EN ISO 230-2" />
          </div>

          {/* Part / spec block — surface ECO-MS-0017 delta */}
          <div style={{ padding: 16, borderBottom: "1px solid " + _MS.lineS, background: _MS.bg1 }}>
            <div className="label" style={{ marginBottom: 8, color: _MS.ink3 }}>PART · {partNo}</div>
            <_MR_KV k="Description"    v="Granite-bed substructure · base block" />
            <_MR_KV k="Material"       v="Diabas granite · Bavarian quarry" />
            <_MR_KV k="Mass"           v="2,840 kg" mono />
            <_MR_KV k="Lead time"      v="75 d"     mono />
            <_MR_KV k="Cost (target)"  v={(window.forgeI18n && window.forgeI18n.formatMoneyMinor("4800000", "EUR")) || "€48,000"}  mono />
            <div style={{ marginTop: 10, padding: "8px 10px", background: "color-mix(in oklch, " + _MS.warn + " 10%, " + _MS.bg0 + ")", border: "1px solid " + _MS.warn, borderRadius: 3, fontSize: 12, color: _MS.ink2 }}>
              <b style={{ color: _MS.warn }}>ECO-MS-0017</b> · flatness tightened
              <span className="mono" style={{ color: _MS.ink2 }}> ±5 µm → ±3 µm</span>.
              Two-pass lap with re-grind between rough &amp; finish. Cost delta
              <span className="mono"> +{(window.forgeI18n && window.forgeI18n.formatMoneyMinor("82000", "EUR")) || "€820"}/unit</span>.
            </div>
          </div>

          {/* Supplier panel */}
          <div style={{ padding: 16, borderBottom: "1px solid " + _MS.lineS }}>
            <div className="label" style={{ marginBottom: 8, color: _MS.ink3 }}>SUPPLIER · {supplier.split(" (")[0]}</div>
            <_MR_KV k="On-time % (12mo)"  v="94.2 %"   mono />
            <_MR_KV k="NCR rate"          v="1.7 %"    mono />
            <_MR_KV k="Last audit"        v={(window.forgeI18n && window.forgeI18n.formatDate("2026-02-11")) || "2026-02-11"} mono />
            <_MR_KV k="Approval status"   v="QSL approved · IATF aligned" />
            <_MR_KV k="Last 6 lots"       v={
              <span className="mono" style={{ color: _MS.ink2 }}>
                <span style={{ color: _MS.accent }}>●</span>
                <span style={{ color: _MS.accent }}>●</span>
                <span style={{ color: _MS.warn }}>●</span>
                <span style={{ color: _MS.bad }}>●</span>
                <span style={{ color: _MS.accent }}>●</span>
                <span style={{ color: _MS.accent }}>●</span>
              </span>
            } />
          </div>

          {/* Quick actions */}
          <div style={{ padding: 16, display: "flex", gap: 8, flexWrap: "wrap" }}>
            {_msBtn({ size: "sm", icon: "FileText",  children: "open COC PDF",         onClick: () => {} })}
            {_msBtn({ size: "sm", icon: "Camera",    children: "rephoto blank",        onClick: () => setPhotoCaptured(false) })}
            {_msBtn({ size: "sm", icon: "AlertTriangle", children: "open NCR form",    onClick: () => decide("NCR") })}
            {_msBtn({ size: "sm", icon: "ArrowRight", children: "next station",        onClick: () => { if (typeof navigate === "function") navigate("/traveler/machine-shop"); } })}
          </div>
        </div>
      </div>

      {/* ─── Bottom: chronological event log ─────────────────────── */}
      <div style={{
        borderTop: "1px solid " + _MS.line,
        background: _MS.bg2,
        maxHeight: 220,
        overflow: "auto",
        flexShrink: 0,
      }}>
        <div style={_MR_LOG_HEADER_STYLE}>
          <div>Time</div>
          <div>Date</div>
          <div>Operator</div>
          <div>Serial</div>
          <div>Flatness</div>
          <div>Action</div>
          <div>Note</div>
        </div>
        {log.map((row, i) => {
          const tone = row.action === "PASS"   ? _MS.accent
                    : row.action === "HOLD"   ? _MS.warn
                    : row.action === "REJECT" ? _MS.bad
                    : row.action === "NCR"    ? _MS.bad : _MS.ink3;
          return (
            <div key={row.sn + "·" + row.ts} style={_mrLogRowStyle(i === 0 && eventEmitted)}>
              <div className="mono" style={{ color: _MS.ink3 }}>{row.ts}</div>
              <div className="mono" style={{ color: _MS.ink3 }}>{row.date}</div>
              <div style={{ color: _MS.ink2 }}>{row.op}</div>
              <div className="mono" style={{ color: _MS.ink2 }}>{row.sn}</div>
              <div className="mono tnum" style={{ color: row.flatness > REJECT_UM ? _MS.bad : row.flatness > TARGET_UM ? _MS.warn : _MS.ink2 }}>
                {Number(row.flatness).toFixed(1)} µm
              </div>
              <div className="mono" style={{ color: tone, fontWeight: 600, fontSize: 12, letterSpacing: "0.04em" }}>
                {row.action}
              </div>
              <div style={{ color: _MS.ink3, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{row.note}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────
   Sub-atoms · scoped to this screen
   ──────────────────────────────────────────────────────────────────── */

function _MR_DecisionBtn({ label, tone, active, onClick, disabled, primary }) {
  const colorMap = {
    ok:   _MS.accent,
    warn: _MS.warn,
    err:  _MS.bad,
  };
  const c = colorMap[tone] || _MS.ink3;
  const bg     = active ? "color-mix(in oklch, " + c + " 18%, " + _MS.bg0 + ")" : _MS.bg0;
  const border = (active || primary) ? c : _MS.line;
  const fg     = active ? c : _MS.ink2;
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      style={_mrDecisionBtnStyle(disabled, bg, fg, border)}>
      {label}
    </button>
  );
}

function _MR_KV({ k, v, mono }) {
  return (
    <div style={{
      display: "flex", justifyContent: "space-between", alignItems: "baseline",
      padding: "5px 0",
      borderBottom: "1px dashed " + _MS.lineS,
      fontSize: 12,
    }}>
      <span style={{ color: _MS.ink3, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.05em" }}>{k}</span>
      <span className={mono ? "mono tnum" : ""} style={{ color: _MS.ink2, textAlign: "right", maxWidth: "65%" }}>{v}</span>
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────────
   Expose component on window (for cross-screen routing) and register
   the route. Prefer registerMittelstandRoute when shipped (agent #3),
   fall back to registerPumpRoute so the path resolves today.
   ──────────────────────────────────────────────────────────────────── */

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

(function _registerReceivingRoute() {
  const route = {
    path:     "/traveler/receiving",
    mode:     "traveler",
    title:    "Receiving · Granite blank QC",
    tenant:   "mittelstand",
    renderer: function() { return React.createElement(ScreenMittelstandReceiving); },
  };
  if (typeof registerMittelstandRoute === "function") {
    registerMittelstandRoute(route);
  } else if (typeof window !== "undefined" && typeof window.registerMittelstandRoute === "function") {
    window.registerMittelstandRoute(route);
  } else if (typeof registerPumpRoute === "function") {
    // Fallback so the screen is reachable before agent #3 lands the registry.
    registerPumpRoute(route);
  }
})();
})();
