(function(){
/* FORGE — Mittelstand tenant cockpit (Wave A1 / Agent #9).
   Single screen: ScreenMittelstandDashboard. Mounted at /forge/dashboard
   when active tenant id is "mittelstand"; the registry-router (Agent #3)
   conditionally swaps it in over the generic ScreenDashboard.

   Data source:  window.MITTELSTAND_TENANT (fixture-master, Agent #1)
   Style atoms:  MSCard / MSPill / MSBtn (cross-cutting, Agent #8) — the
                 file degrades gracefully to local fall-back atoms when
                 the cross-cutting layer has not yet loaded, so this
                 dashboard renders against the spec in isolation.

   Spec anchors: demo/tenant-spec/mittelstand.md §4 (KPIs), §5 (lifecycle),
                 §6 (hero ECO), §10 (palette).

   Style discipline:
     - Cool gray palette only (--mittel-* CSS vars or hex fall-backs).
     - All money in € · all tolerance in µm · all lead-time in d.
     - Mono everywhere a part number, ECO id, traveler id, or unit appears.
     - No emoji. No marketing copy. Restrained.
*/

const { useState: uSMD, useEffect: uEMD, useMemo: uMMD } = React;

// ──────────────────────────────────────────────────────────────────────
// Style atoms — match cross-cutting.jsx §10 block, with hex fall-back.
// Resolved at runtime via CSS custom properties; the values below are the
// inline-style fall-backs used when --mittel-* is not yet on :root.
// ──────────────────────────────────────────────────────────────────────
const MD_BG       = "var(--mittel-bg, oklch(0.97 0.003 250))";
const MD_BG_2     = "var(--mittel-bg-2, oklch(0.92 0.004 250))";
const MD_BG_3     = "var(--mittel-bg-3, oklch(0.95 0.003 250))";
const MD_INK      = "var(--mittel-ink, oklch(0.18 0.01 250))";
const MD_INK_2    = "var(--mittel-ink-2, oklch(0.32 0.01 250))";
const MD_INK_3    = "var(--mittel-ink-3, oklch(0.48 0.01 250))";
const MD_INK_4    = "var(--mittel-ink-4, oklch(0.62 0.005 250))";
const MD_LINE     = "var(--mittel-line, oklch(0.82 0.005 250))";
const MD_LINE_SOFT= "var(--mittel-line-soft, oklch(0.88 0.004 250))";
const MD_ACCENT   = "var(--mittel-accent, oklch(0.55 0.02 250))";
const MD_WARN     = "var(--mittel-accent-warn, oklch(0.62 0.13 60))";
const MD_BAD      = "var(--mittel-accent-bad, oklch(0.55 0.18 25))";
const MD_FONT_UI  = "var(--font-ui)";
const MD_FONT_MONO= "var(--font-mono)";
const MD_FONT_SERIF= "var(--font-serif)";

// ──────────────────────────────────────────────────────────────────────
// Local fall-back atoms — rendered only when MSCard/MSPill/MSBtn (from
// mittelstand/cross-cutting.jsx) have not yet attached to window.
// ──────────────────────────────────────────────────────────────────────
function MDCardLocal(props) {
  const pad = props.pad == null ? 12 : props.pad;
  return React.createElement("div", {
    style: Object.assign({
      background: MD_BG,
      border: "1px solid " + MD_LINE_SOFT,
      borderRadius: 4,
      padding: pad,
      minWidth: 0,
    }, props.style || {}),
  }, props.children);
}

function MDPillLocal(props) {
  const tone = props.tone || "info";
  let bg = MD_BG_3, fg = MD_INK_2, border = MD_LINE_SOFT;
  if (tone === "warn") { bg = "color-mix(in oklch, " + MD_WARN + " 18%, " + MD_BG + ")"; fg = MD_WARN; border = MD_WARN; }
  if (tone === "bad" || tone === "err") { bg = "color-mix(in oklch, " + MD_BAD + " 14%, " + MD_BG + ")"; fg = MD_BAD; border = MD_BAD; }
  if (tone === "ok") { bg = MD_BG_3; fg = MD_INK_2; border = MD_LINE; }
  return React.createElement("span", {
    style: {
      display: "inline-flex",
      alignItems: "center",
      gap: 4,
      height: 18,
      padding: "0 7px",
      borderRadius: 2,
      border: "1px solid " + border,
      background: bg,
      color: fg,
      fontFamily: MD_FONT_MONO,
      fontSize: 12,
      letterSpacing: "0.04em",
      textTransform: "uppercase",
    },
  }, props.children);
}

function MDBtnLocal(props) {
  const variant = props.variant || "ghost";
  const isPrimary = variant === "primary";
  return React.createElement("button", {
    onClick: props.onClick,
    title: props.title,
    style: {
      display: "inline-flex",
      alignItems: "center",
      gap: 6,
      height: 26,
      padding: "0 10px",
      border: "1px solid " + (isPrimary ? MD_INK : MD_LINE),
      background: isPrimary ? MD_INK : MD_BG,
      color: isPrimary ? MD_BG : MD_INK_2,
      borderRadius: 3,
      fontFamily: MD_FONT_UI,
      fontSize: 12,
      letterSpacing: "0.02em",
      cursor: "pointer",
    },
  }, props.children);
}

// Resolve atom: prefer cross-cutting MSCard/MSPill/MSBtn at render-time so
// that script-load ordering is not load-bearing.
function MDCard(props) {
  const ext = (typeof window !== "undefined") ? window.MSCard : null;
  if (typeof ext === "function") return React.createElement(ext, props);
  return React.createElement(MDCardLocal, props);
}
function MDPill(props) {
  const ext = (typeof window !== "undefined") ? window.MSPill : null;
  if (typeof ext === "function") return React.createElement(ext, props);
  return React.createElement(MDPillLocal, props);
}
function MDBtn(props) {
  const ext = (typeof window !== "undefined") ? window.MSBtn : null;
  if (typeof ext === "function") return React.createElement(ext, props);
  return React.createElement(MDBtnLocal, props);
}

// ──────────────────────────────────────────────────────────────────────
// Spec defaults — used when window.MITTELSTAND_TENANT has not yet attached.
// These mirror demo/tenant-spec/mittelstand.md exactly so the dashboard is
// readable in isolation and agent-handoff is survivable.
// ──────────────────────────────────────────────────────────────────────
// Locale-aware money formatter resolved at render time. Falls back to the
// pre-formatted "€2.4M" shorthand if forgeI18n isn't yet on window (script
// order race on first paint). minor amounts here are computed in cents
// (2_400_000 EUR × 100 = 240_000_000 cents = €2,400,000.00).
function mdMoney(minor, currency, fallback) {
  var i18n = (typeof window !== "undefined") ? window.forgeI18n : null;
  if (i18n && typeof i18n.formatMoneyMinor === "function") {
    var out = i18n.formatMoneyMinor(minor, currency || "EUR");
    if (out) return out;
  }
  return fallback;
}

function mdSpecKpis() {
  return [
    { k: "Open RFQs",       v: mdMoney("240000000", "EUR", "€2.4M"), d: "+1 (MAHLE batch-2)",  trend: "up"   },
    { k: "WOs scheduled",   v: "8",      d: "24 mills",            trend: "up"   },
    { k: "Open ECOs",       v: "4",      d: "1 critical (MS-0017)",trend: "up", crit: true },
    { k: "Line readiness",  v: "91%",    d: "−3 pt (granite cell)",trend: "down" },
    { k: "Alerts (24h)",    v: "5",      d: "2 supplier · 3 quality", trend: "up" },
    { k: "FAI pass rate",   v: "94%",    d: "+2 pt YTD",           trend: "up"   },
  ];
}

const MD_SPEC_LIFECYCLE = [
  { ix: 1, ym: "2025-09", title: "Frame contract signed",        sub: "MAHLE · 24 mills · two batches",            state: "done" },
  { ix: 2, ym: "2025-11", title: "Engineering Rev D freeze",     sub: "ECO-MS-0017 raised against 10.01 / 10.02",  state: "done" },
  { ix: 3, ym: "2026-01", title: "Long-lead release",            sub: "GMN spindle 180 d · TNC 640 45 d",          state: "done" },
  { ix: 4, ym: "2026-03", title: "Granite-cell rework",          sub: "Re-grind operation qualified on lap stones",state: "active" },
  { ix: 5, ym: "2026-06", title: "First article assembly start", sub: "Unit 1 of 24 · spindle alignment Faro",     state: "next"   },
  { ix: 6, ym: "2026-08", title: "FAI pass + PPAP Level 3",      sub: "Target 2026-08-14 · TRV-MS-0244",           state: "next"   },
];
// Spec §5 calls out 7 phases; the cockpit visualises the 6 active build-
// path phases. The 2026-12 batch-1 ship-acceptance is rendered separately
// as the program window header.

// Hero ECO cost block — 820 EUR/unit × 24 units = 19,680 EUR batch total.
// We pre-format with forgeI18n where it has resolved by render-time; the
// "+" sign is preserved for positive deltas (cost-up notation matches the
// rest of the dashboard).
function mdSpecHeroEco() {
  function moneyDelta(minorAbs, currency, fallback) {
    var formatted = mdMoney(minorAbs, currency, null);
    if (!formatted) return fallback;
    return "+" + formatted;
  }
  return {
    id:        "ECO-MS-0017",
    title:     "Granite-bed flatness · Rev C → Rev D",
    status:    "Awaiting Quality (CMM gauge R&R)",
    parts:     ["MTL-220.10.01 · granite base block", "MTL-220.10.02 · granite cross-beam"],
    before:    "±5 µm · single lap pass",
    after:     "±3 µm · two-pass lap with re-grind",
    cost:      moneyDelta("82000", "EUR", "+€820") + " / unit",
    costBatch: moneyDelta("1968000", "EUR", "+€19,680") + " over the 24-unit batch",
    lead:      "+11 d granite path",
    leadNet:   "0 d net program slip · spindle remains critical at 180 d",
    approvals: [
      { who: "R. Vogt",    role: "Engineering",   state: "ok",   when: "signed" },
      { who: "D. Becker",  role: "Manufacturing", state: "ok",   when: "signed" },
      { who: "S. Klein",   role: "Quality",       state: "warn", when: "awaiting CMM gauge R&R" },
      { who: "Sign-off",   role: "Final",         state: "info", when: "blocked on Quality" },
    ],
    compliance:"IATF 16949 §8.5.6 · ISO 9001 §8.3.6 · PPAP Level 3 re-submission",
    rootCause: "3 returns, vibration > 0.8 mm/s RMS at 12k rpm — granite cross-beam flatness drift on S/N 0089–0094",
  };
}
const MD_SPEC_HERO_ECO = mdSpecHeroEco();

const MD_SPEC_ALERTS = [
  { sev: "bad",  src: "Quality",  title: "3 Rev C field returns",
    body: "S/N 0089 · 0091 · 0094 · vibration > 0.8 mm/s RMS at 12k rpm contouring",
    href: "/forge/field-issues" },
  { sev: "warn", src: "Supplier", title: "GMN spindle long lead",
    body: "HSK-A63 24k rpm · 180 d firm · single source · no qualified dual",
    href: "/build/connectors" },
  { sev: "warn", src: "Mfg",      title: "Granite cell shortage",
    body: "Lap stone reorder · 2 pcs short for re-grind operation · ETA 14 d",
    href: "/line/queue" },
];

const MD_SPEC_HERO_BAND = {
  programId: "MTL-220 Rev D",
  customer:  "MAHLE Industriebeteiligungen GmbH",
  scope:     "24-mill frame contract · two batches FY split",
  window:    "2025-09 → 2026-12",
};

// ──────────────────────────────────────────────────────────────────────
// Resolve tenant from window — fall through stub from active-tenant.jsx.
// ──────────────────────────────────────────────────────────────────────
function mdResolveTenant() {
  if (typeof window === "undefined") return null;
  if (window.MITTELSTAND_TENANT) return window.MITTELSTAND_TENANT;
  if (typeof window.getActiveTenant === "function") {
    const t = window.getActiveTenant();
    if (t && t.tenant && t.tenant.id === "mittelstand") return t;
  }
  return null;
}

function mdKpis(tenant) {
  // Discriminate by content, not just shape — the legacy stub in
  // active-tenant.jsx:22-29 also has 6 entries but the wrong six KPIs
  // (Active SKUs / Audits due / On-time). Only adopt the tenant block
  // when its first key matches the §4 spec ("Open RFQs"); otherwise
  // surface the spec defaults so the cockpit reads correctly while
  // fixture-master (#1) and tenant-config (#2) catch up.
  if (tenant && Array.isArray(tenant.kpis) && tenant.kpis.length === 6) {
    const first = tenant.kpis[0];
    if (first && typeof first.k === "string" && first.k.toLowerCase().indexOf("rfq") >= 0) {
      return tenant.kpis;
    }
  }
  // Re-evaluate at call time so forgeI18n.formatMoneyMinor picks up the
  // tenant locale once /api/config has resolved (post-mount, not module load).
  return mdSpecKpis();
}
function mdLifecycle(tenant) {
  if (tenant && Array.isArray(tenant.lifecycle) && tenant.lifecycle.length) return tenant.lifecycle;
  return MD_SPEC_LIFECYCLE;
}
function mdHeroEco(tenant) {
  // Re-evaluate the spec hero at call time so the EUR cost lines pick up
  // locale-aware formatting once forgeI18n + tenant config have hydrated.
  const spec = mdSpecHeroEco();
  if (tenant && tenant.eco && Array.isArray(tenant.eco)) {
    const hero = tenant.eco.find(function(e) { return e.id === "ECO-MS-0017"; });
    if (hero) return Object.assign({}, spec, hero);
  }
  return spec;
}
function mdAlerts(tenant) {
  if (tenant && Array.isArray(tenant.alerts) && tenant.alerts.length) return tenant.alerts;
  return MD_SPEC_ALERTS;
}
function mdHeroBand(tenant) {
  if (tenant && tenant.program) {
    const p = tenant.program;
    return {
      programId: (p.code || "MTL-220") + " Rev " + (p.revision || "D"),
      customer:  p.customer || MD_SPEC_HERO_BAND.customer,
      scope:     p.scope    || MD_SPEC_HERO_BAND.scope,
      window:    p.window   || MD_SPEC_HERO_BAND.window,
    };
  }
  return MD_SPEC_HERO_BAND;
}

function mdNav(path) {
  if (typeof window !== "undefined" && typeof window.navigate === "function") window.navigate(path);
  else if (typeof window !== "undefined") window.location.hash = path;
}

// ──────────────────────────────────────────────────────────────────────
// Sub-components
// ──────────────────────────────────────────────────────────────────────

function MDLabel(props) {
  return React.createElement("div", {
    style: {
      fontFamily: MD_FONT_MONO,
      fontSize: 12,
      letterSpacing: "0.08em",
      textTransform: "uppercase",
      color: MD_INK_3,
    },
  }, props.children);
}

function MDMono(props) {
  return React.createElement("span", {
    style: Object.assign({
      fontFamily: MD_FONT_MONO,
      fontVariantNumeric: "tabular-nums",
      color: MD_INK_2,
    }, props.style || {}),
  }, props.children);
}

function MDHeroBand(props) {
  const band = props.band;
  // Canonical compound string per the task brief (keep verbatim — smoke
  // tests and downstream agents may grep for it):
  // "MTL-220 Rev D · MAHLE 24-mill batch · 2025-09 → 2026-12"
  const canonical = band.programId + " · MAHLE 24-mill batch · " + band.window;
  return React.createElement("div", {
    style: {
      gridColumn: "1 / -1",
      padding: "14px 16px",
      background: MD_BG,
      border: "1px solid " + MD_LINE,
      borderRadius: 4,
      display: "grid",
      gridTemplateColumns: "minmax(0, 1.2fr) auto auto auto",
      gap: 24,
      alignItems: "center",
    },
  },
    React.createElement("div", null,
      React.createElement(MDLabel, null, "Active program"),
      React.createElement("div", {
        style: { fontFamily: MD_FONT_MONO, fontSize: 17, fontWeight: 600, color: MD_INK, marginTop: 4, letterSpacing: "-0.01em" },
        title: canonical,
        "data-canonical": canonical,
      }, canonical),
      React.createElement("div", {
        style: { fontFamily: MD_FONT_UI, fontSize: 12, color: MD_INK_3, marginTop: 4 },
      }, band.customer + " · " + band.scope),
    ),
    React.createElement("div", null,
      React.createElement(MDLabel, null, "Window"),
      React.createElement(MDMono, { style: { fontSize: 13, color: MD_INK_2, display: "block", marginTop: 4 } }, band.window),
    ),
    React.createElement("div", null,
      React.createElement(MDLabel, null, "Site"),
      React.createElement(MDMono, { style: { fontSize: 13, color: MD_INK_2, display: "block", marginTop: 4 } }, "Stuttgart, DE"),
    ),
    React.createElement("div", null,
      React.createElement(MDLabel, null, "ERP"),
      React.createElement(MDMono, { style: { fontSize: 13, color: MD_INK_2, display: "block", marginTop: 4 } }, "SAP B1 + proALPHA"),
    ),
  );
}

function MDKpiTile(props) {
  const k = props.kpi;
  const trendChar = k.trend === "up" ? "▲" : k.trend === "down" ? "▼" : "·";
  const trendColor = k.crit ? MD_BAD : (k.trend === "up" ? MD_INK_3 : (k.trend === "down" ? MD_WARN : MD_INK_3));
  return React.createElement("div", {
    style: {
      padding: "11px 12px",
      background: MD_BG,
      border: "1px solid " + (k.crit ? MD_BAD : MD_LINE_SOFT),
      borderRadius: 4,
      minWidth: 0,
      display: "flex",
      flexDirection: "column",
      gap: 6,
    },
  },
    React.createElement(MDLabel, null, k.k),
    React.createElement("div", {
      style: {
        fontFamily: MD_FONT_MONO,
        fontVariantNumeric: "tabular-nums",
        fontSize: 22,
        color: k.crit ? MD_BAD : MD_INK,
        letterSpacing: "-0.01em",
      },
    }, k.v),
    React.createElement("div", {
      style: { display: "flex", alignItems: "center", gap: 6, fontFamily: MD_FONT_MONO, fontSize: 12, color: trendColor },
    },
      React.createElement("span", null, trendChar),
      React.createElement("span", { style: { color: MD_INK_3 } }, k.d),
    ),
  );
}

function MDStageRow(props) {
  const s = props.stage;
  const tone = s.state === "done" ? "ok" : (s.state === "active" ? "warn" : "info");
  const dotColor = s.state === "done" ? MD_INK_3 : (s.state === "active" ? MD_WARN : MD_LINE);
  return React.createElement("div", {
    style: {
      display: "grid",
      gridTemplateColumns: "22px 80px minmax(0, 1fr) auto",
      gap: 10,
      alignItems: "center",
      padding: "9px 10px",
      borderBottom: "1px solid " + MD_LINE_SOFT,
    },
  },
    React.createElement("div", {
      style: {
        width: 18, height: 18,
        display: "flex", alignItems: "center", justifyContent: "center",
        fontFamily: MD_FONT_MONO,
        fontSize: 12,
        color: MD_INK_3,
        border: "1px solid " + MD_LINE,
        borderRadius: 2,
        background: s.state === "active" ? "color-mix(in oklch, " + MD_WARN + " 18%, " + MD_BG + ")" : MD_BG_3,
      },
    }, String(s.ix).padStart(2, "0")),
    React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_3 } }, s.ym),
    React.createElement("div", { style: { minWidth: 0 } },
      React.createElement("div", {
        style: { fontFamily: MD_FONT_UI, fontSize: 13, color: MD_INK },
      }, s.title),
      React.createElement("div", {
        style: { fontFamily: MD_FONT_UI, fontSize: 12, color: MD_INK_3, marginTop: 2 },
      }, s.sub),
    ),
    React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 6 } },
      React.createElement("span", {
        style: { width: 6, height: 6, borderRadius: 6, background: dotColor, display: "inline-block" },
      }),
      React.createElement(MDPill, { tone: tone }, s.state),
    ),
  );
}

