/* FORGE — cross-cutting affordances for the pump-CDMO demo.
   Single file. Babel-standalone in-browser pattern. NO ES imports / exports.

   Components:
     1. CommandPalette        — ⌘K palette (routes, parts, SKUs, suppliers, WOs, events)
     2. NotificationBell      — top-right ping with derived alerts
     3. ResetDemo             — floating reset button
     4. MODE_FCP_TEMPLATES    — global registry the WorkshopDrawer can read
   Plus: CrossCuttingMount    — composite mounting helper

   All globals are exposed at end-of-file. Style follows the deck-paper
   aesthetic from landing.jsx (oklch palette, mono accents, paper cards).
*/

const { useState: uSCC, useEffect: uECC, useMemo: uMCC, useRef: uRCC } = React;

// ──────────────────────────────────────────────────────────────────────
// Shared style atoms (kept inline to avoid coupling)
// ──────────────────────────────────────────────────────────────────────
const CC_PAPER_BG       = "oklch(0.985 0.004 85)";
const CC_PAPER_BG_2     = "oklch(0.93 0.005 85)";
const CC_PAPER_BG_3     = "oklch(0.965 0.005 85)";
const CC_PAPER_INK      = "oklch(0.16 0.01 85)";
const CC_PAPER_INK_2    = "oklch(0.30 0.01 85)";
const CC_PAPER_INK_3    = "oklch(0.46 0.01 85)";
const CC_PAPER_INK_4    = "oklch(0.60 0.01 85)";
const CC_PAPER_LINE     = "oklch(0.84 0.006 85)";
const CC_PAPER_LINE_SOFT= "oklch(0.90 0.005 85)";
const CC_ACCENT         = "var(--accent, oklch(0.55 0.18 250))";
const CC_FONT_UI        = "var(--font-ui)";
const CC_FONT_MONO      = "var(--font-mono)";

// Severity → tone
function ccSevTone(sev) {
  if (sev === "critical") return { fg: "#fff", bg: "oklch(0.55 0.18 25)",  label: "critical" };
  if (sev === "warn")     return { fg: "oklch(0.20 0.06 70)", bg: "oklch(0.85 0.10 75)",  label: "warn" };
  return                       { fg: CC_PAPER_INK_2, bg: CC_PAPER_BG_3, label: "info" };
}

// Mode → ink color (mirrors app-shell)
const CC_MODE_COLOR = {
  forge:    "oklch(0.55 0.18 250)",
  plan:     "oklch(0.55 0.16 290)",
  build:    "oklch(0.55 0.16 30)",
  line:     "oklch(0.55 0.16 150)",
  traveler: "oklch(0.55 0.16 350)",
  auditor:  "oklch(0.30 0.01 85)",
};

function CCModeBadge(props) {
  const c = CC_MODE_COLOR[props.mode] || CC_PAPER_INK_3;
  return React.createElement("span", {
    style: {
      display: "inline-flex",
      alignItems: "center",
      gap: 4,
      height: 16,
      padding: "0 6px",
      borderRadius: 3,
      fontFamily: CC_FONT_MONO,
      fontSize: 12,
      letterSpacing: "0.04em",
      color: "#fff",
      background: c,
    },
  }, props.mode);
}

// ──────────────────────────────────────────────────────────────────────
// 1. CommandPalette
// ──────────────────────────────────────────────────────────────────────

function ccScore(query, label) {
  if (!query) return 0;
  const q = String(query).toLowerCase();
  const l = String(label || "").toLowerCase();
  if (l.length === 0) return -1;
  if (l === q) return 1000;
  if (l.startsWith(q)) return 800;
  // word-boundary
  const parts = l.split(/[^a-z0-9]+/);
  for (let i = 0; i < parts.length; i++) {
    if (parts[i].startsWith(q)) return 600;
  }
  if (l.indexOf(q) >= 0) return 400;
  return -1;
}

