// Sidebar.jsx — primary dashboard navigation
(function () {
  const h = React.createElement;
  const NAV = window.NAV;
  const { can, denyReason } = window.EmplixPermissions;

  function Sidebar({ active, setActive, role, open, pending, hiredCount }) {
    const mobileQuery = "(max-width: 800px)";
    const [isMobile, setIsMobile] = React.useState(() => window.matchMedia && window.matchMedia(mobileQuery).matches);
    const sidebarRef = React.useRef(null);
    React.useEffect(() => {
      if (!window.matchMedia) return undefined;
      const query = window.matchMedia(mobileQuery);
      const sync = () => setIsMobile(query.matches);
      sync();
      if (query.addEventListener) query.addEventListener("change", sync);
      else query.addListener(sync);
      return () => {
        if (query.removeEventListener) query.removeEventListener("change", sync);
        else query.removeListener(sync);
      };
    }, []);
    const hidden = isMobile && !open;
    React.useEffect(() => {
      if (!hidden || !sidebarRef.current || !sidebarRef.current.contains(document.activeElement)) return;
      const menuButton = document.querySelector('[data-nav-action="open"]');
      if (menuButton && menuButton.focus) menuButton.focus();
    }, [hidden]);
    return h("aside", { ref: sidebarRef, className: "app-sidebar" + (open ? " open" : ""), "data-nav-sidebar": "true", "data-nav-open": open ? "true" : "false", "data-nav-active": active || "",
      "aria-hidden": hidden ? "true" : undefined, inert: hidden ? "" : undefined,
      style: { width: "var(--sidebar-w)", flex: "none", height: "100vh", position: "sticky", top: 0,
      background: "var(--bg-2)", borderRight: "1px solid var(--border)", display: "flex", flexDirection: "column", zIndex: 60 } },
      // brand
      h("a", { href: "index.html", style: { display: "flex", alignItems: "center", gap: 11, padding: "0 18px", height: "var(--topbar-h)", borderBottom: "1px solid var(--border)", textDecoration: "none", color: "var(--text)" } },
        h("div", { style: { width: 32, height: 32, borderRadius: 9, background: "linear-gradient(135deg,#5aa2ff,#6438e8)", display: "grid", placeItems: "center", color: "#fff", boxShadow: "0 6px 14px -5px rgba(100,56,232,.6)" } },
          h(window.Icon, { name: "layers", size: 18 })),
        h("div", null,
          h("div", { style: { fontWeight: 700, fontSize: 16, letterSpacing: "-0.02em" } }, "Emplix"),
          h("div", { style: { fontSize: 10.5, color: "var(--text-faint)", fontFamily: "var(--mono)", letterSpacing: ".05em", marginTop: -1 } }, "SAMPLE BUSINESS"))),
      // nav
      h("nav", { style: { flex: 1, overflowY: "auto", padding: "12px 12px 20px" } },
        h("a", { href: "index.html", className: "nav-item", "data-nav-item": "landing", "data-nav-label": "Back to Landing",
          style: { width: "100%", display: "flex", alignItems: "center", gap: 11, padding: "9px 11px", marginBottom: 10, borderRadius: 9,
            textDecoration: "none", fontFamily: "var(--font)", fontSize: 13.5, fontWeight: 600,
            background: "var(--green-soft)", color: "var(--green)", border: "1px solid rgba(18,168,119,.2)" } },
          h(window.Icon, { name: "logout", size: 17, color: "currentColor", style: { transform: "rotate(180deg)" } }),
          h("span", { className: "grow" }, "Back to Landing")),
        NAV.filter((n) => !n.hidden).map((n, i, VIS) => {
          const showLabel = i === 0 || VIS[i - 1].section !== n.section;
          const labelPadding = i === 0 ? "10px 10px 8px" : "14px 10px 8px";
          if (showLabel) return h(React.Fragment, { key: "sec" + n.id },
            h("div", { style: { fontSize: 10, fontWeight: 700, letterSpacing: ".12em", color: "var(--text-faint)", padding: labelPadding } }, n.section),
            navItem(n, active, setActive, role, pending));
          return navItem(n, active, setActive, role, pending);
        }),
        h("div", { className: "sidebar-mobile-lang", style: { marginTop: 14, padding: "14px 10px", borderTop: "1px solid var(--border)" } },
          h("div", { style: { fontSize: 10, fontWeight: 700, letterSpacing: ".12em", color: "var(--text-faint)", marginBottom: 10 } }, "LANGUAGE"),
          h(window.LangToggle))),
      // footer card
      h("div", { style: { padding: 12 } },
        h("div", { style: { background: "var(--bg-3)", border: "1px solid var(--border)", borderRadius: 12, padding: "12px 14px" } },
          h("div", { className: "row gap8", style: { marginBottom: 6 } }, h("span", { className: "live-dot" }), h("span", { style: { fontSize: 12, fontWeight: 600 } }, "Sample demo ready")),
          h("div", { style: { fontSize: 11.5, color: "var(--text-faint)", lineHeight: 1.4 } },
            h("span", null, "Owner view"), " · ",
            h("span", null, (hiredCount || 0)), " ", h("span", null, "active roles"), " · ",
            pending > 0
              ? h("span", null, "Approvals waiting: " + pending)
              : h("span", null, "none pending"),
            ". ",
            h("span", null, "Floor View is for daily work.")))));
  }

  function navItem(n, active, setActive, role, pending) {
    // hidden child screens (e.g. #employee/<roleId>) light up their listed parent.
    const PARENT = { employee: "employees", agent: "training", "training-setup": "training", workorder: "workorders", connector: "connectors", "audit-event": "audit", incident: "health" };
    const effActive = PARENT[active] || active;
    const isActive = effActive === n.id;
    // live Approval Desk badge — mirrors the floor dock-badge (rendered only when > 0).
    const badge = n.id === "approvals" ? pending : n.badge;
    // builder/ops screens are dimmed + locked (still navigable, never hidden) for
    // any level that cannot configure (everyone except owner).
    const dim = n.fde && !can(role, "configure");
    return h("button", { key: n.id, onClick: () => setActive(n.id),
      title: dim ? denyReason(role, "configure") : undefined,
      "data-nav-item": n.id,
      "data-nav-label": n.label,
      "data-nav-active": isActive ? "true" : "false",
      "data-nav-dimmed": dim ? "true" : "false",
      "data-nav-section": n.section || "",
      className: "nav-item" + (isActive ? " active" : ""),
      style: { width: "100%", display: "flex", alignItems: "center", gap: 11, padding: "9px 11px", marginBottom: 2, borderRadius: 9,
        border: "none", cursor: "pointer", textAlign: "left", fontFamily: "var(--font)", fontSize: 13.5, fontWeight: isActive ? 600 : 500,
        background: isActive ? "var(--blue-soft)" : "transparent", color: isActive ? "var(--blue-deep)" : (dim ? "var(--text-faint)" : "var(--text-dim)"),
        position: "relative", opacity: dim ? 0.7 : 1 } },
      isActive && h("span", { style: { position: "absolute", left: 0, top: 8, bottom: 8, width: 3, borderRadius: 3, background: "var(--blue)" } }),
      h(window.Icon, { name: n.icon, size: 17, color: isActive ? "var(--blue)" : "currentColor" }),
      h("span", { className: "grow" }, n.label),
      badge > 0 && h("span", { title: "Approvals waiting: " + badge, "aria-label": "Approvals waiting: " + badge,
        style: { fontSize: 10.5, fontWeight: 700, minWidth: 18, height: 18, padding: "0 5px", borderRadius: 9, display: "grid", placeItems: "center",
        background: "var(--amber-soft)", color: "#a8690a" } }, badge),
      dim && h(window.Icon, { name: "lock", size: 12, color: "var(--text-faint)" }));
  }

  window.Sidebar = Sidebar;
})();