function MDApprovalRow(props) {
  const a = props.appr;
  const tone = a.state === "ok" ? "ok" : (a.state === "warn" ? "warn" : "info");
  const mark = a.state === "ok" ? "✓" : (a.state === "warn" ? "⚠" : "·");
  return React.createElement("div", {
    style: {
      display: "grid",
      gridTemplateColumns: "16px minmax(0, 1fr) auto",
      gap: 8,
      alignItems: "center",
      padding: "5px 0",
      borderBottom: "1px solid " + MD_LINE_SOFT,
    },
  },
    React.createElement("span", {
      style: { fontFamily: MD_FONT_MONO, fontSize: 12, color: a.state === "ok" ? MD_INK_3 : (a.state === "warn" ? MD_WARN : MD_INK_3) },
    }, mark),
    React.createElement("div", { style: { minWidth: 0 } },
      React.createElement("span", {
        style: { fontFamily: MD_FONT_UI, fontSize: 12, color: MD_INK },
      }, a.who),
      React.createElement("span", {
        style: { fontFamily: MD_FONT_UI, fontSize: 12, color: MD_INK_3, marginLeft: 6 },
      }, "· " + a.role),
    ),
    React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_3 } }, a.when),
  );
}

function MDHeroEcoCard(props) {
  const eco = props.eco;
  return React.createElement("div", {
    style: {
      background: MD_BG,
      border: "1px solid " + MD_INK_3,
      borderRadius: 4,
      padding: 14,
      display: "flex",
      flexDirection: "column",
      gap: 10,
      minWidth: 0,
    },
  },
    React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, justifyContent: "space-between" } },
      React.createElement(MDPill, { tone: "warn" }, "hero ECO"),
      React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_3 } }, eco.id),
    ),
    React.createElement("div", null,
      React.createElement("div", {
        style: { fontFamily: MD_FONT_UI, fontSize: 14, color: MD_INK, lineHeight: 1.25 },
      }, eco.title),
      React.createElement("div", {
        style: { fontFamily: MD_FONT_UI, fontSize: 12, color: MD_INK_3, marginTop: 4 },
      }, eco.status),
    ),
    React.createElement("div", null,
      React.createElement(MDLabel, null, "Parts touched"),
      eco.parts.map(function(p, i) {
        return React.createElement("div", {
          key: i,
          style: { fontFamily: MD_FONT_MONO, fontSize: 12, color: MD_INK_2, marginTop: 3 },
        }, p);
      }),
    ),
    React.createElement("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 } },
      React.createElement("div", null,
        React.createElement(MDLabel, null, "Before"),
        React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_2, display: "block", marginTop: 3 } }, eco.before),
      ),
      React.createElement("div", null,
        React.createElement(MDLabel, null, "After"),
        React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK, display: "block", marginTop: 3 } }, eco.after),
      ),
      React.createElement("div", null,
        React.createElement(MDLabel, null, "Cost Δ"),
        React.createElement(MDMono, { style: { fontSize: 12, color: MD_BAD, display: "block", marginTop: 3 } }, eco.cost),
        React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_3, display: "block", marginTop: 2 } }, eco.costBatch),
      ),
      React.createElement("div", null,
        React.createElement(MDLabel, null, "Lead-time Δ"),
        React.createElement(MDMono, { style: { fontSize: 12, color: MD_WARN, display: "block", marginTop: 3 } }, eco.lead),
        React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_3, display: "block", marginTop: 2 } }, eco.leadNet),
      ),
    ),
    React.createElement("div", null,
      React.createElement(MDLabel, null, "Approvals"),
      React.createElement("div", { style: { marginTop: 4 } },
        eco.approvals.map(function(a, i) {
          return React.createElement(MDApprovalRow, { key: i, appr: a });
        }),
      ),
    ),
    React.createElement("div", null,
      React.createElement(MDLabel, null, "Compliance"),
      React.createElement("div", {
        style: { fontFamily: MD_FONT_MONO, fontSize: 12, color: MD_INK_3, marginTop: 4, lineHeight: 1.5 },
      }, eco.compliance),
    ),
    React.createElement("div", null,
      React.createElement(MDLabel, null, "Root cause"),
      React.createElement("div", {
        style: { fontFamily: MD_FONT_UI, fontSize: 12, color: MD_INK_3, marginTop: 4, lineHeight: 1.45 },
      }, eco.rootCause),
    ),
    React.createElement("div", { style: { display: "flex", gap: 6, marginTop: 4 } },
      React.createElement(MDBtn, {
        variant: "primary",
        onClick: function() { mdNav("/build/eco-mittelstand"); },
      }, "Open ECO"),
      React.createElement(MDBtn, {
        onClick: function() { mdNav("/auditor/ledger"); },
      }, "Linked ledger entries"),
    ),
  );
}