function ccBuildIndex() {
  const out = { Screens: [], Parts: [], SKUs: [], Suppliers: [], "Work Orders": [], "Recent Events": [] };

  // Routes (built-in + PUMP_ROUTES) at open-time
  const builtin = (typeof window !== "undefined" && Array.isArray(window.BUILTIN_ROUTES)) ? window.BUILTIN_ROUTES : [];
  const pump    = (typeof window !== "undefined" && Array.isArray(window.PUMP_ROUTES))    ? window.PUMP_ROUTES    : [];
  const allRoutes = builtin.concat(pump);
  for (let i = 0; i < allRoutes.length; i++) {
    const r = allRoutes[i];
    out.Screens.push({
      kind: "screen",
      label: r.title || r.path,
      path: r.path,
      mode: r.mode,
      hint: r.path,
    });
  }

  // Tenant data
  const tenant = (typeof getActiveTenant === "function") ? getActiveTenant() : null;
  if (tenant) {
    const parts = (tenant.parts || []).slice(0, 30);
    for (let i = 0; i < parts.length; i++) {
      const p = parts[i];
      out.Parts.push({
        kind: "part",
        label: p.num + " · " + p.name,
        path: "/forge/ebom",
        hint: p.supplier ? "supplier: " + p.supplier : "",
      });
    }

    const boms = (tenant.boms || []);
    for (let i = 0; i < boms.length; i++) {
      out.SKUs.push({
        kind: "sku",
        label: boms[i].sku,
        path: "/forge/ebom",
        hint: (boms[i].lines || []).length + " lines",
      });
    }

    const sups = (tenant.suppliers || []);
    for (let i = 0; i < sups.length; i++) {
      const s = sups[i];
      out.Suppliers.push({
        kind: "supplier",
        label: s.name,
        path: "/forge/ebom",
        hint: s.category + " · " + s.location,
      });
    }

    const wos = (tenant.work_orders || []);
    for (let i = 0; i < wos.length; i++) {
      const w = wos[i];
      out["Work Orders"].push({
        kind: "wo",
        label: w.id + " · " + w.sku,
        path: "/build/workflows",
        hint: w.status + " · qty " + w.qty,
      });
    }

    const ledger = (tenant.ledger || []);
    const recent = ledger.slice(-5).reverse();
    for (let i = 0; i < recent.length; i++) {
      const e = recent[i];
      out["Recent Events"].push({
        kind: "event",
        label: e.event_id + " · " + e.summary,
        path: "/auditor/ledger",
        hint: e.actor + " · " + (e.ts || "").slice(0, 10),
      });
    }
  }

  return out;
}

