/* FORGE — application shell: sidebar + topbar + content + workshop drawer slot.
   Style: matches the deck-paper aesthetic from landing.jsx, using tokens.css vars. */

const { useState: uASS, useEffect: uASE, useMemo: uASM } = React;

// Mode -> color (oklch)
const MODE_COLOR = {
  forge:    "oklch(0.55 0.18 250)",  // blue
  plan:     "oklch(0.55 0.16 290)",  // violet
  build:    "oklch(0.55 0.16 30)",   // amber
  line:     "oklch(0.55 0.16 150)",  // green
  traveler: "oklch(0.55 0.16 350)",  // pink
  auditor:  "oklch(0.30 0.01 85)",   // ink
};

const MODE_LABEL = {
  forge:    "forge://",
  plan:     "plan://",
  build:    "build://",
  line:     "line://",
  traveler: "traveler://",
  auditor:  "auditor://",
};

// ---------------- ModeBadge ----------------
function ModeBadge({ mode }) {
  const color = MODE_COLOR[mode] || MODE_COLOR.forge;
  const label = MODE_LABEL[mode] || (mode + "://");
  const _modeBadgeStyle = {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    height: 22,
    padding: "0 10px",
    borderRadius: 4,
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    letterSpacing: "0.04em",
    color: "#fff",
    background: color,
    border: "1px solid " + color,
  };
  return (
    <span style={_modeBadgeStyle}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#fff", opacity: 0.9 }} />
      {label}
    </span>
  );
}