function MDAlertRow(props) {
  const a = props.alert;
  const tone = a.sev === "bad" ? "bad" : (a.sev === "warn" ? "warn" : "info");
  const stripeColor = a.sev === "bad" ? MD_BAD : (a.sev === "warn" ? MD_WARN : MD_LINE);
  return React.createElement("button", {
    onClick: function() { if (a.href) mdNav(a.href); },
    style: {
      width: "100%",
      textAlign: "left",
      padding: "10px 12px 10px 14px",
      background: MD_BG,
      border: "1px solid " + MD_LINE_SOFT,
      borderLeft: "3px solid " + stripeColor,
      borderRadius: 3,
      cursor: a.href ? "pointer" : "default",
      display: "flex",
      flexDirection: "column",
      gap: 5,
      minWidth: 0,
    },
  },
    React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, justifyContent: "space-between" } },
      React.createElement(MDPill, { tone: tone }, a.src),
      React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_3 } }, "24h"),
    ),
    React.createElement("div", {
      style: { fontFamily: MD_FONT_UI, fontSize: 12, color: MD_INK, lineHeight: 1.3 },
    }, a.title),
    React.createElement("div", {
      style: { fontFamily: MD_FONT_UI, fontSize: 12, color: MD_INK_3, lineHeight: 1.4 },
    }, a.body),
  );
}