function CommandPalette() {
  const [open, setOpen]   = uSCC(false);
  const [query, setQuery] = uSCC("");
  const [active, setActive] = uSCC(0);
  const inputRef = uRCC(null);

  // ⌘K / Ctrl+K toggles
  uECC(function() {
    const handler = function(e) {
      const isMeta = e.metaKey || e.ctrlKey;
      if (isMeta && (e.key === "k" || e.key === "K")) {
        e.preventDefault();
        setOpen(function(v) { return !v; });
      } else if (e.key === "Escape") {
        setOpen(false);
      }
    };
    window.addEventListener("keydown", handler);
    return function() { window.removeEventListener("keydown", handler); };
  }, []);

  // focus input on open, reset state
  uECC(function() {
    if (open) {
      setQuery("");
      setActive(0);
      const t = setTimeout(function() {
        if (inputRef.current && inputRef.current.focus) inputRef.current.focus();
      }, 20);
      return function() { clearTimeout(t); };
    }
    return undefined;
  }, [open]);

  const index = uMCC(function() { return open ? ccBuildIndex() : null; }, [open]);

  // Filter + score
  const grouped = uMCC(function() {
    if (!index) return [];
    const out = [];
    const cats = ["Screens", "Parts", "SKUs", "Suppliers", "Work Orders", "Recent Events"];
    let total = 0;
    for (let ci = 0; ci < cats.length; ci++) {
      const cat = cats[ci];
      const items = index[cat] || [];
      let scored = items.map(function(it) {
        const sName = ccScore(query, it.label);
        const sPath = ccScore(query, it.path);
        const score = Math.max(sName, sPath);
        return { it: it, score: score };
      });
      if (query) scored = scored.filter(function(x) { return x.score >= 0; });
      scored.sort(function(a, b) { return b.score - a.score; });
      const top = scored.slice(0, 5).map(function(x) { return x.it; });
      if (top.length === 0) continue;
      out.push({ cat: cat, items: top });
      total += top.length;
      if (total >= 18) break;
    }
    // Cap to 18 total
    let count = 0;
    const capped = [];
    for (let i = 0; i < out.length; i++) {
      const left = 18 - count;
      if (left <= 0) break;
      const slice = out[i].items.slice(0, left);
      capped.push({ cat: out[i].cat, items: slice });
      count += slice.length;
    }
    return capped;
  }, [index, query]);

  // Flatten visible items for keyboard nav
  const flat = uMCC(function() {
    const f = [];
    for (let i = 0; i < grouped.length; i++) {
      for (let j = 0; j < grouped[i].items.length; j++) {
        f.push({ cat: grouped[i].cat, it: grouped[i].items[j] });
      }
    }
    return f;
  }, [grouped]);

  uECC(function() {
    if (active >= flat.length) setActive(flat.length > 0 ? flat.length - 1 : 0);
  }, [flat, active]);

  function pick(it) {
    setOpen(false);
    if (it && it.path && typeof navigate === "function") navigate(it.path);
  }

  function onKey(e) {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActive(function(a) { return Math.min(flat.length - 1, a + 1); });
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActive(function(a) { return Math.max(0, a - 1); });
    } else if (e.key === "Enter") {
      e.preventDefault();
      const sel = flat[active];
      if (sel) pick(sel.it);
    }
  }

  if (!open) return null;

  return React.createElement(
    "div",
    {
      style: {
        position: "fixed",
        inset: 0,
        zIndex: 1000,
        display: "flex",
        alignItems: "flex-start",
        justifyContent: "center",
        paddingTop: "12vh",
        background: "rgba(20,20,20,0.32)",
        backdropFilter: "blur(2px)",
        fontFamily: CC_FONT_UI,
      },
      onClick: function() { setOpen(false); },
    },
    React.createElement(
      "div",
      {
        onClick: function(e) { e.stopPropagation(); },
        style: {
          width: 640,
          maxHeight: "70vh",
          background: CC_PAPER_BG,
          color: CC_PAPER_INK,
          border: "1px solid " + CC_PAPER_LINE,
          borderRadius: 8,
          boxShadow: "0 30px 60px -10px rgba(0,0,0,0.25), 0 0 0 1px rgba(0,0,0,0.04)",
          overflow: "hidden",
          display: "flex",
          flexDirection: "column",
        },
      },
      // Search bar
      React.createElement(
        "div",
        {
          style: {
            display: "flex",
            alignItems: "center",
            gap: 8,
            padding: "10px 14px",
            borderBottom: "1px solid " + CC_PAPER_LINE_SOFT,
            background: CC_PAPER_BG_3,
          },
        },
        React.createElement(
          "span",
          {
            style: {
              fontFamily: CC_FONT_MONO,
              fontSize: 12,
              color: CC_PAPER_INK_3,
              letterSpacing: "0.08em",
              textTransform: "uppercase",
            },
          },
          "⌘K"
        ),
        React.createElement("input", {
          ref: inputRef,
          id: "cc-palette-search",
          name: "cc-palette-search",
          "aria-label": "Search screens, parts, SKUs, suppliers, work orders",
          value: query,
          placeholder: "search screens, parts, SKUs, suppliers, work orders…",
          onChange: function(e) { setQuery(e.target.value); setActive(0); },
          onKeyDown: onKey,
          style: {
            flex: 1,
            border: 0,
            outline: "none",
            background: "transparent",
            fontFamily: CC_FONT_MONO,
            fontSize: 13,
            color: CC_PAPER_INK,
            padding: 4,
          },
        }),
        React.createElement(
          "span",
          {
            style: {
              fontFamily: CC_FONT_MONO,
              fontSize: 12,
              color: CC_PAPER_INK_4,
              padding: "2px 6px",
              border: "1px solid " + CC_PAPER_LINE,
              borderRadius: 3,
            },
          },
          "esc"
        )
      ),
      // Results
      React.createElement(
        "div",
        {
          style: {
            flex: 1,
            overflowY: "auto",
            padding: "6px 0",
          },
        },
        grouped.length === 0
          ? React.createElement(
              "div",
              {
                style: {
                  padding: "24px 20px",
                  fontFamily: CC_FONT_MONO,
                  fontSize: 12,
                  color: CC_PAPER_INK_4,
                  textAlign: "center",
                },
              },
              query ? "no matches" : "loading index…"
            )
          : grouped.map(function(g, gi) {
              return React.createElement(
                "div",
                { key: g.cat, style: { padding: "4px 0 8px" } },
                React.createElement(
                  "div",
                  {
                    style: {
                      fontFamily: CC_FONT_MONO,
                      fontSize: 12,
                      letterSpacing: "0.10em",
                      textTransform: "uppercase",
                      color: CC_PAPER_INK_4,
                      padding: "6px 16px 4px",
                    },
                  },
                  g.cat
                ),
                g.items.map(function(it, ii) {
                  // compute global flat index
                  let flatIdx = 0;
                  for (let x = 0; x < gi; x++) flatIdx += grouped[x].items.length;
                  flatIdx += ii;
                  const isActive = flatIdx === active;
                  return React.createElement(
                    "button",
                    {
                      key: it.label + "_" + ii,
                      onMouseEnter: function() { setActive(flatIdx); },
                      onClick: function() { pick(it); },
                      style: {
                        display: "flex",
                        alignItems: "center",
                        gap: 8,
                        width: "100%",
                        padding: "8px 16px",
                        border: 0,
                        background: isActive ? CC_PAPER_BG_3 : "transparent",
                        borderLeft: isActive ? "2px solid " + CC_ACCENT : "2px solid transparent",
                        cursor: "pointer",
                        textAlign: "left",
                        fontFamily: CC_FONT_UI,
                        fontSize: 13,
                        color: CC_PAPER_INK,
                      },
                    },
                    g.cat === "Screens" && it.mode
                      ? React.createElement(CCModeBadge, { mode: it.mode })
                      : React.createElement(
                          "span",
                          {
                            style: {
                              width: 16,
                              fontFamily: CC_FONT_MONO,
                              fontSize: 12,
                              color: CC_PAPER_INK_4,
                              textAlign: "center",
                            },
                          },
                          it.kind === "part" ? "·"
                            : it.kind === "sku" ? "≡"
                            : it.kind === "supplier" ? "▸"
                            : it.kind === "wo" ? "WO"
                            : it.kind === "event" ? "E"
                            : "→"
                        ),
                    React.createElement(
                      "span",
                      { style: { flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } },
                      it.label
                    ),
                    it.hint
                      ? React.createElement(
                          "span",
                          {
                            style: {
                              fontFamily: CC_FONT_MONO,
                              fontSize: 12,
                              color: CC_PAPER_INK_4,
                              marginLeft: 8,
                              flexShrink: 0,
                            },
                          },
                          it.hint
                        )
                      : null,
                    isActive
                      ? React.createElement(
                          "span",
                          {
                            style: {
                              fontFamily: CC_FONT_MONO,
                              fontSize: 12,
                              color: CC_PAPER_INK_4,
                              marginLeft: 8,
                              padding: "1px 6px",
                              border: "1px solid " + CC_PAPER_LINE,
                              borderRadius: 3,
                            },
                          },
                          "↵"
                        )
                      : null
                  );
                })
              );
            })
      ),
      // Footer hint
      React.createElement(
        "div",
        {
          style: {
            padding: "8px 14px",
            borderTop: "1px solid " + CC_PAPER_LINE_SOFT,
            display: "flex",
            justifyContent: "space-between",
            fontFamily: CC_FONT_MONO,
            fontSize: 12,
            color: CC_PAPER_INK_4,
            background: CC_PAPER_BG_3,
          },
        },
        React.createElement("span", null, "↑↓ navigate · ↵ open · esc close"),
        React.createElement("span", null, flat.length + " result" + (flat.length === 1 ? "" : "s"))
      )
    )
  );
}

