"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { createContext, useContext } from "react";
import Link from "next/link";
import Image from "next/image";
import { ChevronDown, ChevronLeft, Home, PanelLeftClose, PanelLeftOpen, X } from "lucide-react";
import { Button } from "../primitives/button.js";
import {
  Breadcrumb as BreadcrumbNav,
  BreadcrumbEllipsis,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator
} from "../primitives/breadcrumb.js";
import { IconButton } from "../primitives/icon-button.js";
import { SearchInput } from "../primitives/search-input.js";
import { FlashMessages } from "./FlashMessages.js";
import { QueryProvider } from "../theme/QueryProvider.js";
import { usePathname, useSearchParams } from "next/navigation";
import { LastOperationBanner } from "./operations/LastOperationBanner.js";
import { ProgressTopBar } from "./progress/ProgressTopBar.js";
import { UpgradeActionBanner } from "./upgrades/UpgradeActionBanner.js";
import { PartialIndexBanner } from "./indexes/PartialIndexBanner.js";
import { useLocale, useT } from "@open-mercato/shared/lib/i18n/context";
import { slugifySidebarId } from "@open-mercato/shared/modules/navigation/sidebarPreferences";
import { cloneSidebarGroups } from "./sidebar/customization-helpers.js";
import { InjectionSpot } from "./injection/InjectionSpot.js";
import { LEGACY_GLOBAL_MUTATION_INJECTION_SPOT_ID } from "./injection/mutationEvents.js";
import { mergeMenuItems } from "./injection/mergeMenuItems.js";
import { useInjectedMenuItems } from "./injection/useInjectedMenuItems.js";
import { resolveInjectedIcon } from "./injection/resolveInjectedIcon.js";
import { useEventBridge } from "./injection/eventBridge.js";
import { StatusBadgeInjectionSpot } from "./injection/StatusBadgeInjectionSpot.js";
import { UmesDevToolsPanel } from "./devtools/index.js";
import { AiDockProvider } from "../ai/AiDock.js";
import { AiChatSessionsProvider } from "../ai/AiChatSessions.js";
import { AiAssistantLauncher } from "../ai/AiAssistantLauncher.js";
import { BackendChromeProvider, useBackendChrome } from "./BackendChromeProvider.js";
import {
  BACKEND_LAYOUT_FOOTER_INJECTION_SPOT_ID,
  BACKEND_LAYOUT_TOP_INJECTION_SPOT_ID,
  BACKEND_RECORD_CURRENT_INJECTION_SPOT_ID,
  BACKEND_SIDEBAR_FOOTER_INJECTION_SPOT_ID,
  BACKEND_SIDEBAR_TOP_INJECTION_SPOT_ID,
  BACKEND_SIDEBAR_NAV_FOOTER_INJECTION_SPOT_ID,
  BACKEND_SIDEBAR_NAV_INJECTION_SPOT_ID,
  BACKEND_TOPBAR_ACTIONS_INJECTION_SPOT_ID,
  GLOBAL_HEADER_STATUS_INDICATORS_INJECTION_SPOT_ID,
  GLOBAL_SIDEBAR_STATUS_BADGES_INJECTION_SPOT_ID
} from "./injection/spotIds.js";
function convertInjectedMenuItemToSidebarItem(item, title) {
  if (!item.href) return null;
  return {
    id: item.id,
    href: item.href,
    title,
    defaultTitle: title,
    icon: resolveInjectedIcon(item.icon) ?? void 0,
    iconName: item.icon,
    enabled: true,
    hidden: false,
    pageContext: "main"
  };
}
function resolveInjectedMenuLabel(item, t) {
  if (item.labelKey && item.label) return t(item.labelKey, item.label);
  if (item.labelKey) return t(item.labelKey, item.id);
  if (item.label && item.label.includes(".")) return t(item.label, item.id);
  return item.label ?? item.id;
}
function mergeSidebarItemsWithInjected(items, injectedItems, t) {
  if (injectedItems.length === 0) return items;
  const builtInById = /* @__PURE__ */ new Map();
  for (const item of items) {
    builtInById.set(item.id ?? item.href, item);
  }
  const merged = mergeMenuItems(
    items.map((item) => ({
      id: item.id ?? item.href
    })),
    injectedItems
  );
  const result = [];
  for (const entry of merged) {
    if (entry.source === "built-in") {
      const original = builtInById.get(entry.id);
      if (original) result.push(original);
      continue;
    }
    const translatedLabel = resolveInjectedMenuLabel(
      { id: entry.id, label: entry.label, labelKey: entry.labelKey },
      t
    );
    const converted = convertInjectedMenuItemToSidebarItem(
      {
        id: entry.id,
        label: translatedLabel,
        icon: entry.icon,
        href: entry.href
      },
      translatedLabel
    );
    if (converted) result.push(converted);
  }
  return result;
}
function mergeSidebarGroupsWithInjected(groups, injectedItems, t) {
  if (injectedItems.length === 0) return groups;
  const injectedByGroup = /* @__PURE__ */ new Map();
  const ungrouped = [];
  for (const item of injectedItems) {
    if (item.groupId && item.groupId.trim().length > 0) {
      const groupItems = injectedByGroup.get(item.groupId) ?? [];
      groupItems.push(item);
      injectedByGroup.set(item.groupId, groupItems);
      continue;
    }
    ungrouped.push(item);
  }
  const nextGroups = groups.map((group, index) => {
    const groupId = group.id || resolveGroupKey(group);
    const groupInjected = [
      ...injectedByGroup.get(groupId) ?? [],
      ...index === 0 ? ungrouped : []
    ];
    return {
      ...group,
      items: mergeSidebarItemsWithInjected(group.items, groupInjected, t)
    };
  });
  const existingIds = new Set(nextGroups.map((group) => group.id || resolveGroupKey(group)));
  for (const [groupId, items] of injectedByGroup.entries()) {
    if (existingIds.has(groupId)) continue;
    const first = items[0];
    const label = first.groupLabelKey ? t(first.groupLabelKey, first.groupLabel ?? groupId) : first.groupLabel ?? groupId;
    const groupItems = mergeSidebarItemsWithInjected([], items, t);
    if (groupItems.length === 0) continue;
    nextGroups.push({
      id: groupId,
      name: label,
      defaultName: label,
      items: groupItems
    });
  }
  return nextGroups;
}
function mergeSectionGroupsWithInjected(sections, injectedItems, t) {
  if (injectedItems.length === 0) return sections;
  const byGroup = /* @__PURE__ */ new Map();
  for (const item of injectedItems) {
    const groupId = item.groupId && item.groupId.trim().length > 0 ? item.groupId : "injected";
    const bucket = byGroup.get(groupId) ?? [];
    bucket.push(item);
    byGroup.set(groupId, bucket);
  }
  const nextSections = sections.map((section) => {
    const sectionItems = byGroup.get(section.id) ?? [];
    if (sectionItems.length === 0) return section;
    const mergedItems = mergeMenuItems(
      section.items.map((item) => ({ id: item.id, item })),
      sectionItems
    ).flatMap((item) => {
      if (item.source === "built-in") {
        const original = section.items.find((entry) => entry.id === item.id);
        return original ? [original] : [];
      }
      if (!item.href) return [];
      const label = resolveInjectedMenuLabel(item, t);
      return [{
        id: item.id,
        label,
        href: item.href,
        icon: resolveInjectedIcon(item.icon) ?? void 0
      }];
    });
    return {
      ...section,
      items: mergedItems
    };
  });
  for (const [sectionId, sectionItems] of byGroup.entries()) {
    const exists = nextSections.some((section) => section.id === sectionId);
    if (exists) continue;
    const first = sectionItems[0];
    const label = first.groupLabelKey ? t(first.groupLabelKey, first.groupLabel ?? sectionId) : first.groupLabel ?? sectionId;
    const items = sectionItems.flatMap((item) => {
      if (!item.href) return [];
      const itemLabel = resolveInjectedMenuLabel(item, t);
      return [{
        id: item.id,
        label: itemLabel,
        href: item.href,
        icon: resolveInjectedIcon(item.icon) ?? void 0
      }];
    });
    if (items.length === 0) continue;
    nextSections.push({ id: sectionId, label, items });
  }
  return nextSections;
}
function resolveGroupKey(group) {
  if (group.id && group.id.length) return group.id;
  if (group.defaultName && group.defaultName.length) return slugifySidebarId(group.defaultName);
  return slugifySidebarId(group.name);
}
function resolveItemKey(item) {
  const candidate = item.id?.trim();
  if (candidate && candidate.length > 0) return candidate;
  return item.href;
}
function SerializedIcon({ markup }) {
  return /* @__PURE__ */ jsx("span", { "aria-hidden": "true", dangerouslySetInnerHTML: { __html: markup } });
}
function renderIcon(icon, iconName, iconMarkup, fallback) {
  if (icon) return icon;
  if (iconName) {
    const resolved = resolveInjectedIcon(iconName);
    if (resolved) return resolved;
  }
  if (iconMarkup) return /* @__PURE__ */ jsx(SerializedIcon, { markup: iconMarkup });
  return fallback;
}
const HeaderContext = createContext(null);
function ApplyBreadcrumb({ breadcrumb, title, titleKey }) {
  const ctx = useContext(HeaderContext);
  const t = useT();
  const resolvedBreadcrumb = React.useMemo(() => {
    if (!breadcrumb) return void 0;
    return breadcrumb.map(({ label, labelKey, href }) => {
      const translated = labelKey ? t(labelKey) : void 0;
      const finalLabel = translated && translated !== labelKey ? translated : label;
      return {
        href,
        label: finalLabel
      };
    });
  }, [breadcrumb, t]);
  const resolvedTitle = React.useMemo(() => {
    if (!titleKey) return title;
    const translated = t(titleKey);
    if (translated && translated !== titleKey) return translated;
    return title;
  }, [titleKey, title, t]);
  React.useEffect(() => {
    ctx?.setBreadcrumb(resolvedBreadcrumb);
    if (resolvedTitle !== void 0) ctx?.setTitle(resolvedTitle);
  }, [ctx, resolvedBreadcrumb, resolvedTitle]);
  return null;
}
const DefaultIcon = /* @__PURE__ */ jsxs("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: [
  /* @__PURE__ */ jsx("path", { d: "M8 6h13M8 12h13M8 18h13" }),
  /* @__PURE__ */ jsx("path", { d: "M3 6h.01M3 12h.01M3 18h.01" })
] });
const DataTableIcon = /* @__PURE__ */ jsxs("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: [
  /* @__PURE__ */ jsx("rect", { x: "3", y: "4", width: "18", height: "16", rx: "2", ry: "2" }),
  /* @__PURE__ */ jsx("line", { x1: "3", y1: "8", x2: "21", y2: "8" }),
  /* @__PURE__ */ jsx("line", { x1: "9", y1: "8", x2: "9", y2: "20" }),
  /* @__PURE__ */ jsx("line", { x1: "15", y1: "8", x2: "15", y2: "20" })
] });
const CustomizeIcon = /* @__PURE__ */ jsxs("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: [
  /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "3" }),
  /* @__PURE__ */ jsx("path", { d: "M19.4 15a1.65 1.65 0 0 0 .33 1.82l.05.05a2 2 0 1 1-2.83 2.83l-.05-.05A1.65 1.65 0 0 0 15 19.4a1.65 1.65 0 0 0-1 .6 1.65 1.65 0 0 0-.33 1.82l-.05.05a2 2 0 1 1-2.83-2.83l.05-.05A1.65 1.65 0 0 0 9 15a1.65 1.65 0 0 0-1-.6 1.65 1.65 0 0 0-1.82.33l-.05.05a2 2 0 1 1-2.83-2.83l.05-.05A1.65 1.65 0 0 0 4.6 9 1.65 1.65 0 0 0 4 8a1.65 1.65 0 0 0-.6-1.82l-.05-.05a2 2 0 1 1 2.83-2.83l.05.05A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-.6 1.65 1.65 0 0 0 .33-1.82l.05-.05a2 2 0 1 1 2.83 2.83l-.05.05A1.65 1.65 0 0 0 15 9a1.65 1.65 0 0 0 1 .6 1.65 1.65 0 0 0 1.82-.33l.05-.05a2 2 0 1 1 2.83 2.83l-.05.05A1.65 1.65 0 0 0 19.4 15z" })
] });
const BackArrowIcon = /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx("path", { d: "M19 12H5M12 19l-7-7 7-7" }) });
function Chevron({ open }) {
  return /* @__PURE__ */ jsx("svg", { className: `transition-transform ${open ? "rotate-180" : ""}`, width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: /* @__PURE__ */ jsx("path", { d: "M6 9l6 6 6-6" }) });
}
function AppShell(props) {
  return /* @__PURE__ */ jsx(QueryProvider, { children: /* @__PURE__ */ jsx(BackendChromeProvider, { adminNavApi: props.adminNavApi, children: /* @__PURE__ */ jsx(AiChatSessionsProvider, { children: /* @__PURE__ */ jsx(AiDockProvider, { children: /* @__PURE__ */ jsx(AppShellBody, { ...props }) }) }) }) });
}
function AppShellBody({ productName, logo, email, groups, rightHeaderSlot, children, sidebarCollapsedDefault = false, currentTitle, breadcrumb, version, settingsSectionTitle, settingsPathPrefixes = [], settingsSections, profileSections, profileSectionTitle, profilePathPrefixes = [], mobileSidebarSlot }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const t = useT();
  const locale = useLocale();
  const { payload: chromePayload, isReady: isChromeReady, isLoading: isChromeLoading } = useBackendChrome();
  const resolvedGroups = React.useMemo(
    () => cloneSidebarGroups(chromePayload?.groups ?? groups),
    [chromePayload?.groups, groups]
  );
  const resolvedSettingsSections = chromePayload?.settingsSections ?? settingsSections;
  const resolvedSettingsPathPrefixes = chromePayload?.settingsPathPrefixes ?? settingsPathPrefixes;
  const resolvedProfileSections = chromePayload?.profileSections ?? profileSections;
  const resolvedProfilePathPrefixes = chromePayload?.profilePathPrefixes ?? profilePathPrefixes;
  const { items: mainSidebarInjectedMenuItems } = useInjectedMenuItems("menu:sidebar:main");
  const { items: settingsSidebarInjectedMenuItems } = useInjectedMenuItems("menu:sidebar:settings");
  const { items: profileSidebarInjectedMenuItems } = useInjectedMenuItems("menu:sidebar:profile");
  const { items: topbarInjectedMenuItems } = useInjectedMenuItems("menu:topbar:actions");
  useEventBridge();
  const resolvedProductName = productName ?? t("appShell.productName");
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [mobileDrawerView, setMobileDrawerView] = React.useState("auto");
  React.useEffect(() => {
    if (!mobileOpen) setMobileDrawerView("auto");
  }, [mobileOpen]);
  const [collapsed, setCollapsed] = React.useState(sidebarCollapsedDefault);
  const [navGroups, setNavGroups] = React.useState(resolvedGroups);
  const [openGroups, setOpenGroups] = React.useState(
    () => Object.fromEntries(resolvedGroups.map((g) => [resolveGroupKey(g), true]))
  );
  const [headerTitle, setHeaderTitle] = React.useState(currentTitle);
  const [headerBreadcrumb, setHeaderBreadcrumb] = React.useState(breadcrumb);
  const [navQuery, setNavQuery] = React.useState("");
  const navQueryNorm = navQuery.trim().toLowerCase();
  const navQueryActive = navQueryNorm.length > 0;
  const matchesQuery = React.useCallback((label) => {
    if (!navQueryActive) return true;
    if (!label) return false;
    return label.toLowerCase().includes(navQueryNorm);
  }, [navQueryActive, navQueryNorm]);
  const effectiveCollapsed = collapsed;
  const expandedSidebarWidth = "240px";
  const sidebarAsideRef = React.useRef(null);
  const [sidebarScrollState, setSidebarScrollState] = React.useState("down");
  const sidebarScrollIntentRef = React.useRef(null);
  const handleSidebarChevronScroll = React.useCallback((target) => {
    const aside = sidebarAsideRef.current;
    if (!aside) return;
    const scrollTarget = aside.querySelector('[data-sidebar-scroll="true"]');
    if (!scrollTarget) return;
    const prefersReducedMotion = typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const behavior = prefersReducedMotion ? "auto" : "smooth";
    const maxScrollTop = Math.max(0, scrollTarget.scrollHeight - scrollTarget.clientHeight);
    if (maxScrollTop <= 1) {
      sidebarScrollIntentRef.current = null;
      setSidebarScrollState("none");
      return;
    }
    sidebarScrollIntentRef.current = target;
    setSidebarScrollState(target === "bottom" ? "up" : "down");
    scrollTarget.scrollTo({
      top: target === "top" ? 0 : maxScrollTop,
      behavior
    });
  }, []);
  React.useEffect(() => {
    const aside = sidebarAsideRef.current;
    if (!aside) return;
    const target = aside.querySelector('[data-sidebar-scroll="true"]');
    if (!target) return;
    const update = () => {
      const { scrollTop, scrollHeight, clientHeight } = target;
      const canScroll = scrollHeight > clientHeight + 1;
      if (!canScroll) {
        sidebarScrollIntentRef.current = null;
        setSidebarScrollState("none");
        return;
      }
      const maxScrollTop = Math.max(0, scrollHeight - clientHeight);
      const atTop = scrollTop <= 8;
      const atBottom = scrollTop >= maxScrollTop - 8;
      const scrollIntent = sidebarScrollIntentRef.current;
      if (scrollIntent === "bottom") {
        if (atBottom) sidebarScrollIntentRef.current = null;
        setSidebarScrollState("up");
        return;
      }
      if (scrollIntent === "top") {
        if (atTop) sidebarScrollIntentRef.current = null;
        setSidebarScrollState("down");
        return;
      }
      setSidebarScrollState(atBottom ? "up" : "down");
    };
    update();
    target.addEventListener("scroll", update, { passive: true });
    const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(update) : null;
    ro?.observe(target);
    return () => {
      target.removeEventListener("scroll", update);
      ro?.disconnect();
    };
  }, [pathname, effectiveCollapsed]);
  const injectionContext = React.useMemo(
    () => ({
      path: pathname ?? "",
      query: searchParams?.toString() ?? ""
    }),
    [pathname, searchParams]
  );
  const isOnSettingsPath = React.useMemo(() => {
    if (!pathname) return false;
    if (pathname === "/backend/settings") return true;
    return resolvedSettingsPathPrefixes.some((prefix) => pathname.startsWith(prefix));
  }, [pathname, resolvedSettingsPathPrefixes]);
  const isOnProfilePath = React.useMemo(() => {
    if (!pathname) return false;
    if (pathname === "/backend/profile") return true;
    return resolvedProfilePathPrefixes.some((prefix) => pathname.startsWith(prefix));
  }, [pathname, resolvedProfilePathPrefixes]);
  const sidebarMode = isOnSettingsPath ? "settings" : isOnProfilePath ? "profile" : "main";
  const mainNavGroupsWithInjected = React.useMemo(
    () => mergeSidebarGroupsWithInjected(navGroups, mainSidebarInjectedMenuItems, t),
    [mainSidebarInjectedMenuItems, navGroups, t]
  );
  React.useEffect(() => {
    if (!mobileOpen || typeof document === "undefined") return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [mobileOpen]);
  React.useEffect(() => {
    try {
      const savedOpen = typeof window !== "undefined" ? localStorage.getItem("om:sidebarOpenGroups") : null;
      if (!savedOpen) return;
      const parsed = JSON.parse(savedOpen);
      setOpenGroups((prev) => {
        const next = { ...prev };
        for (const group of resolvedGroups) {
          const key = resolveGroupKey(group);
          if (key in parsed) next[key] = !!parsed[key];
          else if (group.name in parsed) next[key] = !!parsed[group.name];
        }
        return next;
      });
    } catch {
    }
  }, [resolvedGroups]);
  const toggleGroup = (groupId) => setOpenGroups((prev) => ({ ...prev, [groupId]: prev[groupId] === false }));
  const asideWidth = effectiveCollapsed ? "80px" : expandedSidebarWidth;
  const asideClassesBase = `border-r bg-background py-4`;
  React.useEffect(() => {
    try {
      localStorage.setItem("om:sidebarCollapsed", collapsed ? "1" : "0");
    } catch {
    }
    try {
      document.cookie = `om_sidebar_collapsed=${collapsed ? "1" : "0"}; path=/; max-age=31536000; samesite=lax`;
    } catch {
    }
  }, [collapsed]);
  const collapsedBeforeSectionRef = React.useRef(null);
  const previousSidebarModeRef = React.useRef("main");
  React.useEffect(() => {
    const previous = previousSidebarModeRef.current;
    if (previous === "main" && sidebarMode !== "main") {
      collapsedBeforeSectionRef.current = collapsed;
      if (!collapsed) setCollapsed(true);
    } else if (previous !== "main" && sidebarMode === "main" && collapsedBeforeSectionRef.current !== null) {
      const restoreTo = collapsedBeforeSectionRef.current;
      collapsedBeforeSectionRef.current = null;
      if (collapsed !== restoreTo) setCollapsed(restoreTo);
    }
    previousSidebarModeRef.current = sidebarMode;
  }, [sidebarMode, collapsed]);
  React.useEffect(() => {
    try {
      localStorage.setItem("om:sidebarOpenGroups", JSON.stringify(openGroups));
    } catch {
    }
  }, [openGroups]);
  React.useEffect(() => {
    const activeGroup = navGroups.find((g) => g.items.some((i) => pathname?.startsWith(i.href)));
    if (!activeGroup) return;
    const key = resolveGroupKey(activeGroup);
    setOpenGroups((prev) => prev[key] === false ? { ...prev, [key]: true } : prev);
  }, [pathname, navGroups]);
  React.useEffect(() => {
    setHeaderTitle(currentTitle);
    setHeaderBreadcrumb(breadcrumb);
  }, [currentTitle, breadcrumb]);
  const prevPathname = React.useRef(pathname);
  React.useEffect(() => {
    if (pathname !== prevPathname.current) {
      prevPathname.current = pathname;
      setHeaderTitle(void 0);
      setHeaderBreadcrumb(void 0);
    }
  }, [pathname]);
  React.useEffect(() => {
    setNavGroups(cloneSidebarGroups(resolvedGroups));
  }, [resolvedGroups]);
  function renderSectionSidebar(sections, title, compact, hideHeader, hideSearch) {
    const sortedSections = [...sections].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
    const lastVisibleIndex = sortedSections.length - 1;
    return /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col gap-3", children: [
      !hideHeader && /* @__PURE__ */ jsx("div", { className: "mb-2", children: /* @__PURE__ */ jsxs(
        Link,
        {
          href: "/backend",
          className: `flex items-center gap-3 rounded-xl transition-colors hover:bg-muted ${compact ? "p-2 justify-center" : "p-3"}`,
          "aria-label": t("appShell.goToDashboard"),
          children: [
            /* @__PURE__ */ jsx(Image, { src: logo?.src ?? "/open-mercato.svg", alt: logo?.alt ?? resolvedProductName, width: 40, height: 40, className: "rounded-full shrink-0" }),
            !compact && /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-medium text-foreground", children: resolvedProductName })
          ]
        }
      ) }),
      !compact && !hideSearch && /* @__PURE__ */ jsx(
        SearchInput,
        {
          value: navQuery,
          onChange: setNavQuery,
          placeholder: t("appShell.searchNavPlaceholder", "Search..."),
          "aria-label": t("appShell.searchNavAria", "Search navigation"),
          clearLabel: t("appShell.searchNavClear", "Clear search"),
          className: "mb-2"
        }
      ),
      /* @__PURE__ */ jsx("div", { "data-sidebar-scroll": "true", className: `flex flex-1 flex-col gap-3 overflow-y-auto scrollbar-hide pr-1 ${compact ? "-ml-2 pl-2" : "-ml-3 pl-3"}`, children: /* @__PURE__ */ jsx("nav", { className: "flex flex-col gap-2", children: sortedSections.map((section, sectionIndex) => {
        const sectionNavQueryActive = hideSearch ? false : navQueryActive;
        const matchesItemQuery = (item) => {
          if (!sectionNavQueryActive) return true;
          const label = item.labelKey ? t(item.labelKey, item.label) : item.label;
          if (matchesQuery(label)) return true;
          return Array.isArray(item.children) && item.children.some(matchesItemQuery);
        };
        const visibleItems = sectionNavQueryActive ? section.items.filter(matchesItemQuery) : section.items;
        if (visibleItems.length === 0) return null;
        const sortedItems = [...visibleItems].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
        const sectionLabel = section.labelKey ? t(section.labelKey, section.label) : section.label;
        const sectionKey = `settings:${section.id}`;
        const open = openGroups[sectionKey] !== false;
        const sortSectionItems = (items = []) => [...items].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
        const filterChildren = (children2) => {
          if (!children2) return [];
          if (!sectionNavQueryActive) return [...children2];
          return children2.filter(matchesItemQuery);
        };
        const renderSectionItem = (item, depth = 0) => {
          const label = item.labelKey ? t(item.labelKey, item.label) : item.label;
          const childItems = sortSectionItems(filterChildren(item.children));
          const isOnItemBranch = !!pathname && (pathname === item.href || pathname.startsWith(`${item.href}/`));
          const hasActiveChild = !!(pathname && childItems.some((child) => pathname === child.href || pathname.startsWith(`${child.href}/`)));
          const showChildren = childItems.length > 0 && (isOnItemBranch || sectionNavQueryActive);
          const isActive = isOnItemBranch || hasActiveChild;
          const base = compact ? "w-10 h-10 justify-center" : "w-full py-2 gap-2";
          const spacingStyle = !compact ? {
            paddingLeft: `${12 + depth * 16}px`,
            paddingRight: "12px"
          } : void 0;
          return /* @__PURE__ */ jsxs(React.Fragment, { children: [
            /* @__PURE__ */ jsxs(
              Link,
              {
                href: item.href,
                className: `relative text-sm font-medium rounded-lg inline-flex items-center ${base} ${isActive ? "bg-muted text-foreground" : "text-muted-foreground hover:bg-muted"}`,
                style: spacingStyle,
                title: compact ? label : void 0,
                "data-menu-item-id": item.id,
                onClick: () => setMobileOpen(false),
                children: [
                  isActive && /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: `absolute ${compact ? "left-[-20px]" : "left-[-12px]"} top-2 w-1 h-5 rounded-r bg-foreground` }),
                  /* @__PURE__ */ jsx("span", { className: "flex items-center justify-center shrink-0", children: renderIcon(
                    item.icon,
                    item.iconName,
                    item.iconMarkup,
                    item.href.includes("/backend/entities/user/") && item.href.endsWith("/records") ? DataTableIcon : DefaultIcon
                  ) }),
                  !compact && /* @__PURE__ */ jsx("span", { className: "truncate", children: label })
                ]
              }
            ),
            showChildren ? childItems.map((child) => renderSectionItem(child, depth + 1)) : null
          ] }, item.id);
        };
        return /* @__PURE__ */ jsxs("div", { children: [
          !compact && /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "muted",
              onClick: () => toggleGroup(sectionKey),
              className: "w-full px-1 justify-between flex text-xs font-medium uppercase tracking-wider text-muted-foreground/70 py-1",
              "aria-expanded": open,
              children: [
                /* @__PURE__ */ jsx("span", { children: sectionLabel }),
                /* @__PURE__ */ jsx(Chevron, { open })
              ]
            }
          ),
          (open || compact) && /* @__PURE__ */ jsx("div", { className: `flex flex-col ${compact ? "items-center" : ""} gap-1`, children: sortedItems.map((item) => renderSectionItem(item)) }),
          sectionIndex !== lastVisibleIndex && /* @__PURE__ */ jsx("div", { className: `my-2 border-t ${compact ? "-ml-2 -mr-3" : "-ml-3 -mr-4"}` })
        ] }, section.id);
      }) }) })
    ] });
  }
  function renderSidebar(compact, hideHeader, forceMainOnly) {
    if (!isChromeReady && isChromeLoading && resolvedGroups.length === 0) {
      return /* @__PURE__ */ jsxs("div", { className: "flex flex-col min-h-full gap-3", "data-testid": "backend-chrome-loading", children: [
        !hideHeader ? /* @__PURE__ */ jsx("div", { className: "mb-2", children: /* @__PURE__ */ jsxs(
          Link,
          {
            href: "/backend",
            className: `flex items-center gap-3 rounded-xl transition-colors hover:bg-muted ${compact ? "p-2 justify-center" : "p-3"}`,
            "aria-label": t("appShell.goToDashboard"),
            children: [
              /* @__PURE__ */ jsx(Image, { src: logo?.src ?? "/open-mercato.svg", alt: logo?.alt ?? resolvedProductName, width: 40, height: 40, className: "rounded-full shrink-0" }),
              !compact && /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-medium text-foreground", children: resolvedProductName })
            ]
          }
        ) }) : null,
        /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col gap-3 pr-1", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsx("div", { className: "h-8 rounded bg-muted/50" }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-2 pl-1", children: [
              /* @__PURE__ */ jsx("div", { className: "h-8 rounded bg-muted/50" }),
              /* @__PURE__ */ jsx("div", { className: "h-8 rounded bg-muted/50" }),
              /* @__PURE__ */ jsx("div", { className: "h-8 rounded bg-muted/50" })
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsx("div", { className: "h-8 rounded bg-muted/50" }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-2 pl-1", children: [
              /* @__PURE__ */ jsx("div", { className: "h-8 rounded bg-muted/50" }),
              /* @__PURE__ */ jsx("div", { className: "h-8 rounded bg-muted/50" })
            ] })
          ] })
        ] })
      ] });
    }
    if (!forceMainOnly && sidebarMode === "settings" && resolvedSettingsSections && resolvedSettingsSections.length > 0) {
      const mergedSettingsSections = mergeSectionGroupsWithInjected(
        resolvedSettingsSections,
        settingsSidebarInjectedMenuItems,
        t
      );
      return renderSectionSidebar(
        mergedSettingsSections,
        settingsSectionTitle ?? t("backend.nav.settings", "Settings"),
        compact,
        hideHeader
      );
    }
    if (!forceMainOnly && sidebarMode === "profile" && resolvedProfileSections && resolvedProfileSections.length > 0) {
      const mergedProfileSections = mergeSectionGroupsWithInjected(
        resolvedProfileSections,
        profileSidebarInjectedMenuItems,
        t
      );
      return renderSectionSidebar(
        mergedProfileSections,
        profileSectionTitle ?? t("backend.nav.profile", "Profile"),
        compact,
        hideHeader
      );
    }
    const isMobileVariant = !!hideHeader;
    const shouldRenderSidebarInjectionSpots = !isMobileVariant;
    return /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col gap-3", children: [
      !hideHeader && /* @__PURE__ */ jsx("div", { className: "mb-2", children: /* @__PURE__ */ jsxs(
        Link,
        {
          href: "/backend",
          className: `flex items-center gap-3 rounded-xl transition-colors hover:bg-muted ${compact ? "p-2 justify-center" : "p-3"}`,
          "aria-label": t("appShell.goToDashboard"),
          children: [
            /* @__PURE__ */ jsx(Image, { src: logo?.src ?? "/open-mercato.svg", alt: logo?.alt ?? resolvedProductName, width: 40, height: 40, className: "rounded-full shrink-0" }),
            !compact && /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-medium text-foreground", children: resolvedProductName })
          ]
        }
      ) }),
      shouldRenderSidebarInjectionSpots ? /* @__PURE__ */ jsx(
        InjectionSpot,
        {
          spotId: BACKEND_SIDEBAR_TOP_INJECTION_SPOT_ID,
          context: injectionContext
        }
      ) : null,
      !compact && /* @__PURE__ */ jsx(
        SearchInput,
        {
          value: navQuery,
          onChange: setNavQuery,
          placeholder: t("appShell.searchNavPlaceholder", "Search..."),
          "aria-label": t("appShell.searchNavAria", "Search navigation"),
          clearLabel: t("appShell.searchNavClear", "Clear search"),
          className: "mb-2"
        }
      ),
      /* @__PURE__ */ jsx("div", { "data-sidebar-scroll": "true", className: `flex flex-1 flex-col gap-3 overflow-y-auto scrollbar-hide pr-1 ${compact ? "-ml-2 pl-2" : "-ml-3 pl-3"}`, children: (() => {
        const isSettingsPath = (href) => {
          if (href === "/backend/settings") return true;
          return resolvedSettingsPathPrefixes.some((prefix) => href.startsWith(prefix));
        };
        const isMainItem = (item) => {
          if (item.pageContext && item.pageContext !== "main") return false;
          if (isSettingsPath(item.href)) return false;
          return true;
        };
        const mainGroups = mainNavGroupsWithInjected.map((g) => ({
          ...g,
          items: g.items.filter((item) => isMainItem(item) && item.hidden !== true)
        })).filter((g) => g.items.length > 0);
        const mainLastVisibleGroupIndex = (() => {
          for (let idx = mainGroups.length - 1; idx >= 0; idx -= 1) {
            if (mainGroups[idx].items.some((item) => item.hidden !== true)) return idx;
          }
          return -1;
        })();
        return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsxs("nav", { className: "flex flex-col gap-2", "data-testid": "sidebar", children: [
          shouldRenderSidebarInjectionSpots ? /* @__PURE__ */ jsx(
            InjectionSpot,
            {
              spotId: BACKEND_SIDEBAR_NAV_INJECTION_SPOT_ID,
              context: injectionContext
            }
          ) : null,
          mainGroups.map((g, gi) => {
            const groupId = resolveGroupKey(g);
            const open = navQueryActive ? true : openGroups[groupId] !== false;
            const visibleItems = g.items.filter((item) => {
              if (item.hidden === true) return false;
              if (!navQueryActive) return true;
              if (matchesQuery(item.title)) return true;
              const itemChildren = (item.children ?? []).filter((c) => c.hidden !== true);
              return itemChildren.some((c) => matchesQuery(c.title));
            });
            if (visibleItems.length === 0) return null;
            return /* @__PURE__ */ jsxs("div", { children: [
              !compact && /* @__PURE__ */ jsxs(
                Button,
                {
                  variant: "muted",
                  onClick: () => toggleGroup(groupId),
                  className: "w-full px-1 justify-between flex text-xs font-medium uppercase tracking-wider text-muted-foreground/70 py-1",
                  "aria-expanded": open,
                  children: [
                    /* @__PURE__ */ jsx("span", { children: g.name }),
                    /* @__PURE__ */ jsx(Chevron, { open })
                  ]
                }
              ),
              (open || compact) && /* @__PURE__ */ jsx("div", { className: `flex flex-col ${compact ? "items-center" : ""} gap-1`, children: visibleItems.map((i) => {
                const allChildItems = (i.children ?? []).filter((child) => child.hidden !== true);
                const matchingChildItems = navQueryActive ? allChildItems.filter((c) => matchesQuery(c.title)) : allChildItems;
                const childItems = navQueryActive ? matchingChildItems : allChildItems;
                const showChildren = navQueryActive ? matchingChildItems.length > 0 : !!pathname && allChildItems.length > 0 && pathname.startsWith(i.href);
                const hasActiveChild = !!(pathname && allChildItems.some((c) => pathname.startsWith(c.href)));
                const isParentActive = pathname === i.href || !navQueryActive && showChildren && !hasActiveChild;
                const base = compact ? "w-10 h-10 justify-center" : "w-full px-3 py-2 gap-2";
                return /* @__PURE__ */ jsxs(React.Fragment, { children: [
                  /* @__PURE__ */ jsxs(
                    Link,
                    {
                      href: i.href,
                      className: `relative text-sm font-medium rounded-lg inline-flex items-center ${base} ${isParentActive ? "bg-muted text-foreground" : "text-muted-foreground hover:bg-muted"} ${i.enabled === false ? "pointer-events-none opacity-50" : ""}`,
                      "aria-disabled": i.enabled === false,
                      title: compact ? i.title : void 0,
                      "data-menu-item-id": i.id ?? i.href,
                      onClick: () => setMobileOpen(false),
                      children: [
                        isParentActive ? /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: `absolute ${compact ? "left-[-20px]" : "left-[-12px]"} top-2 w-1 h-5 rounded-r bg-foreground` }) : null,
                        /* @__PURE__ */ jsx("span", { className: "flex items-center justify-center shrink-0", children: renderIcon(
                          i.icon,
                          i.iconName,
                          i.iconMarkup,
                          DefaultIcon
                        ) }),
                        !compact && /* @__PURE__ */ jsx("span", { children: i.title })
                      ]
                    }
                  ),
                  showChildren ? /* @__PURE__ */ jsxs("div", { className: `relative flex flex-col ${compact ? "items-center" : ""} gap-1`, children: [
                    !compact && /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: "pointer-events-none absolute left-1.5 top-1 bottom-1 w-px bg-border" }),
                    childItems.map((c) => {
                      const childActive = pathname?.startsWith(c.href);
                      const childBase = compact ? "w-10 h-8 justify-center" : "w-full pl-5 pr-3 py-2 gap-2";
                      return /* @__PURE__ */ jsxs(
                        Link,
                        {
                          href: c.href,
                          className: `relative text-sm font-medium rounded-lg inline-flex items-center ${childBase} ${childActive ? "bg-muted text-foreground" : "text-muted-foreground hover:bg-muted"} ${c.enabled === false ? "pointer-events-none opacity-50" : ""}`,
                          "aria-disabled": c.enabled === false,
                          title: compact ? c.title : void 0,
                          "data-menu-item-id": c.id ?? c.href,
                          onClick: () => setMobileOpen(false),
                          children: [
                            childActive ? /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: `absolute ${compact ? "left-[-20px]" : "left-[-12px]"} top-2 w-1 h-5 rounded-r bg-foreground` }) : null,
                            /* @__PURE__ */ jsx("span", { className: "flex items-center justify-center shrink-0", children: renderIcon(
                              c.icon,
                              c.iconName,
                              c.iconMarkup,
                              c.href.includes("/backend/entities/user/") && c.href.endsWith("/records") ? DataTableIcon : DefaultIcon
                            ) }),
                            !compact && /* @__PURE__ */ jsx("span", { children: c.title })
                          ]
                        },
                        c.href
                      );
                    })
                  ] }) : null
                ] }, i.href);
              }) }),
              gi !== mainLastVisibleGroupIndex && /* @__PURE__ */ jsx("div", { className: `my-2 border-t ${compact ? "-ml-2 -mr-3" : "-ml-3 -mr-4"}` })
            ] }, groupId);
          })
        ] }) });
      })() }),
      /* @__PURE__ */ jsxs("div", { className: "sticky bottom-0 bg-background pb-1", children: [
        shouldRenderSidebarInjectionSpots ? /* @__PURE__ */ jsx(
          InjectionSpot,
          {
            spotId: BACKEND_SIDEBAR_NAV_FOOTER_INJECTION_SPOT_ID,
            context: injectionContext
          }
        ) : null,
        shouldRenderSidebarInjectionSpots ? /* @__PURE__ */ jsx(
          StatusBadgeInjectionSpot,
          {
            spotId: GLOBAL_SIDEBAR_STATUS_BADGES_INJECTION_SPOT_ID,
            context: injectionContext
          }
        ) : null,
        shouldRenderSidebarInjectionSpots ? /* @__PURE__ */ jsx(
          InjectionSpot,
          {
            spotId: BACKEND_SIDEBAR_FOOTER_INJECTION_SPOT_ID,
            context: injectionContext
          }
        ) : null
      ] })
    ] });
  }
  function renderSectionAside() {
    let sections = null;
    let title = "";
    if (sidebarMode === "settings" && resolvedSettingsSections && resolvedSettingsSections.length > 0) {
      sections = mergeSectionGroupsWithInjected(
        resolvedSettingsSections,
        settingsSidebarInjectedMenuItems,
        t
      );
      title = settingsSectionTitle ?? t("backend.nav.settings", "Settings");
    } else if (sidebarMode === "profile" && resolvedProfileSections && resolvedProfileSections.length > 0) {
      sections = mergeSectionGroupsWithInjected(
        resolvedProfileSections,
        profileSidebarInjectedMenuItems,
        t
      );
      title = profileSectionTitle ?? t("backend.nav.profile", "Profile");
    }
    if (!sections) return null;
    return /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col gap-2", children: [
      /* @__PURE__ */ jsxs(
        Link,
        {
          href: "/backend",
          className: "inline-flex items-center gap-2 rounded-lg px-2 py-2 text-sm font-semibold text-foreground transition-colors hover:bg-muted",
          "data-testid": "appshell-section-back-to-main",
          "aria-label": t("backend.nav.backToMain", "Back to Main"),
          children: [
            /* @__PURE__ */ jsx(ChevronLeft, { className: "size-4 shrink-0", "aria-hidden": true }),
            /* @__PURE__ */ jsx("span", { className: "truncate", children: title })
          ]
        }
      ),
      /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1", children: renderSectionSidebar(sections, title, false, true, true) })
    ] });
  }
  const isSectionView = sidebarMode === "settings" && !!resolvedSettingsSections && resolvedSettingsSections.length > 0 || sidebarMode === "profile" && !!resolvedProfileSections && resolvedProfileSections.length > 0;
  const gridColsClass = isSectionView ? effectiveCollapsed ? "lg:grid-cols-[80px_240px_1fr]" : "lg:grid-cols-[240px_240px_1fr]" : effectiveCollapsed ? "lg:grid-cols-[80px_1fr]" : "lg:grid-cols-[240px_1fr]";
  const headerCtxValue = React.useMemo(() => ({
    setBreadcrumb: setHeaderBreadcrumb,
    setTitle: setHeaderTitle
  }), []);
  const renderedTopbarInjectedActions = React.useMemo(
    () => topbarInjectedMenuItems.map((item) => {
      const label = resolveInjectedMenuLabel(item, t);
      if (item.href) {
        return /* @__PURE__ */ jsx(
          Link,
          {
            href: item.href,
            className: "inline-flex items-center rounded border px-2 py-1 text-xs hover:bg-accent hover:text-accent-foreground",
            "data-menu-item-id": item.id,
            children: label
          },
          item.id
        );
      }
      return /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          "data-menu-item-id": item.id,
          onClick: () => item.onClick?.(),
          children: label
        },
        item.id
      );
    }),
    [t, topbarInjectedMenuItems]
  );
  return /* @__PURE__ */ jsxs(HeaderContext.Provider, { value: headerCtxValue, children: [
    /* @__PURE__ */ jsxs(
      "div",
      {
        className: `relative min-h-svh lg:grid transition-[grid-template-columns] duration-200 ease-out ${gridColsClass}`,
        style: { "--topbar-height": "61px" },
        children: [
          /* @__PURE__ */ jsx(
            "button",
            {
              type: "button",
              onClick: () => setCollapsed((c) => !c),
              "aria-label": t("appShell.toggleSidebar"),
              className: "hidden lg:flex fixed top-4 z-dropdown size-7 items-center justify-center rounded-md border bg-background text-muted-foreground shadow-sm transition-all hover:text-foreground hover:bg-muted focus:outline-none focus-visible:shadow-focus",
              style: { left: `calc(${asideWidth} - 14px)` },
              children: effectiveCollapsed ? /* @__PURE__ */ jsx(PanelLeftOpen, { className: "size-4" }) : /* @__PURE__ */ jsx(PanelLeftClose, { className: "size-4" })
            }
          ),
          /* @__PURE__ */ jsxs("aside", { ref: sidebarAsideRef, className: `${asideClassesBase} ${effectiveCollapsed ? "px-2" : "px-3"} hidden lg:block lg:sticky lg:top-0 lg:h-svh lg:self-start lg:overflow-hidden lg:relative transition-[width,padding] duration-200 ease-out`, style: { width: asideWidth }, children: [
            renderSidebar(effectiveCollapsed, false, isSectionView),
            sidebarScrollState !== "none" ? /* @__PURE__ */ jsx(
              "div",
              {
                className: "pointer-events-none absolute inset-x-0 bottom-0 flex h-10 items-end justify-center bg-gradient-to-t from-background via-background/80 to-transparent pb-1.5",
                children: /* @__PURE__ */ jsx(
                  IconButton,
                  {
                    type: "button",
                    variant: "ghost",
                    size: "sm",
                    "data-testid": "sidebar-scroll-chevron",
                    "data-sidebar-scroll-chevron": sidebarScrollState,
                    "aria-label": sidebarScrollState === "up" ? t("ui.sidebar.chevron.scrollTop", "Scroll to top") : t("ui.sidebar.chevron.scrollBottom", "Scroll to bottom"),
                    className: "pointer-events-auto text-muted-foreground/70 hover:text-foreground",
                    onClick: () => handleSidebarChevronScroll(sidebarScrollState === "up" ? "top" : "bottom"),
                    children: /* @__PURE__ */ jsx(
                      "span",
                      {
                        className: `inline-flex transition-transform duration-300 ${sidebarScrollState === "up" ? "rotate-180" : ""}`,
                        children: /* @__PURE__ */ jsx(ChevronDown, { className: "size-4 animate-bounce" })
                      }
                    )
                  }
                )
              }
            ) : null
          ] }),
          isSectionView ? /* @__PURE__ */ jsxs(
            "aside",
            {
              className: `${asideClassesBase} px-3 hidden lg:block lg:sticky lg:top-0 lg:h-svh lg:self-start lg:overflow-hidden lg:relative`,
              style: { width: "240px" },
              "data-testid": "appshell-section-sidebar",
              children: [
                renderSectionAside(),
                /* @__PURE__ */ jsx(
                  "div",
                  {
                    "aria-hidden": true,
                    className: "pointer-events-none absolute inset-x-0 bottom-0 h-10 bg-gradient-to-t from-background via-background/80 to-transparent"
                  }
                )
              ]
            }
          ) : null,
          /* @__PURE__ */ jsxs("div", { className: "flex min-h-svh flex-col min-w-0", children: [
            /* @__PURE__ */ jsxs("header", { className: "sticky top-0 z-sticky border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 px-3 sm:px-4 lg:px-6 py-3 flex items-center justify-between gap-2 sm:gap-3", children: [
              /* @__PURE__ */ jsx(
                "div",
                {
                  "data-testid": "backend-chrome-ready",
                  "data-ready": isChromeReady ? "true" : "false",
                  className: "hidden"
                }
              ),
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 min-w-0", children: [
                /* @__PURE__ */ jsx(IconButton, { variant: "ghost", size: "sm", className: "lg:hidden", "aria-label": t("appShell.openMenu"), onClick: () => setMobileOpen(true), children: /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: /* @__PURE__ */ jsx("path", { d: "M3 6h18M3 12h18M3 18h18" }) }) }),
                (() => {
                  const dashboardLabel = t("dashboard.title");
                  const root = [{ label: dashboardLabel, href: "/backend" }];
                  let rest = [];
                  if (headerBreadcrumb && headerBreadcrumb.length) {
                    const first = headerBreadcrumb[0];
                    const dup = first && (first.href === "/backend" || first.label === dashboardLabel || first.label?.toLowerCase() === "dashboard");
                    rest = dup ? headerBreadcrumb.slice(1) : headerBreadcrumb;
                  } else if (headerTitle) {
                    rest = [{ label: headerTitle }];
                  }
                  const items = [...root, ...rest];
                  if (items.length === 0) return null;
                  const home = items[0];
                  const current = items.length > 1 ? items[items.length - 1] : null;
                  const mid = items.slice(1, -1);
                  const hasMid = mid.length > 0;
                  return /* @__PURE__ */ jsx(BreadcrumbNav, { divider: "arrow", className: "ml-2 lg:ml-3 text-sm", children: /* @__PURE__ */ jsxs(BreadcrumbList, { className: "[&_[data-slot=breadcrumb-separator]_svg]:size-4", children: [
                    /* @__PURE__ */ jsx(BreadcrumbItem, { children: home.href && current ? /* @__PURE__ */ jsx(BreadcrumbLink, { asChild: true, "aria-label": home.label, children: /* @__PURE__ */ jsx(Link, { href: home.href, children: /* @__PURE__ */ jsx(Home, { className: "size-4", "aria-hidden": "true" }) }) }) : /* @__PURE__ */ jsx(BreadcrumbPage, { "aria-label": home.label, children: /* @__PURE__ */ jsx(Home, { className: "size-4", "aria-hidden": "true" }) }) }),
                    current ? /* @__PURE__ */ jsxs(Fragment, { children: [
                      hasMid ? /* @__PURE__ */ jsxs(Fragment, { children: [
                        /* @__PURE__ */ jsx(BreadcrumbSeparator, { className: "md:hidden" }),
                        /* @__PURE__ */ jsx(BreadcrumbItem, { className: "md:hidden", children: /* @__PURE__ */ jsx(BreadcrumbEllipsis, { "aria-label": t("appShell.breadcrumb.collapsed", { count: mid.length }) }) }),
                        mid.map((b, i) => /* @__PURE__ */ jsxs(React.Fragment, { children: [
                          /* @__PURE__ */ jsx(BreadcrumbSeparator, { className: "hidden md:inline-flex" }),
                          /* @__PURE__ */ jsx(BreadcrumbItem, { className: "hidden md:inline-flex", children: b.href ? /* @__PURE__ */ jsx(BreadcrumbLink, { asChild: true, title: b.label, children: /* @__PURE__ */ jsx(Link, { href: b.href, children: b.label }) }) : /* @__PURE__ */ jsx(BreadcrumbLink, { title: b.label, "aria-disabled": "true", tabIndex: -1, children: b.label }) })
                        ] }, `mid-${i}`))
                      ] }) : null,
                      /* @__PURE__ */ jsx(BreadcrumbSeparator, {}),
                      /* @__PURE__ */ jsx(BreadcrumbItem, { children: /* @__PURE__ */ jsx(BreadcrumbPage, { title: current.label, children: current.label }) })
                    ] }) : null
                  ] }) });
                })()
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 sm:gap-2 md:gap-3 text-sm shrink-0", children: [
                /* @__PURE__ */ jsx(
                  StatusBadgeInjectionSpot,
                  {
                    spotId: GLOBAL_HEADER_STATUS_INDICATORS_INJECTION_SPOT_ID,
                    context: injectionContext
                  }
                ),
                /* @__PURE__ */ jsx(
                  InjectionSpot,
                  {
                    spotId: BACKEND_TOPBAR_ACTIONS_INJECTION_SPOT_ID,
                    context: injectionContext
                  }
                ),
                renderedTopbarInjectedActions,
                /* @__PURE__ */ jsx(AiAssistantLauncher, { variant: "topbar" }),
                rightHeaderSlot ? rightHeaderSlot : /* @__PURE__ */ jsx("span", { className: "opacity-80", children: email || t("appShell.userFallback") })
              ] })
            ] }),
            /* @__PURE__ */ jsx(ProgressTopBar, { t, className: "sticky top-0 z-sticky" }),
            /* @__PURE__ */ jsxs("main", { className: "flex-1 p-4 lg:p-6 mx-auto w-full max-w-screen-2xl", children: [
              /* @__PURE__ */ jsx(InjectionSpot, { spotId: BACKEND_LAYOUT_TOP_INJECTION_SPOT_ID, context: injectionContext }),
              /* @__PURE__ */ jsx(FlashMessages, {}),
              /* @__PURE__ */ jsx(PartialIndexBanner, {}),
              /* @__PURE__ */ jsx(UpgradeActionBanner, {}),
              /* @__PURE__ */ jsx(LastOperationBanner, {}),
              /* @__PURE__ */ jsx(InjectionSpot, { spotId: BACKEND_RECORD_CURRENT_INJECTION_SPOT_ID, context: injectionContext }),
              /* @__PURE__ */ jsx(
                InjectionSpot,
                {
                  spotId: LEGACY_GLOBAL_MUTATION_INJECTION_SPOT_ID,
                  context: injectionContext
                }
              ),
              /* @__PURE__ */ jsx("div", { id: "om-top-banners", className: "mb-3 space-y-2" }),
              children,
              /* @__PURE__ */ jsx(InjectionSpot, { spotId: BACKEND_LAYOUT_FOOTER_INJECTION_SPOT_ID, context: injectionContext })
            ] }),
            /* @__PURE__ */ jsxs("footer", { className: "border-t bg-background/80 backdrop-blur supports-[backdrop-filter]:bg-background/80 px-4 py-3 flex flex-wrap items-center justify-end gap-4", children: [
              version ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("appShell.version", { version }) }) : null,
              /* @__PURE__ */ jsxs("nav", { className: "flex items-center gap-3 text-xs text-muted-foreground", children: [
                /* @__PURE__ */ jsx(Link, { href: "/terms", className: "transition hover:text-foreground", children: t("common.terms") }),
                /* @__PURE__ */ jsx(Link, { href: "/privacy", className: "transition hover:text-foreground", children: t("common.privacy") })
              ] })
            ] })
          ] }),
          mobileOpen && /* @__PURE__ */ jsxs("div", { className: "lg:hidden fixed inset-0 z-modal", children: [
            /* @__PURE__ */ jsx("div", { className: "absolute inset-0 bg-black/50 backdrop-blur-sm", onClick: () => setMobileOpen(false), "aria-hidden": "true" }),
            /* @__PURE__ */ jsxs("aside", { className: "absolute left-0 top-0 flex h-full w-[280px] max-w-[85vw] flex-col bg-background border-r shadow-lg overflow-hidden", children: [
              /* @__PURE__ */ jsxs("div", { className: "shrink-0 flex items-center justify-between gap-2 border-b px-4 py-3", children: [
                /* @__PURE__ */ jsxs(Link, { href: "/backend", className: "flex items-center gap-2 min-w-0 text-sm font-semibold", onClick: () => setMobileOpen(false), "aria-label": t("appShell.goToDashboard"), children: [
                  /* @__PURE__ */ jsx(Image, { src: logo?.src ?? "/open-mercato.svg", alt: logo?.alt ?? resolvedProductName, width: 28, height: 28, className: "rounded shrink-0" }),
                  /* @__PURE__ */ jsx("span", { className: "truncate", children: resolvedProductName })
                ] }),
                /* @__PURE__ */ jsx(IconButton, { variant: "ghost", size: "sm", onClick: () => setMobileOpen(false), "aria-label": t("appShell.closeMenu"), children: /* @__PURE__ */ jsx(X, { className: "size-4" }) })
              ] }),
              mobileSidebarSlot && /* @__PURE__ */ jsx("div", { className: "shrink-0 border-b px-3 py-2", children: mobileSidebarSlot }),
              sidebarMode !== "main" ? /* @__PURE__ */ jsx("div", { className: "shrink-0 flex items-center gap-5 border-b px-4 pt-3 pb-0", role: "tablist", children: [
                { id: "main", label: t("backend.nav.main", "Main") },
                {
                  id: "section",
                  label: sidebarMode === "settings" ? settingsSectionTitle ?? t("backend.nav.settings", "Settings") : profileSectionTitle ?? t("backend.nav.profile", "Profile")
                }
              ].map((tab) => {
                const isActive = tab.id === "main" ? mobileDrawerView === "main" : mobileDrawerView === "auto";
                const tabId = `mobile-drawer-tab-${tab.id}`;
                return /* @__PURE__ */ jsxs(
                  "button",
                  {
                    id: tabId,
                    type: "button",
                    role: "tab",
                    "aria-selected": isActive,
                    "aria-controls": "mobile-drawer-tabpanel",
                    onClick: () => setMobileDrawerView(tab.id === "main" ? "main" : "auto"),
                    className: "relative inline-flex items-center pb-2 text-sm font-medium leading-5 tracking-tight transition-colors focus:outline-none data-[active=true]:text-foreground data-[active=false]:text-muted-foreground hover:text-foreground",
                    "data-active": isActive,
                    children: [
                      /* @__PURE__ */ jsx("span", { children: tab.label }),
                      isActive ? /* @__PURE__ */ jsx(
                        "span",
                        {
                          className: "absolute -bottom-px left-0 right-0 h-0.5 bg-foreground",
                          "aria-hidden": "true"
                        }
                      ) : null
                    ]
                  },
                  tab.id
                );
              }) }) : null,
              /* @__PURE__ */ jsx(
                "div",
                {
                  id: "mobile-drawer-tabpanel",
                  role: sidebarMode !== "main" ? "tabpanel" : void 0,
                  "aria-labelledby": sidebarMode !== "main" ? `mobile-drawer-tab-${mobileDrawerView === "main" ? "main" : "section"}` : void 0,
                  className: "min-h-0 flex-1 overflow-y-auto overflow-x-hidden p-3",
                  children: renderSidebar(false, true, mobileDrawerView === "main")
                }
              )
            ] })
          ] })
        ]
      }
    ),
    /* @__PURE__ */ jsx(UmesDevToolsPanel, {})
  ] });
}
export {
  AppShell,
  ApplyBreadcrumb
};
//# sourceMappingURL=AppShell.js.map