// ──────────────────────────────────────────────────────────────────────
// Main screen
// ──────────────────────────────────────────────────────────────────────
function ScreenMittelstandDashboard() {
  const [tenant, setTenant] = uSMD(mdResolveTenant);

  // Re-resolve when the tenant changes (event from active-tenant.jsx).
  uEMD(function() {
    const onChange = function() { setTenant(mdResolveTenant()); };
    if (typeof window !== "undefined") {
      window.addEventListener("forge:tenant-change", onChange);
      // Also re-resolve once after mount in case the fixtures script
      // attached MITTELSTAND_TENANT after this component first rendered.
      const t = setTimeout(onChange, 0);
      return function() {
        window.removeEventListener("forge:tenant-change", onChange);
        clearTimeout(t);
      };
    }
    return undefined;
  }, []);

  const band      = uMMD(function() { return mdHeroBand(tenant); }, [tenant]);
  const kpis      = uMMD(function() { return mdKpis(tenant); }, [tenant]);
  const lifecycle = uMMD(function() { return mdLifecycle(tenant); }, [tenant]);
  const heroEco   = uMMD(function() { return mdHeroEco(tenant); }, [tenant]);
  const alerts    = uMMD(function() { return mdAlerts(tenant); }, [tenant]);

  return React.createElement("div", {
    style: {
      padding: 16,
      display: "grid",
      gridTemplateColumns: "minmax(0, 1.55fr) minmax(320px, 0.85fr) minmax(280px, 0.6fr)",
      gridTemplateRows: "auto auto 1fr auto",
      gap: 14,
      minHeight: 0,
      height: "100%",
      background: MD_BG_3,
      color: MD_INK,
      fontFamily: MD_FONT_UI,
    },
  },

    // Row 1 — full-width hero band
    React.createElement(MDHeroBand, { band: band }),

    // Row 2 — six KPI tiles spanning the left + middle columns;
    //         hero ECO card pinned top-right rolls into rows 2–3.
    React.createElement("div", {
      style: {
        gridColumn: "1 / 3",
        display: "grid",
        gridTemplateColumns: "repeat(6, minmax(0, 1fr))",
        gap: 10,
      },
    },
      kpis.map(function(k, i) {
        return React.createElement(MDKpiTile, { key: i, kpi: k });
      }),
    ),

    // Hero ECO card · pinned top-right · rolls into rows 2–3
    React.createElement("div", {
      style: { gridColumn: "3 / 4", gridRow: "2 / 4" },
    },
      React.createElement(MDHeroEcoCard, { eco: heroEco }),
    ),

    // Row 3 — left: live operating stack (lifecycle stages)
    //         middle: right rail (alerts)
    React.createElement("div", {
      style: {
        gridColumn: "1 / 2",
        gridRow: "3 / 4",
        background: MD_BG,
        border: "1px solid " + MD_LINE_SOFT,
        borderRadius: 4,
        display: "flex",
        flexDirection: "column",
        minHeight: 0,
        overflow: "hidden",
      },
    },
      React.createElement("div", {
        style: {
          padding: "10px 12px",
          borderBottom: "1px solid " + MD_LINE_SOFT,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        },
      },
        React.createElement(MDLabel, null, "Live operating stack · MTL-220 Rev D"),
        React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_3 } }, "6 phases"),
      ),
      React.createElement("div", { style: { flex: 1, overflow: "auto" } },
        lifecycle.map(function(s, i) {
          return React.createElement(MDStageRow, { key: i, stage: s });
        }),
      ),
    ),

    // Right rail · alerts (24h)
    React.createElement("div", {
      style: {
        gridColumn: "2 / 3",
        gridRow: "3 / 4",
        background: MD_BG,
        border: "1px solid " + MD_LINE_SOFT,
        borderRadius: 4,
        display: "flex",
        flexDirection: "column",
        minHeight: 0,
        overflow: "hidden",
      },
    },
      React.createElement("div", {
        style: {
          padding: "10px 12px",
          borderBottom: "1px solid " + MD_LINE_SOFT,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        },
      },
        React.createElement(MDLabel, null, "Alerts · last 24h"),
        React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_3 } }, String(alerts.length) + " open"),
      ),
      React.createElement("div", {
        style: { flex: 1, overflow: "auto", padding: 10, display: "flex", flexDirection: "column", gap: 8 },
      },
        alerts.map(function(a, i) {
          return React.createElement(MDAlertRow, { key: i, alert: a });
        }),
      ),
    ),

    // Wave 3C item 26 — live ActivityStream spanning full width.
    // SSE channel is tenant-aware (api.js routes /api/<tenant>/events/stream),
    // so this surfaces Mittelstand FAI / ECO transitions in real time.
    (function() {
      const AS = (typeof window !== "undefined") ? window.ActivityStream : null;
      if (!AS) return null;
      return React.createElement("div", {
        style: { gridColumn: "1 / -1", minHeight: 0 },
      }, React.createElement(AS, { title: "Activity · MTL-220 Rev D timeline" }));
    })(),

    // Row 4 — full-width action bar
    React.createElement("div", {
      style: {
        gridColumn: "1 / -1",
        background: MD_BG,
        border: "1px solid " + MD_LINE_SOFT,
        borderRadius: 4,
        padding: "10px 14px",
        display: "flex",
        alignItems: "center",
        gap: 10,
        flexWrap: "wrap",
      },
    },
      React.createElement(MDLabel, null, "Open lane"),
      React.createElement(MDBtn, {
        variant: "primary",
        onClick: function() { mdNav("/build/eco-mittelstand"); },
      }, "Open ECO"),
      React.createElement(MDBtn, {
        onClick: function() { mdNav("/build/routing"); },
      }, "Open routing"),
      React.createElement(MDBtn, {
        onClick: function() { mdNav("/traveler/report"); },
      }, "Open FAI"),
      React.createElement(MDBtn, {
        onClick: function() { mdNav("/auditor/ledger"); },
      }, "View ledger"),
      React.createElement("div", { style: { flex: 1 } }),
      React.createElement(MDMono, { style: { fontSize: 12, color: MD_INK_3 } },
        "All routes · /forge · /build · /plan · /line · /traveler · /auditor",
      ),
    ),
  );
}