// ──────────────────────────────────────────────────────────────────────
// 2. NotificationBell
// ──────────────────────────────────────────────────────────────────────

function ccBuildNotifications() {
  const tenant = (typeof getActiveTenant === "function") ? getActiveTenant() : null;
  const out = [];
  if (!tenant) return out;

  // Audit due — derived from tenant.audit_case
  if (tenant.audit_case) {
    out.push({
      id: "audit-due",
      severity: "warn",
      ts: tenant.audit_case.date || "2026-04-10",
      title: "Audit due in 14d",
      summary: tenant.audit_case.supplier + " — conditional approval gap (CAPA closure 38d vs 21d target)",
      cta: "Review audit",
      path: "/auditor/ledger",
    });
  }

  // Field returns — derived from tenant.field_returns.length
  const fr = tenant.field_returns || [];
  if (fr.length > 0) {
    out.push({
      id: "field-returns",
      severity: "critical",
      ts: fr[fr.length - 1] ? fr[fr.length - 1].date_returned : "2026-04-14",
      title: fr.length + " returns flagged",
      summary: fr.length + " NRV cracking returns. ECO-0051 in review.",
      cta: "Open ECO-0051",
      path: "/build/eco",
    });
  }

  // Castings short — synthetic (skip on stub tenants)
  if (tenant && tenant.depth !== "stub") {
    out.push({
      id: "castings-short",
      severity: "warn",
      ts: "2026-04-28",
      title: "C.I. castings short by 12 units",
      summary: "Athena Castings can expedite within 9 days at +6% premium.",
      cta: "Expedite",
      path: "/line/queue",
    });
  }

  // Pilot pass — tenant.work_orders[2] (M-31507 pilot)
  const pilot = (tenant.work_orders || [])[2];
  if (pilot && pilot.status === "pilot") {
    out.push({
      id: "pilot-pass",
      severity: "info",
      ts: "2026-04-28",
      title: "Pilot 7/10 pass",
      summary: pilot.id + " · " + pilot.sku + " — convert to series soon.",
      cta: "Open work order",
      path: "/build/workflows",
    });
  }

  // ECO awaiting approval (skip on stub tenants)
  if (tenant && tenant.depth !== "stub") {
    out.push({
      id: "eco-pending",
      severity: "warn",
      ts: "2026-04-22",
      title: "1 ECO awaiting approval",
      summary: "ECO-0051 NRV redesign — Plant Director sign-off pending.",
      cta: "Approve",
      path: "/build/approvals",
    });
  }

  return out;
}

