"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useState, useCallback, useMemo } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "../primitives/button.js";
import { IconButton } from "../primitives/icon-button.js";
import { usePortalInjectedMenuItems } from "./hooks/usePortalInjectedMenuItems.js";
import { usePortalEventBridge } from "./hooks/usePortalEventBridge.js";
import { mergeMenuItems } from "../backend/injection/mergeMenuItems.js";
import { PortalNotificationBell } from "./components/PortalNotificationBell.js";
import { usePortalContext } from "./PortalContext.js";
import { apiCall } from "../backend/utils/apiCall.js";
const PORTAL_SHELL_HANDLE = "page:portal:layout";
const PORTAL_HEADER_HANDLE = "section:portal:header";
const PORTAL_FOOTER_HANDLE = "section:portal:footer";
const PORTAL_SIDEBAR_HANDLE = "section:portal:sidebar";
const PORTAL_USER_MENU_HANDLE = "section:portal:user-menu";
function PortalEventBridgeMount() {
  usePortalEventBridge();
  return null;
}
function MenuIcon({ className }) {
  return /* @__PURE__ */ jsxs("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className, children: [
    /* @__PURE__ */ jsx("line", { x1: "4", x2: "20", y1: "12", y2: "12" }),
    /* @__PURE__ */ jsx("line", { x1: "4", x2: "20", y1: "6", y2: "6" }),
    /* @__PURE__ */ jsx("line", { x1: "4", x2: "20", y1: "18", y2: "18" })
  ] });
}
function XIcon({ className }) {
  return /* @__PURE__ */ jsxs("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className, children: [
    /* @__PURE__ */ jsx("path", { d: "M18 6 6 18" }),
    /* @__PURE__ */ jsx("path", { d: "m6 6 12 12" })
  ] });
}
function LogOutIcon({ className }) {
  return /* @__PURE__ */ jsxs("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className, children: [
    /* @__PURE__ */ jsx("path", { d: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" }),
    /* @__PURE__ */ jsx("polyline", { points: "16 17 21 12 16 7" }),
    /* @__PURE__ */ jsx("line", { x1: "21", x2: "9", y1: "12", y2: "12" })
  ] });
}
function SidebarNavItem({
  item,
  active,
  t,
  onClick
}) {
  const label = item.labelKey ? t(item.labelKey, item.label) : item.label;
  if (!label) return null;
  const cls = [
    "flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] font-medium transition-colors",
    active ? "bg-foreground text-background" : "text-muted-foreground hover:bg-muted hover:text-foreground"
  ].join(" ");
  if (item.href) {
    return /* @__PURE__ */ jsx(Link, { href: item.href, className: cls, "data-menu-item-id": item.id, onClick, children: label });
  }
  if (item.onClick) {
    return /* @__PURE__ */ jsx("button", { type: "button", className: cls, "data-menu-item-id": item.id, onClick: () => {
      item.onClick?.();
      onClick?.();
    }, children: label });
  }
  return null;
}
function UserAvatar({ name, className }) {
  const initials = name ? name.split(" ").map((w) => w[0]).slice(0, 2).join("").toUpperCase() : "?";
  return /* @__PURE__ */ jsx("div", { className: `flex items-center justify-center rounded-full bg-foreground text-[11px] font-semibold text-background ${className ?? "size-8"}`, children: initials });
}
function useOptionalPortalContext() {
  try {
    return usePortalContext();
  } catch {
    return null;
  }
}
function PortalShell({
  children,
  orgSlug: orgSlugProp,
  organizationName: orgNameProp,
  authenticated: authenticatedProp,
  onLogout: onLogoutProp,
  enableEventBridge = false,
  userName: userNameProp,
  userEmail: userEmailProp
}) {
  const t = useT();
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen] = useState(false);
  const portalCtx = useOptionalPortalContext();
  const orgSlug = portalCtx?.orgSlug ?? orgSlugProp;
  const orgName = portalCtx?.tenant.organizationName ?? orgNameProp;
  const user = portalCtx?.auth.user ?? null;
  const authenticated = authenticatedProp ?? !!user;
  const onLogout = onLogoutProp ?? portalCtx?.auth.logout;
  const userName = userNameProp ?? user?.displayName;
  const userEmail = userEmailProp ?? user?.email;
  const { items: injectedMainItems } = usePortalInjectedMenuItems("menu:portal:sidebar:main");
  const { items: injectedAccountItems } = usePortalInjectedMenuItems("menu:portal:sidebar:account");
  const portalHome = orgSlug ? `/${orgSlug}/portal` : "/portal";
  const loginHref = orgSlug ? `/${orgSlug}/portal/login` : "/portal/login";
  const signupHref = orgSlug ? `/${orgSlug}/portal/signup` : "/portal/signup";
  const headerTitle = orgName || t("portal.title", "Customer Portal");
  const closeMobile = useCallback(() => setMobileOpen(false), []);
  const [autoNavGroups, setAutoNavGroups] = useState([]);
  useEffect(() => {
    if (!authenticated) {
      setAutoNavGroups([]);
      return;
    }
    let cancelled = false;
    const load = async () => {
      try {
        const { ok, result } = await apiCall(
          "/api/customer_accounts/portal/nav"
        );
        if (cancelled || !ok || !result?.ok) return;
        setAutoNavGroups(Array.isArray(result.groups) ? result.groups : []);
      } catch {
        if (!cancelled) setAutoNavGroups([]);
      }
    };
    void load();
    return () => {
      cancelled = true;
    };
  }, [authenticated]);
  const mergedNavItems = useMemo(() => {
    if (!authenticated) return [];
    const discovered = autoNavGroups.find((g) => g.id === "main")?.items ?? [];
    const builtIn = discovered.map((item) => ({
      id: item.id,
      labelKey: item.labelKey,
      label: item.label,
      href: item.href
    }));
    return mergeMenuItems(builtIn, injectedMainItems);
  }, [authenticated, autoNavGroups, injectedMainItems]);
  const mergedAccountItems = useMemo(() => {
    if (!authenticated) return [];
    const discovered = autoNavGroups.find((g) => g.id === "account")?.items ?? [];
    const builtIn = discovered.map((item) => ({
      id: item.id,
      labelKey: item.labelKey,
      label: item.label,
      href: item.href
    }));
    return mergeMenuItems(builtIn, injectedAccountItems);
  }, [authenticated, autoNavGroups, injectedAccountItems]);
  if (!authenticated) {
    return /* @__PURE__ */ jsxs("div", { className: "flex min-h-svh flex-col bg-background", "data-portal-handle": PORTAL_SHELL_HANDLE, children: [
      /* @__PURE__ */ jsx("header", { className: "sticky top-0 z-40 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80", "data-portal-handle": PORTAL_HEADER_HANDLE, children: /* @__PURE__ */ jsxs("div", { className: "mx-auto flex h-16 w-full max-w-screen-lg items-center justify-between px-6", children: [
        /* @__PURE__ */ jsxs(Link, { href: portalHome, className: "flex items-center gap-2.5 text-foreground transition hover:opacity-80", "aria-label": headerTitle, children: [
          /* @__PURE__ */ jsx(Image, { src: "/open-mercato.svg", alt: "", width: 28, height: 28, className: "", priority: true }),
          /* @__PURE__ */ jsx("span", { className: "text-[15px] font-semibold tracking-tight", children: headerTitle })
        ] }),
        /* @__PURE__ */ jsxs("nav", { "aria-label": "Primary", className: "flex items-center gap-1", children: [
          /* @__PURE__ */ jsx(Button, { asChild: true, variant: "ghost", size: "sm", className: "text-[13px]", children: /* @__PURE__ */ jsx(Link, { href: loginHref, children: t("portal.nav.login", "Log In") }) }),
          /* @__PURE__ */ jsx(Button, { asChild: true, size: "sm", className: "rounded-lg text-[13px]", children: /* @__PURE__ */ jsx(Link, { href: signupHref, children: t("portal.nav.signup", "Sign Up") }) })
        ] })
      ] }) }),
      /* @__PURE__ */ jsx("main", { className: "flex-1", children: /* @__PURE__ */ jsx("div", { className: "mx-auto flex w-full max-w-screen-lg flex-col gap-8 px-6 py-12 sm:py-20", children }) }),
      /* @__PURE__ */ jsx("footer", { className: "border-t", "data-portal-handle": PORTAL_FOOTER_HANDLE, children: /* @__PURE__ */ jsxs("div", { className: "mx-auto flex w-full max-w-screen-lg items-center justify-between px-6 py-6", children: [
        /* @__PURE__ */ jsxs(Link, { href: portalHome, className: "flex items-center gap-2 text-muted-foreground transition hover:text-foreground", children: [
          /* @__PURE__ */ jsx(Image, { src: "/open-mercato.svg", alt: "", width: 20, height: 20, className: "" }),
          /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-foreground", children: headerTitle })
        ] }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground/60", children: t("portal.footer.copyright", "\xA9 {year} All rights reserved.", { year: (/* @__PURE__ */ new Date()).getFullYear() }) })
      ] }) })
    ] });
  }
  const sidebarContent = /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col", "data-portal-handle": PORTAL_SIDEBAR_HANDLE, children: [
    /* @__PURE__ */ jsx("div", { className: "flex h-16 items-center gap-2.5 border-b px-5", children: /* @__PURE__ */ jsxs(Link, { href: portalHome, className: "flex items-center gap-2.5 text-foreground transition hover:opacity-80", "aria-label": headerTitle, children: [
      /* @__PURE__ */ jsx(Image, { src: "/open-mercato.svg", alt: "", width: 22, height: 22, className: "" }),
      /* @__PURE__ */ jsx("span", { className: "text-[14px] font-semibold tracking-tight truncate", children: headerTitle })
    ] }) }),
    /* @__PURE__ */ jsxs("nav", { "aria-label": "Portal navigation", className: "flex-1 overflow-y-auto px-3 py-5", children: [
      /* @__PURE__ */ jsx("p", { className: "mb-2 px-3 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground/50", children: t("portal.nav.home", "Portal") }),
      /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-0.5", children: mergedNavItems.map((item) => /* @__PURE__ */ jsx(
        SidebarNavItem,
        {
          item,
          active: !!item.href && pathname.startsWith(item.href),
          t,
          onClick: closeMobile
        },
        item.id
      )) }),
      mergedAccountItems.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "mt-8", children: [
        /* @__PURE__ */ jsx("p", { className: "mb-2 px-3 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground/50", children: t("portal.nav.account", "Account") }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-0.5", children: mergedAccountItems.map((item) => /* @__PURE__ */ jsx(
          SidebarNavItem,
          {
            item,
            active: !!item.href && pathname.startsWith(item.href),
            t,
            onClick: closeMobile
          },
          item.id
        )) })
      ] }) : null
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "border-t px-3 py-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5 rounded-lg px-3 py-2", children: [
        /* @__PURE__ */ jsx(UserAvatar, { name: userName, className: "size-8" }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
          userName ? /* @__PURE__ */ jsx("p", { className: "truncate text-[13px] font-medium leading-tight", children: userName }) : /* @__PURE__ */ jsx("div", { className: "h-4 w-24 animate-pulse rounded bg-muted" }),
          userEmail ? /* @__PURE__ */ jsx("p", { className: "truncate text-[11px] text-muted-foreground", children: userEmail }) : /* @__PURE__ */ jsx("div", { className: "mt-1 h-3 w-32 animate-pulse rounded bg-muted" })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(
        "button",
        {
          type: "button",
          onClick: onLogout,
          className: "mt-0.5 flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
          "data-portal-handle": PORTAL_USER_MENU_HANDLE,
          "data-menu-item-id": "portal-logout",
          children: [
            /* @__PURE__ */ jsx(LogOutIcon, { className: "size-4" }),
            t("portal.nav.logout", "Log Out")
          ]
        }
      )
    ] })
  ] });
  return /* @__PURE__ */ jsxs("div", { className: "flex min-h-svh bg-background", "data-portal-handle": PORTAL_SHELL_HANDLE, children: [
    enableEventBridge ? /* @__PURE__ */ jsx(PortalEventBridgeMount, {}) : null,
    /* @__PURE__ */ jsx("aside", { className: "hidden w-[240px] shrink-0 border-r lg:block", children: sidebarContent }),
    mobileOpen ? /* @__PURE__ */ jsxs("div", { className: "fixed inset-0 z-50 lg:hidden", children: [
      /* @__PURE__ */ jsx("div", { className: "absolute inset-0 bg-black/30 backdrop-blur-sm", onClick: closeMobile }),
      /* @__PURE__ */ jsxs("aside", { className: "relative z-10 h-full w-[280px] bg-background shadow-2xl", children: [
        /* @__PURE__ */ jsx("div", { className: "absolute right-3 top-4 z-20", children: /* @__PURE__ */ jsx(IconButton, { variant: "ghost", size: "sm", type: "button", onClick: closeMobile, "aria-label": "Close menu", children: /* @__PURE__ */ jsx(XIcon, { className: "size-4" }) }) }),
        sidebarContent
      ] })
    ] }) : null,
    /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [
      /* @__PURE__ */ jsxs("header", { className: "flex h-16 items-center justify-between border-b px-4 lg:px-8", "data-portal-handle": PORTAL_HEADER_HANDLE, children: [
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsx(IconButton, { variant: "ghost", size: "sm", type: "button", onClick: () => setMobileOpen(true), className: "lg:hidden", "aria-label": "Open menu", children: /* @__PURE__ */ jsx(MenuIcon, { className: "size-5" }) }) }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsx(PortalNotificationBell, { t }) })
      ] }),
      /* @__PURE__ */ jsx("main", { className: "flex-1 overflow-y-auto", children: /* @__PURE__ */ jsx("div", { className: "w-full px-4 py-6 lg:px-8 lg:py-8", children }) }),
      /* @__PURE__ */ jsx("footer", { className: "border-t px-4 py-4 lg:px-8", "data-portal-handle": PORTAL_FOOTER_HANDLE, children: /* @__PURE__ */ jsx("p", { className: "text-[11px] text-muted-foreground/50", children: t("portal.footer.copyright", "\xA9 {year} All rights reserved.", { year: (/* @__PURE__ */ new Date()).getFullYear() }) }) })
    ] })
  ] });
}
var PortalShell_default = PortalShell;
export {
  PORTAL_FOOTER_HANDLE,
  PORTAL_HEADER_HANDLE,
  PORTAL_SHELL_HANDLE,
  PORTAL_SIDEBAR_HANDLE,
  PORTAL_USER_MENU_HANDLE,
  PortalShell,
  PortalShell_default as default
};
//# sourceMappingURL=PortalShell.js.map