// ──────────────────────────────────────────────────────────────────────
// Registration. Mirrors the pump convention (pump/registry-index.jsx is
// loaded before any pump act file in index.html so registerPumpRoute is
// always defined at the call site). Agent #3 (registry-router) owns the
// equivalent ordering for mittelstand: it ships
// client/mittelstand/registry-index.jsx and patches index.html to load
// it before this file. We expose the screen on window unconditionally so
// router.jsx's renderIfExists fall-back works even before the registry
// helper attaches.
// ──────────────────────────────────────────────────────────────────────
if (typeof window !== "undefined") {
  window.ScreenMittelstandDashboard = ScreenMittelstandDashboard;

  if (typeof window.registerMittelstandRoute === "function") {
    window.registerMittelstandRoute({
      path: "/forge/dashboard",
      mode: "forge",
      title: "Dashboard",
      renderer: function() { return React.createElement(ScreenMittelstandDashboard); },
    });
  } else if (typeof console !== "undefined" && console.warn) {
    // Loud fall-back: visible in dev console so #3's missing ordering
    // surfaces immediately rather than silently dropping the route.
    console.warn(
      "[mittelstand/dashboard] registerMittelstandRoute is not defined — " +
      "ensure mittelstand/registry-index.jsx loads before mittelstand/dashboard.jsx in index.html. " +
      "Falling back to renderIfExists('ScreenMittelstandDashboard') via router.jsx."
    );
  }
}
})();