function NotificationBell() {
  const [open, setOpen] = uSCC(false);
  const [pulse, setPulse] = uSCC(true);
  const [seenAt, setSeenAt] = uSCC(0);
  const wrapRef = uRCC(null);

  const items = uMCC(function() { return ccBuildNotifications(); }, [open, seenAt]);

  // Pulse decays after 3 seconds (subtle "new" cue)
  uECC(function() {
    const t = setTimeout(function() { setPulse(false); }, 3000);
    return function() { clearTimeout(t); };
  }, []);

  // Re-pulse every 60s to indicate live signals (decorative)
  uECC(function() {
    const interval = setInterval(function() {
      setPulse(true);
      setTimeout(function() { setPulse(false); }, 1800);
    }, 60000);
    return function() { clearInterval(interval); };
  }, []);

  // Click outside closes
  uECC(function() {
    if (!open) return undefined;
    const onDown = function(e) {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener("mousedown", onDown);
    return function() { document.removeEventListener("mousedown", onDown); };
  }, [open]);

  function takeAction(it) {
    setOpen(false);
    if (it && it.path && typeof navigate === "function") navigate(it.path);
  }

  const Ic = (typeof Icons !== "undefined") ? Icons : {};
  const BellIcon = Ic.Bell || function() { return React.createElement("span", null, "♪"); };

  return React.createElement(
    "div",
    {
      ref: wrapRef,
      style: {
        position: "fixed",
        top: 14,
        right: 18,
        zIndex: 900,
        fontFamily: CC_FONT_UI,
      },
    },
    React.createElement(
      "button",
      {
        onClick: function() { setOpen(function(v) { return !v; }); setSeenAt(Date.now()); },
        title: "notifications",
        style: {
          position: "relative",
          width: 30,
          height: 30,
          borderRadius: 6,
          background: open ? CC_PAPER_BG_2 : "transparent",
          border: "1px solid " + (open ? CC_PAPER_LINE : "transparent"),
          color: CC_PAPER_INK_2,
          cursor: "pointer",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          transition: "background .15s ease",
        },
      },
      React.createElement(BellIcon, { size: 16 }),
      items.length > 0
        ? React.createElement(
            "span",
            {
              style: {
                position: "absolute",
                top: 2,
                right: 2,
                minWidth: 14,
                height: 14,
                padding: "0 3px",
                borderRadius: 7,
                fontFamily: CC_FONT_MONO,
                fontSize: 12,
                lineHeight: "14px",
                color: "#fff",
                background: "oklch(0.55 0.18 25)",
                textAlign: "center",
                boxShadow: pulse ? "0 0 0 4px rgba(220,80,60,0.18)" : "none",
                transition: "box-shadow .35s ease",
              },
            },
            items.length
          )
        : null
    ),
    open
      ? React.createElement(
          "div",
          {
            style: {
              position: "absolute",
              top: 36,
              right: 0,
              width: 360,
              background: CC_PAPER_BG,
              border: "1px solid " + CC_PAPER_LINE,
              borderRadius: 8,
              boxShadow: "0 18px 40px -10px rgba(0,0,0,0.16)",
              overflow: "hidden",
            },
          },
          React.createElement(
            "div",
            {
              style: {
                padding: "8px 12px",
                borderBottom: "1px solid " + CC_PAPER_LINE_SOFT,
                background: CC_PAPER_BG_3,
                fontFamily: CC_FONT_MONO,
                fontSize: 12,
                letterSpacing: "0.10em",
                textTransform: "uppercase",
                color: CC_PAPER_INK_3,
                display: "flex",
                justifyContent: "space-between",
              },
            },
            React.createElement("span", null, "notifications"),
            React.createElement("span", null, items.length + " active")
          ),
          React.createElement(
            "div",
            { style: { maxHeight: 420, overflowY: "auto" } },
            items.length === 0
              ? React.createElement(
                  "div",
                  {
                    style: {
                      padding: 18,
                      fontFamily: CC_FONT_MONO,
                      fontSize: 12,
                      color: CC_PAPER_INK_4,
                      textAlign: "center",
                    },
                  },
                  "no notifications"
                )
              : items.map(function(it) {
                  const tone = ccSevTone(it.severity);
                  return React.createElement(
                    "div",
                    {
                      key: it.id,
                      style: {
                        padding: "10px 12px",
                        borderBottom: "1px solid " + CC_PAPER_LINE_SOFT,
                        display: "flex",
                        flexDirection: "column",
                        gap: 4,
                      },
                    },
                    React.createElement(
                      "div",
                      { style: { display: "flex", alignItems: "center", gap: 8 } },
                      React.createElement(
                        "span",
                        {
                          style: {
                            fontFamily: CC_FONT_MONO,
                            fontSize: 12,
                            letterSpacing: "0.06em",
                            textTransform: "uppercase",
                            padding: "1px 6px",
                            borderRadius: 3,
                            background: tone.bg,
                            color: tone.fg,
                          },
                        },
                        tone.label
                      ),
                      React.createElement(
                        "span",
                        {
                          style: {
                            fontFamily: CC_FONT_UI,
                            fontSize: 12,
                            fontWeight: 600,
                            color: CC_PAPER_INK,
                            flex: 1,
                          },
                        },
                        it.title
                      ),
                      React.createElement(
                        "span",
                        {
                          style: {
                            fontFamily: CC_FONT_MONO,
                            fontSize: 12,
                            color: CC_PAPER_INK_4,
                          },
                        },
                        (it.ts || "").slice(0, 10)
                      )
                    ),
                    React.createElement(
                      "div",
                      {
                        style: {
                          fontFamily: CC_FONT_UI,
                          fontSize: 12,
                          color: CC_PAPER_INK_2,
                          lineHeight: 1.45,
                        },
                      },
                      it.summary
                    ),
                    React.createElement(
                      "button",
                      {
                        onClick: function() { takeAction(it); },
                        style: {
                          alignSelf: "flex-start",
                          marginTop: 4,
                          padding: "3px 10px",
                          fontFamily: CC_FONT_MONO,
                          fontSize: 12,
                          color: CC_ACCENT,
                          background: "transparent",
                          border: "1px solid " + CC_PAPER_LINE,
                          borderRadius: 4,
                          cursor: "pointer",
                        },
                      },
                      it.cta + " →"
                    )
                  );
                })
          )
        )
      : null
  );
}

// ──────────────────────────────────────────────────────────────────────
// 3. ResetDemo
// ──────────────────────────────────────────────────────────────────────

function ResetDemo() {
  const [confirm, setConfirm] = uSCC(false);
  const [hover, setHover]     = uSCC(false);

  // Esc dismisses the confirm modal
  uECC(function() {
    if (!confirm) return;
    function onKey(e) {
      if (e.key === "Escape") { setConfirm(false); }
    }
    window.addEventListener("keydown", onKey);
    return function() { window.removeEventListener("keydown", onKey); };
  }, [confirm]);

  function doReset() {
    // Capture the active tenant BEFORE wiping localStorage (PR-5):
    // reset on Aetherion must reseed Aetherion, not snap back to Tritan.
    var currentTenant = (typeof window !== "undefined" && typeof window.getActiveTenantId === "function")
      ? window.getActiveTenantId()
      : "tritan";
    try {
      if (typeof localStorage !== "undefined") localStorage.clear();
    } catch (e) { /* ignore */ }
    if (typeof setActiveTenant === "function") setActiveTenant(currentTenant);
    // Server-side reset: truncate + reseed SQLite from fixture for the active tenant.
    var serverReset = (window.forgeApi && typeof window.forgeApi.resetDemo === "function")
      ? window.forgeApi.resetDemo().catch(function() { /* ignore offline */ })
      : Promise.resolve();
    serverReset.then(function() {
      if (typeof window !== "undefined") {
        window.location.hash = "/forge/landing";
        setTimeout(function() { window.location.reload(); }, 30);
      }
    });
  }

  return React.createElement(
    React.Fragment,
    null,
    React.createElement(
      "button",
      {
        onMouseEnter: function() { setHover(true); },
        onMouseLeave: function() { setHover(false); },
        onClick: function() { setConfirm(true); },
        title: "Reset demo state",
        style: {
          position: "fixed",
          right: 18,
          bottom: 18,
          zIndex: 800,
          height: 28,
          padding: "0 12px",
          borderRadius: 14,
          background: hover ? CC_PAPER_BG : CC_PAPER_BG_3,
          border: "1px solid " + CC_PAPER_LINE,
          color: CC_PAPER_INK_2,
          fontFamily: CC_FONT_MONO,
          fontSize: 12,
          letterSpacing: "0.04em",
          cursor: "pointer",
          boxShadow: "0 6px 14px -6px rgba(0,0,0,0.18)",
          display: "inline-flex",
          alignItems: "center",
          gap: 6,
        },
      },
      React.createElement("span", null, "↻"),
      React.createElement("span", null, "reset demo")
    ),
    confirm
      ? React.createElement(
          "div",
          {
            style: {
              position: "fixed",
              inset: 0,
              zIndex: 1100,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              background: "rgba(20,20,20,0.32)",
              backdropFilter: "blur(2px)",
              fontFamily: CC_FONT_UI,
            },
            onClick: function() { setConfirm(false); },
          },
          React.createElement(
            "div",
            {
              onClick: function(e) { e.stopPropagation(); },
              style: {
                width: 420,
                background: CC_PAPER_BG,
                color: CC_PAPER_INK,
                border: "1px solid " + CC_PAPER_LINE,
                borderRadius: 8,
                boxShadow: "0 30px 60px -10px rgba(0,0,0,0.25)",
                padding: 20,
              },
            },
            React.createElement(
              "div",
              {
                style: {
                  fontFamily: CC_FONT_MONO,
                  fontSize: 12,
                  letterSpacing: "0.10em",
                  textTransform: "uppercase",
                  color: CC_PAPER_INK_3,
                  marginBottom: 8,
                },
              },
              "reset · confirm"
            ),
            React.createElement(
              "div",
              {
                style: {
                  fontFamily: CC_FONT_UI,
                  fontSize: 16,
                  fontWeight: 600,
                  marginBottom: 8,
                  lineHeight: 1.3,
                },
              },
              "Reset all demo state?"
            ),
            React.createElement(
              "div",
              {
                style: {
                  fontFamily: CC_FONT_UI,
                  fontSize: 13,
                  color: CC_PAPER_INK_2,
                  marginBottom: 16,
                  lineHeight: 1.5,
                },
              },
              "Tenant switches, recent events, drafts will be cleared. The demo will reload to landing."
            ),
            React.createElement(
              "div",
              { style: { display: "flex", justifyContent: "flex-end", gap: 8 } },
              React.createElement(
                "button",
                {
                  onClick: function() { setConfirm(false); },
                  style: {
                    height: 32,
                    padding: "0 14px",
                    borderRadius: 4,
                    background: "transparent",
                    border: "1px solid " + CC_PAPER_LINE,
                    color: CC_PAPER_INK_2,
                    fontFamily: CC_FONT_UI,
                    fontSize: 13,
                    cursor: "pointer",
                  },
                },
                "cancel"
              ),
              React.createElement(
                "button",
                {
                  onClick: function() { doReset(); },
                  style: {
                    height: 32,
                    padding: "0 14px",
                    borderRadius: 4,
                    background: "oklch(0.55 0.18 25)",
                    border: "1px solid oklch(0.55 0.18 25)",
                    color: "#fff",
                    fontFamily: CC_FONT_UI,
                    fontSize: 13,
                    fontWeight: 600,
                    cursor: "pointer",
                  },
                },
                "reset"
              )
            )
          )
        )
      : null
  );
}

// ──────────────────────────────────────────────────────────────────────
// 4. ModeAwareWorkshopHints — global FCP template registry
// ──────────────────────────────────────────────────────────────────────

const MODE_FCP_TEMPLATES = {
  forge: [
    { verb: "match",     noun: "envelope", template: "forge.match_envelope({ duty: { Q: 160, H: 120, HP: 2.0 } })" },
    { verb: "explain",   noun: "cost",     template: "forge.explain_cost({ sku: \"M-27418\", layer: \"motor_rmc\" })" },
    { verb: "carryover", noun: "design",   template: "forge.carryover({ from: \"M-26102\", to: \"M-27418\" })" },
  ],
  plan: [
    { verb: "lock",     noun: "price",     template: "plan.lock_price({ material: \"copper\", weeks: 8 })" },
    { verb: "schedule", noun: "tooling",   template: "plan.schedule_tooling({ wo: \"WO-44219\" })" },
    { verb: "simulate", noun: "lead-time", template: "plan.simulate_lead_time({ scenario: \"dual_source_castings\" })" },
  ],
  build: [
    { verb: "release", noun: "routing", template: "build.release_routing({ rev: \"C\", wos: [\"WO-44219\"] })" },
    { verb: "tighten", noun: "gate",    template: "build.tighten_gate({ gate_id: \"QG-014\", spec: \"<2g\" })" },
    { verb: "raise",   noun: "eco",     template: "build.raise_eco({ part: \"NRV-86mm\", reason: \"5 field returns\" })" },
  ],
  line: [
    { verb: "expedite",  noun: "supply",   template: "line.expedite({ part: \"casting-body\", supplier: \"Athena\" })" },
    { verb: "rebalance", noun: "stations", template: "line.rebalance({ wo: \"WO-44219\" })" },
    { verb: "dispatch",  noun: "tranche",  template: "line.dispatch({ wo: \"WO-44219\", tranche: 1, qty: 100 })" },
  ],
  traveler: [
    { verb: "capture", noun: "dimension", template: "traveler.capture({ serial: \"TPX-H-0011\", param: \"rotor_shaft_dia\" })" },
    { verb: "advance", noun: "station",   template: "traveler.advance({ serial: \"TPX-H-0008\", from: 5, to: 6 })" },
    { verb: "raise",   noun: "ncr",       template: "traveler.raise_ncr({ serial: \"TPX-H-0011\", reason: \"stator bore OOT\" })" },
  ],
  auditor: [
    { verb: "filter", noun: "ledger",     template: "auditor.filter({ wo: \"WO-44219\" })" },
    { verb: "export", noun: "audit-pack", template: "auditor.export({ wo: \"WO-44219\", format: \"pdf\" })" },
    { verb: "verify", noun: "signature",  template: "auditor.verify({ event_id: \"E-0017\" })" },
  ],
};

// ──────────────────────────────────────────────────────────────────────
// UserSwitcher — temporary pill that surfaces window.__forgeCurrentUser
// so operator signatures (Rohit B., Neha G., …) flip cleanly during demo.
// Lives in the top bar / floating; clicking opens a popover of PUMP_TENANT.people.
// ──────────────────────────────────────────────────────────────────────

function UserSwitcher() {
  const [open, setOpen] = uSCC(false);
  const [, bump] = uSCC(0);

  uECC(function() {
    const onMutate = function() { bump(function(b) { return b + 1; }); };
    window.addEventListener("forge:tenant-mutated", onMutate);
    window.addEventListener("forge:tenant-change", onMutate);
    return function() {
      window.removeEventListener("forge:tenant-mutated", onMutate);
      window.removeEventListener("forge:tenant-change", onMutate);
    };
  }, []);

  const tenant = (typeof getActiveTenant === "function") ? getActiveTenant() : null;
  const people = (tenant && tenant.people) || [];
  const current = (window.getCurrentUser && window.getCurrentUser()) || people[0] || { name: "—", role: "—" };

  function pick(p) {
    if (window.setCurrentUser) window.setCurrentUser(p);
    setOpen(false);
  }

  // W15B — Sign out wires the previously orphaned POST /api/:tenant/auth/logout
  // endpoint. Server-side: req.session.destroy() drops the express-session
  // cookie. Client: clear __forgeCurrentUser, notify listeners, and bounce
  // to the chromeless landing route. ensureAuth() will auto-re-login on
  // the next mutation, so this is a soft logout for demo purposes.
  function onSignOut() {
    setOpen(false);
    if (!window.forgeApi || typeof window.forgeApi.logout !== "function") return;
    window.forgeApi.logout().then(function() {
      window.__forgeCurrentUser = null;
      try {
        window.dispatchEvent(new CustomEvent("forge:user-switched", { detail: { user: null, reason: "logout" } }));
      } catch (_e) { /* ignore */ }
      try { window.location.hash = "#/forge/landing"; } catch (_e) { /* ignore */ }
    }).catch(function() {
      // soft-fail — server may already have destroyed the session.
      window.__forgeCurrentUser = null;
      try {
        window.dispatchEvent(new CustomEvent("forge:user-switched", { detail: { user: null, reason: "logout" } }));
      } catch (_e) { /* ignore */ }
    });
  }

  return React.createElement(
    "div",
    {
      style: {
        position: "fixed", top: 14, right: 96, zIndex: 70,
        fontFamily: CC_FONT_UI,
      },
    },
    React.createElement(
      "button",
      {
        onClick: function() { setOpen(function(v) { return !v; }); },
        title: "Switch operator",
        style: {
          height: 28, padding: "0 10px",
          borderRadius: 14,
          border: "1px solid " + CC_PAPER_LINE,
          background: CC_PAPER_BG,
          color: CC_PAPER_INK_2,
          fontSize: 12,
          fontFamily: CC_FONT_UI,
          cursor: "pointer",
          display: "inline-flex", alignItems: "center", gap: 8,
          boxShadow: "0 2px 6px rgba(0,0,0,0.06)",
        },
      },
      React.createElement(
        "span",
        {
          style: {
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            width: 18, height: 18, borderRadius: "50%",
            background: CC_ACCENT, color: "white",
            fontFamily: CC_FONT_MONO, fontSize: 10, fontWeight: 600,
          },
        },
        (current.name || "—").split(/\s+/).map(function(s) { return s[0]; }).join("").slice(0, 2).toUpperCase()
      ),
      React.createElement("span", { className: "mono", style: { fontSize: 12 } }, current.name || "—"),
      React.createElement("span", { style: { color: CC_PAPER_INK_4, fontSize: 12 } }, "▾")
    ),
    open && React.createElement(
      "div",
      {
        style: {
          position: "absolute", top: 34, right: 0,
          minWidth: 260,
          background: CC_PAPER_BG,
          border: "1px solid " + CC_PAPER_LINE,
          borderRadius: 4,
          boxShadow: "0 10px 32px rgba(0,0,0,0.12)",
          padding: 6,
        },
      },
      React.createElement("div", { className: "label", style: { padding: "6px 8px", color: CC_PAPER_INK_4 } }, "switch operator"),
      people.map(function(p) {
        const active = p.name === current.name;
        return React.createElement(
          "button",
          {
            key: p.id || p.name,
            onClick: function() { pick(p); },
            style: {
              display: "flex", alignItems: "center", gap: 8, width: "100%",
              padding: "7px 8px",
              background: active ? CC_PAPER_BG_3 : "transparent",
              border: "none", borderRadius: 3,
              cursor: "pointer", textAlign: "left",
              fontFamily: CC_FONT_UI, fontSize: 12, color: CC_PAPER_INK_2,
            },
          },
          React.createElement(
            "span",
            {
              style: {
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                width: 22, height: 22, borderRadius: "50%",
                background: CC_ACCENT, color: "white",
                fontFamily: CC_FONT_MONO, fontSize: 10, fontWeight: 600,
              },
            },
            (p.name || "—").split(/\s+/).map(function(s) { return s[0]; }).join("").slice(0, 2).toUpperCase()
          ),
          React.createElement("span", { style: { flex: 1 } },
            React.createElement("div", null, p.name),
            React.createElement("div", { className: "mono", style: { fontSize: 12, color: CC_PAPER_INK_4 } }, p.role + " · " + p.station)
          ),
          active && React.createElement("span", { className: "mono", style: { color: CC_ACCENT, fontSize: 12 } }, "✓")
        );
      }),
      // W15B — separator + Sign out (wires POST /api/:tenant/auth/logout).
      React.createElement("div", {
        style: { height: 1, background: CC_PAPER_LINE, margin: "6px 4px" },
      }),
      React.createElement(
        "button",
        {
          onClick: onSignOut,
          style: {
            display: "flex", alignItems: "center", gap: 8, width: "100%",
            padding: "7px 8px",
            background: "transparent",
            border: "none", borderRadius: 3,
            cursor: "pointer", textAlign: "left",
            fontFamily: CC_FONT_UI, fontSize: 12, color: CC_PAPER_INK_2,
          },
        },
        React.createElement(
          "span",
          {
            style: {
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              width: 22, height: 22, borderRadius: "50%",
              border: "1px solid " + CC_PAPER_LINE,
              color: CC_PAPER_INK_4,
              fontFamily: CC_FONT_MONO, fontSize: 12, fontWeight: 600,
            },
          },
          "→"
        ),
        React.createElement("span", { style: { flex: 1 } },
          React.createElement("div", null, "Sign out"),
          React.createElement("div", { className: "mono", style: { fontSize: 12, color: CC_PAPER_INK_4 } }, "end session · return to landing")
        )
      )
    )
  );
}

// ──────────────────────────────────────────────────────────────────────
// Composite mount
// ──────────────────────────────────────────────────────────────────────

function CrossCuttingMount() {
  return React.createElement(
    React.Fragment,
    null,
    React.createElement(CommandPalette),
    React.createElement(NotificationBell),
    React.createElement(UserSwitcher),
    React.createElement(ResetDemo)
  );
}

// ──────────────────────────────────────────────────────────────────────
// Globals
// ──────────────────────────────────────────────────────────────────────

if (typeof window !== "undefined") {
  window.CommandPalette       = CommandPalette;
  window.NotificationBell     = NotificationBell;
  window.UserSwitcher         = UserSwitcher;
  window.ResetDemo            = ResetDemo;
  window.CrossCuttingMount    = CrossCuttingMount;
  window.MODE_FCP_TEMPLATES   = MODE_FCP_TEMPLATES;
}