// ---------------- TenantSwitcher ----------------
function TenantSwitcher() {
  const [open, setOpen] = uASS(false);
  const [, bump] = uASS(0);
  const tenants = (typeof listTenants === "function") ? listTenants() : [];
  const currentId = (typeof getActiveTenantId === "function") ? getActiveTenantId() : "tritan";
  const current = tenants.find(function(t) { return t.id === currentId; }) || tenants[0];

  uASE(function() {
    const onChange = function() { bump(Math.random()); };
    window.addEventListener("forge:tenant-change", onChange);
    return function() { window.removeEventListener("forge:tenant-change", onChange); };
  }, []);

  const depthTone = function(depth) {
    if (depth === "deep") return { bg: "oklch(0.88 0.07 150)", fg: "oklch(0.30 0.08 150)" };
    if (depth === "stub-with-bom") return { bg: "oklch(0.78 0.10 85)", fg: "oklch(0.20 0.01 85)" };
    return { bg: "oklch(0.86 0.005 85)", fg: "oklch(0.30 0.01 85)" };
  };

  const t = depthTone(current ? current.depth : "stub");
  const _switcherBtnStyle = {
    display: "inline-flex",
    alignItems: "center",
    gap: 8,
    height: 28,
    padding: "0 10px",
    borderRadius: 4,
    background: "var(--bg-1, #fff)",
    border: "1px solid var(--line, oklch(0.84 0.006 85))",
    fontFamily: "var(--font-ui)",
    fontSize: 12,
    color: "var(--ink-1, oklch(0.16 0.01 85))",
    cursor: "pointer",
  };
  const _switcherDepthBadgeStyle = {
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    letterSpacing: "0.06em",
    textTransform: "uppercase",
    padding: "1px 6px",
    borderRadius: 3,
    background: t.bg,
    color: t.fg,
  };
  const _switcherMenuStyle = {
    position: "absolute",
    top: 32,
    right: 0,
    zIndex: 1000,
    minWidth: 280,
    background: "var(--bg-1, #fff)",
    border: "1px solid var(--line-strong, oklch(0.78 0.006 85))",
    borderRadius: 6,
    boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
    padding: 6,
  };

  return (
    <div style={{ position: "relative" }}>
      <button
        onClick={function() { setOpen(!open); }}
        style={_switcherBtnStyle}
      >
        <span style={{ fontWeight: 500 }}>{current ? current.name : "—"}</span>
        <span style={_switcherDepthBadgeStyle}>
          {current ? current.depth : "—"}
        </span>
        <span style={{ opacity: 0.5, fontSize: 12 }}>▾</span>
      </button>
      {open && (
        <div style={_switcherMenuStyle}>
          {tenants.map(function(tt) {
            const tn = depthTone(tt.depth);
            const isCurrent = tt.id === currentId;
            const _tenantItemStyle = {
              display: "block",
              width: "100%",
              textAlign: "left",
              padding: "8px 10px",
              borderRadius: 4,
              border: 0,
              background: isCurrent ? "var(--bg-2, oklch(0.965 0.005 85))" : "transparent",
              cursor: "pointer",
              marginBottom: 2,
            };
            const _tenantDepthBadgeStyle = {
              fontFamily: "var(--font-mono)",
              fontSize: 12,
              letterSpacing: "0.06em",
              textTransform: "uppercase",
              padding: "1px 6px",
              borderRadius: 3,
              background: tn.bg,
              color: tn.fg,
            };
            return (
              <button
                key={tt.id}
                onClick={function() {
                  if (typeof setActiveTenant === "function") setActiveTenant(tt.id);
                  setOpen(false);
                }}
                style={_tenantItemStyle}
              >
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                  <span style={{ fontFamily: "var(--font-ui)", fontSize: 12, fontWeight: 500 }}>{tt.name}</span>
                  <span style={_tenantDepthBadgeStyle}>
                    {tt.depth}
                  </span>
                </div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-3, oklch(0.46 0.01 85))", marginTop: 2 }}>
                  {tt.tagline}
                </div>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ---------------- Sidebar ----------------
function Sidebar({ nav, current, onPick }) {
  const groups = nav || (typeof NAV !== "undefined" ? NAV : []);
  const Ic = (typeof Icons !== "undefined") ? Icons : {};
  const _sidebarStyle = {
    width: 280,
    flex: "0 0 280px",
    height: "100vh",
    overflowY: "auto",
    background: "var(--bg-2, oklch(0.965 0.005 85))",
    borderRight: "1px solid var(--line, oklch(0.84 0.006 85))",
    padding: "16px 12px",
    boxSizing: "border-box",
  };
  const _sidebarHeaderStyle = {
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    letterSpacing: "0.10em",
    textTransform: "uppercase",
    color: "var(--ink-3, oklch(0.46 0.01 85))",
    padding: "0 8px 12px",
    borderBottom: "1px solid var(--line-soft, oklch(0.90 0.005 85))",
    marginBottom: 12,
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
  };
  return (
    <aside style={_sidebarStyle}>
      <div style={_sidebarHeaderStyle}>
        <span style={{ fontWeight: 600, color: "var(--ink-1, oklch(0.16 0.01 85))" }}>FORGE</span>
        <span>system of action</span>
      </div>

      {groups.map(function(g) {
        return (
          <div key={g.g} style={{ marginBottom: 14 }}>
            <div
              style={{
                fontFamily: "var(--font-mono)",
                fontSize: 12,
                letterSpacing: "0.10em",
                textTransform: "uppercase",
                color: "var(--ink-3, oklch(0.46 0.01 85))",
                padding: "0 8px 6px",
              }}
            >
              {g.g}
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
              {(g.items || []).map(function(it) {
                const isCurrent = current === it.id;
                const IconCmp = Ic[it.icon] || Ic.Dot;
                const _navItemStyle = {
                  display: "flex",
                  alignItems: "center",
                  gap: 10,
                  padding: "7px 8px",
                  borderRadius: 4,
                  border: 0,
                  background: isCurrent ? "var(--bg-1, #fff)" : "transparent",
                  borderLeft: isCurrent ? "2px solid var(--accent, oklch(0.55 0.18 250))" : "2px solid transparent",
                  color: isCurrent ? "var(--ink-1, oklch(0.16 0.01 85))" : "var(--ink-2, oklch(0.30 0.01 85))",
                  fontFamily: "var(--font-ui)",
                  fontSize: 12,
                  fontWeight: isCurrent ? 500 : 400,
                  cursor: "pointer",
                  textAlign: "left",
                  width: "100%",
                };
                return (
                  <button
                    key={it.id}
                    onClick={function() { if (onPick) onPick(it.id, g.g); }}
                    style={_navItemStyle}
                  >
                    {IconCmp && <IconCmp size={14} />}
                    <span>{it.label}</span>
                  </button>
                );
              })}
            </div>
          </div>
        );
      })}
    </aside>
  );
}

// ---------------- Topbar ----------------
function Topbar({ mode, breadcrumbs, onOpenWorkshop }) {
  const crumbs = breadcrumbs || [];
  const _topbarStyle = {
    height: 48,
    flex: "0 0 48px",
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    // Right side reserves 232px so the floating UserSwitcher (right:96, w~120)
    // and notification bell (right:18, w:30) don't sit on top of the in-flow
    // ⌘K button + TenantSwitcher pill. Without this, the tenant name+caret
    // get fully occluded — only the "deep" depth badge peeks between the two
    // floating pills.
    padding: "0 232px 0 16px",
    borderBottom: "1px solid var(--line, oklch(0.84 0.006 85))",
    background: "var(--bg-1, #fff)",
    gap: 12,
  };
  const _crumbsStyle = {
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    color: "var(--ink-3, oklch(0.46 0.01 85))",
    display: "flex",
    alignItems: "center",
    gap: 6,
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  };
  return (
    <div style={_topbarStyle}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
        <ModeBadge mode={mode} />
        <div style={_crumbsStyle}>
          {crumbs.map(function(c, i) {
            return (
              <span key={c} style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                {i > 0 && <span style={{ opacity: 0.4 }}>/</span>}
                <span style={{ color: i === crumbs.length - 1 ? "var(--ink-1, oklch(0.16 0.01 85))" : "inherit" }}>{c}</span>
              </span>
            );
          })}
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        {(function () {
          const _topbarKBtnStyle = {
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            height: 28,
            padding: "0 10px",
            borderRadius: 4,
            background: "var(--bg-2, oklch(0.965 0.005 85))",
            border: "1px solid var(--line, oklch(0.84 0.006 85))",
            fontFamily: "var(--font-mono)",
            fontSize: 12,
            color: "var(--ink-2, oklch(0.30 0.01 85))",
            cursor: "pointer",
          };
          return (
            <button
              onClick={onOpenWorkshop}
              title="Open workshop (⌘\\)"
              style={_topbarKBtnStyle}
            >
              ⌘\
            </button>
          );
        })()}
        <TenantSwitcher />
      </div>
    </div>
  );
}

// ---------------- AppShell ----------------
function AppShell({ children, mode, screenId }) {
  const [workshopOpen, setWorkshopOpen] = uASS(false);
  const [toasts, setToasts] = uASS([]);
  const tenant = (typeof getActiveTenant === "function") ? getActiveTenant() : null;
  const nav = (tenant && tenant.nav && tenant.nav.length) ? tenant.nav : (typeof NAV !== "undefined" ? NAV : []);

  // Derive sidebar "current" from screenId (e.g. "/forge/dashboard" -> "dashboard")
  const current = uASM(function() {
    if (!screenId) return "";
    const aliases = {
      "/forge/customer-onboarding": "onboarding",
      "/line/queue": "line",
      "/traveler/console": "traveler",
      "/auditor/ledger": "auditor",
    };
    if (aliases[screenId]) return aliases[screenId];
    const parts = String(screenId).split("/").filter(Boolean);
    return parts[parts.length - 1] || "";
  }, [screenId]);

  // ⌘\ toggles workshop drawer
  uASE(function() {
    const handler = function(e) {
      if ((e.metaKey || e.ctrlKey) && e.key === "\\") {
        e.preventDefault();
        setWorkshopOpen(function(v) { return !v; });
      }
    };
    window.addEventListener("keydown", handler);
    return function() { window.removeEventListener("keydown", handler); };
  }, []);

  // Toast host — the documented listener for window.forgeToast() (see ui.jsx).
  // Inert/coming-in-v2 buttons dispatch "forge:toast"; render a transient stack.
  uASE(function() {
    const onToast = function(e) {
      const msg = (e && e.detail != null) ? String(e.detail) : "";
      if (!msg) return;
      const id = String(Date.now()) + "-" + Math.random().toString(36).slice(2, 7);
      setToasts(function(list) { return list.concat([{ id: id, msg: msg }]); });
      setTimeout(function() {
        setToasts(function(list) { return list.filter(function(t) { return t.id !== id; }); });
      }, 3600);
    };
    window.addEventListener("forge:toast", onToast);
    return function() { window.removeEventListener("forge:toast", onToast); };
  }, []);

  const onPick = function(id, groupName) {
    if (typeof navigate !== "function") return;
    // Resolve nav id against registered routes — sidebar items are keyed by
    // bare id, but routes live under different mode prefixes (e.g. "approvals"
    // is /build/approvals, "auditor" is /auditor/ledger). We map the sidebar
    // group name (e.g. "Line", "Build") to its target mode so we can accurately
    // route items without tail-match collisions.
    const getModeForGroup = function(gName) {
      const g = String(gName || "").toLowerCase();
      if (g.indexOf("program") >= 0) return "forge";
      if (g.indexOf("plan") >= 0) return "plan";
      if (g.indexOf("build") >= 0) return "build";
      if (g.indexOf("line") >= 0) return "line";
      if (g.indexOf("traveler") >= 0) return "traveler";
      if (g.indexOf("governance") >= 0) return "auditor";
      if (g.indexOf("org") >= 0) return "forge";
      return mode || "forge";
    };

    const targetMode = getModeForGroup(groupName);
    const routeOverride = function(navId, gName) {
      const g = String(gName || "").toLowerCase();
      if (g.indexOf("program") >= 0 && navId === "onboarding") return "/forge/customer-onboarding";
      if (g.indexOf("line") >= 0 && navId === "line") return "/line/queue";
      if (g.indexOf("traveler") >= 0 && navId === "traveler") return "/traveler/console";
      if (g.indexOf("governance") >= 0 && navId === "auditor") return "/auditor/ledger";
      if (g.indexOf("plan") >= 0 && navId === "plc") return "/forge/plc";
      if (g.indexOf("plan") >= 0 && navId === "lifecycle") return "/forge/lifecycle";
      return null;
    };

    const getActiveTenantRoutes = function() {
      const tid = (typeof getActiveTenantId === "function") ? getActiveTenantId() : "tritan";
      const win = (typeof window !== "undefined") ? window : {};
      const tenantRoutes = (tid === "tritan")
        ? (win.PUMP_ROUTES || [])
        : (tid === "mittelstand")
          ? (win.MITTELSTAND_ROUTES || [])
          : ((win.AETHERION_ROUTES || win.SPACE_ROUTES) || []);

      return [].concat(tenantRoutes || [], win.BUILTIN_ROUTES || [])
        .filter(function(r) {
          return r && typeof r.path === "string" && typeof r.mode === "string";
        });
    };

    const all = getActiveTenantRoutes();
    const overridePath = routeOverride(id, groupName);
    if (overridePath && all.some(function(r) { return r.path === overridePath; })) {
      navigate(overridePath);
      return;
    }

    // If a route exists at the literal /<targetMode>/<id> path, prefer it.
    const directPath = "/" + targetMode + "/" + id;
    const direct = all.find(function(r) { return r.path === directPath; });
    if (direct) { navigate(directPath); return; }

    const matches = all.filter(function(r) {
      const segs = r.path.split("/").filter(Boolean);
      // match if id is the last segment (e.g. "approvals" → /build/approvals)
      // OR the first segment / mode root (e.g. "line" → /line/queue, "auditor" → /auditor/ledger)
      return segs[segs.length - 1] === id || segs[0] === id;
    });

    if (matches.length === 0) {
      navigate(directPath);
      return;
    }

    const preferred = matches.find(function(r) { return r.mode === targetMode; }) || matches[0];
    navigate(preferred.path);
  };

  const breadcrumbs = uASM(function() {
    const parts = String(screenId || "").split("/").filter(Boolean);
    return parts.length ? parts : ["forge", "landing"];
  }, [screenId]);

  // Use the existing WorkshopDrawer (defined in workshop.jsx, already in global scope)
  const Drawer = (typeof WorkshopDrawer !== "undefined") ? WorkshopDrawer : null;

  return (
    <div
      style={{
        display: "flex",
        height: "100vh",
        width: "100%",
        background: "var(--bg-1, #fff)",
        color: "var(--ink-1, oklch(0.16 0.01 85))",
        fontFamily: "var(--font-ui)",
      }}
    >
      <Sidebar nav={nav} current={current} onPick={onPick} />
      <main style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, overflow: "hidden" }}>
        <Topbar mode={mode} breadcrumbs={breadcrumbs} onOpenWorkshop={function() { setWorkshopOpen(true); }} />
        <section
          style={{
            flex: 1,
            overflow: "auto",
            background: "var(--bg-1, #fff)",
            position: "relative",
          }}
        >
          {children}
        </section>
      </main>
      {Drawer && (
        <Drawer
          open={workshopOpen}
          mode={mode}
          onClose={function() { setWorkshopOpen(false); }}
          onPlan={function() {}}
          onStrike={function() {}}
        />
      )}
      {toasts.length > 0 && (
        <div style={{ position: "fixed", left: 16, bottom: 16, zIndex: 2000, display: "flex", flexDirection: "column-reverse", gap: 8, pointerEvents: "none" }}>
          {toasts.map(function(t) {
            return (
              <div
                key={t.id}
                style={{
                  minWidth: 220,
                  maxWidth: 380,
                  background: "var(--bg-1, #fff)",
                  border: "1px solid var(--line-strong, oklch(0.72 0.008 85))",
                  borderLeft: "2px solid var(--accent, oklch(0.74 0.17 55))",
                  borderRadius: 6,
                  boxShadow: "0 8px 24px rgba(0,0,0,0.10)",
                  padding: "10px 12px",
                  fontFamily: "var(--font-ui)",
                  fontSize: 12.5,
                  lineHeight: 1.4,
                  color: "var(--ink-1, oklch(0.16 0.01 85))",
                }}
              >
                {t.msg}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ---------------- NotFound ----------------
function NotFound({ path }) {
  const _notFoundLabelStyle = {
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    letterSpacing: "0.10em",
    textTransform: "uppercase",
    color: "var(--ink-3, oklch(0.46 0.01 85))",
    marginBottom: 12,
  };
  const _notFoundCtaStyle = {
    height: 32,
    padding: "0 14px",
    borderRadius: 4,
    background: "var(--accent, oklch(0.55 0.18 250))",
    border: 0,
    color: "#fff",
    fontFamily: "var(--font-ui)",
    fontSize: 13,
    cursor: "pointer",
  };
  return (
    <div
      style={{
        padding: 40,
        fontFamily: "var(--font-ui)",
        color: "var(--ink-1, oklch(0.16 0.01 85))",
      }}
    >
      <div style={_notFoundLabelStyle}>
        404 · screen not registered
      </div>
      <div style={{ fontFamily: "var(--font-serif)", fontSize: 32, lineHeight: 1.15, marginBottom: 8 }}>
        no screen at <span style={{ fontFamily: "var(--font-mono)", fontSize: 22 }}>{path || "—"}</span>
      </div>
      <div style={{ color: "var(--ink-3, oklch(0.46 0.01 85))", marginBottom: 24, maxWidth: 560 }}>
        This route hasn't been registered yet. It may be a wave-2 screen still being built, or the path may be misspelled.
      </div>
      <button
        onClick={function() { if (typeof navigate === "function") navigate("/forge/dashboard"); }}
        style={_notFoundCtaStyle}
      >
        go to dashboard
      </button>
    </div>
  );
}

if (typeof window !== "undefined") {
  window.ModeBadge      = ModeBadge;
  window.TenantSwitcher = TenantSwitcher;
  window.Sidebar        = Sidebar;
  window.Topbar         = Topbar;
  window.AppShell       = AppShell;
  window.NotFound       = NotFound;
}
