"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { User, LogOut, Bell, Moon, Sun, Globe, Key, Check, ChevronRight } from "lucide-react";
import { useT, useLocale } from "@open-mercato/shared/lib/i18n/context";
import { locales } from "@open-mercato/shared/lib/i18n/config";
import { useTheme } from "@open-mercato/ui/theme";
import { cn } from "@open-mercato/shared/lib/utils";
import { IconButton } from "../primitives/icon-button.js";
import { Switch } from "../primitives/switch.js";
import { useInjectedMenuItems } from "./injection/useInjectedMenuItems.js";
import { mergeMenuItems } from "./injection/mergeMenuItems.js";
import { resolveInjectedIcon } from "./injection/resolveInjectedIcon.js";
import { InjectionSpot } from "./injection/InjectionSpot.js";
import { BACKEND_TOPBAR_PROFILE_MENU_INJECTION_SPOT_ID } from "./injection/spotIds.js";
const localeLabels = {
  en: "English",
  de: "Deutsch",
  es: "Espa\xF1ol",
  pl: "Polski"
};
function ProfileDropdown({
  email,
  displayName,
  changePasswordHref = "/backend/profile/change-password",
  notificationsHref
}) {
  const t = useT();
  const currentLocale = useLocale();
  const { resolvedTheme, setTheme } = useTheme();
  const [open, setOpen] = React.useState(false);
  const [languageOpen, setLanguageOpen] = React.useState(false);
  const [mounted, setMounted] = React.useState(false);
  const buttonRef = React.useRef(null);
  const menuRef = React.useRef(null);
  const { items: injectedItems } = useInjectedMenuItems("menu:topbar:profile-dropdown");
  React.useEffect(() => {
    setMounted(true);
  }, []);
  const isDark = resolvedTheme === "dark";
  React.useEffect(() => {
    if (!open) return;
    function handleClick(event) {
      if (menuRef.current && !menuRef.current.contains(event.target) && buttonRef.current && !buttonRef.current.contains(event.target)) {
        setOpen(false);
        setLanguageOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, [open]);
  React.useEffect(() => {
    if (!open) return;
    function handleKeyDown(event) {
      if (event.key === "Escape") {
        if (languageOpen) {
          setLanguageOpen(false);
        } else {
          setOpen(false);
          buttonRef.current?.focus();
        }
      }
    }
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [open, languageOpen]);
  const handleThemeToggle = () => {
    setTheme(isDark ? "light" : "dark");
  };
  const handleLocaleChange = async (locale) => {
    try {
      await fetch("/api/auth/locale", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ locale })
      });
      window.location.reload();
    } catch {
    }
  };
  const menuItemClass = cn(
    "group flex h-9 w-full items-center gap-3 rounded-md px-2.5 text-sm text-foreground",
    "transition-colors hover:bg-muted/60 focus:outline-none focus-visible:bg-muted/60",
    "cursor-pointer"
  );
  const menuIconClass = "size-4 shrink-0 text-muted-foreground group-hover:text-foreground";
  const resolveMenuLabel = React.useCallback(
    (item) => {
      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;
    },
    [t]
  );
  const builtInMenuItems = React.useMemo(
    () => {
      const items = [{ id: "change-password" }];
      if (notificationsHref) items.push({ id: "notifications" });
      items.push({ id: "theme-toggle", separator: true }, { id: "language" }, { id: "sign-out", separator: true });
      return items;
    },
    [notificationsHref]
  );
  const mergedMenuItems = React.useMemo(
    () => mergeMenuItems(builtInMenuItems, injectedItems),
    [builtInMenuItems, injectedItems]
  );
  const injectionContext = React.useMemo(
    () => ({
      email,
      displayName,
      locale: currentLocale
    }),
    [currentLocale, displayName, email]
  );
  const renderInjectedItem = React.useCallback(
    (item) => {
      const label = resolveMenuLabel(item);
      const icon = resolveInjectedIcon(item.icon);
      const inner = /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx("span", { className: menuIconClass, children: icon }),
        /* @__PURE__ */ jsx("span", { className: "flex-1 truncate", children: label })
      ] });
      if (item.href) {
        return /* @__PURE__ */ jsx(
          Link,
          {
            href: item.href,
            className: menuItemClass,
            role: "menuitem",
            "data-menu-item-id": item.id,
            onClick: () => setOpen(false),
            children: inner
          },
          item.id
        );
      }
      return /* @__PURE__ */ jsx(
        "button",
        {
          type: "button",
          className: menuItemClass,
          role: "menuitem",
          "data-menu-item-id": item.id,
          onClick: () => {
            item.onClick?.();
            setOpen(false);
          },
          children: inner
        },
        item.id
      );
    },
    [menuItemClass, menuIconClass, resolveMenuLabel]
  );
  const renderBuiltInItem = React.useCallback(
    (id) => {
      if (id === "change-password") {
        return /* @__PURE__ */ jsxs(
          Link,
          {
            href: changePasswordHref,
            className: menuItemClass,
            role: "menuitem",
            onClick: () => setOpen(false),
            children: [
              /* @__PURE__ */ jsx(Key, { className: menuIconClass }),
              /* @__PURE__ */ jsx("span", { className: "flex-1 truncate", children: t("ui.profileMenu.changePassword", "Change Password") })
            ]
          },
          id
        );
      }
      if (id === "notifications" && notificationsHref) {
        return /* @__PURE__ */ jsxs(
          Link,
          {
            href: notificationsHref,
            className: menuItemClass,
            role: "menuitem",
            onClick: () => setOpen(false),
            children: [
              /* @__PURE__ */ jsx(Bell, { className: menuIconClass }),
              /* @__PURE__ */ jsx("span", { className: "flex-1 truncate", children: t("ui.profileMenu.notifications", "Notification Preferences") })
            ]
          },
          id
        );
      }
      if (id === "theme-toggle") {
        if (!mounted) return null;
        return /* @__PURE__ */ jsxs(
          "div",
          {
            className: cn(menuItemClass, "justify-between"),
            role: "menuitem",
            onClick: handleThemeToggle,
            onKeyDown: (e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                handleThemeToggle();
              }
            },
            tabIndex: 0,
            children: [
              /* @__PURE__ */ jsxs("span", { className: "flex flex-1 items-center gap-3", children: [
                isDark ? /* @__PURE__ */ jsx(Moon, { className: menuIconClass }) : /* @__PURE__ */ jsx(Sun, { className: menuIconClass }),
                /* @__PURE__ */ jsx("span", { className: "flex-1 truncate", children: t("ui.profileMenu.theme", "Theme") })
              ] }),
              /* @__PURE__ */ jsx(
                Switch,
                {
                  checked: isDark,
                  onCheckedChange: handleThemeToggle,
                  "aria-label": t("ui.profileMenu.theme", "Theme"),
                  onClick: (e) => e.stopPropagation()
                }
              )
            ]
          },
          id
        );
      }
      if (id === "language") {
        return /* @__PURE__ */ jsxs("div", { className: "contents", children: [
          /* @__PURE__ */ jsxs(
            "button",
            {
              type: "button",
              className: menuItemClass,
              role: "menuitem",
              onClick: () => setLanguageOpen(!languageOpen),
              "aria-expanded": languageOpen,
              children: [
                /* @__PURE__ */ jsx(Globe, { className: menuIconClass }),
                /* @__PURE__ */ jsx("span", { className: "truncate", children: t("ui.profileMenu.language", "Language") }),
                /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: localeLabels[currentLocale] }),
                /* @__PURE__ */ jsx(
                  ChevronRight,
                  {
                    className: cn(
                      "ml-auto size-3.5 shrink-0 text-muted-foreground transition-transform",
                      languageOpen && "rotate-90"
                    ),
                    "aria-hidden": "true"
                  }
                )
              ]
            }
          ),
          languageOpen && /* @__PURE__ */ jsx("div", { className: "ml-7 mr-1 flex flex-col gap-0.5 border-l pl-2 py-1", children: locales.map((locale) => /* @__PURE__ */ jsxs(
            "button",
            {
              type: "button",
              className: cn(
                "flex h-8 w-full items-center justify-between gap-2 rounded-md px-2 text-sm transition-colors hover:bg-muted/60 focus:outline-none focus-visible:bg-muted/60",
                locale === currentLocale ? "font-medium text-foreground" : "text-muted-foreground"
              ),
              onClick: () => handleLocaleChange(locale),
              children: [
                /* @__PURE__ */ jsx("span", { className: "truncate", children: localeLabels[locale] }),
                locale === currentLocale && /* @__PURE__ */ jsx(Check, { className: "size-3.5 shrink-0 text-accent-indigo", "aria-hidden": "true" })
              ]
            },
            locale
          )) })
        ] }, id);
      }
      if (id === "sign-out") {
        return /* @__PURE__ */ jsx("form", { action: "/api/auth/logout", method: "POST", children: /* @__PURE__ */ jsxs(
          "button",
          {
            type: "submit",
            className: menuItemClass,
            role: "menuitem",
            children: [
              /* @__PURE__ */ jsx(LogOut, { className: menuIconClass }),
              /* @__PURE__ */ jsx("span", { className: "flex-1 truncate text-left", children: t("ui.userMenu.logout", "Sign Out") })
            ]
          }
        ) }, id);
      }
      return null;
    },
    [
      changePasswordHref,
      currentLocale,
      handleThemeToggle,
      isDark,
      languageOpen,
      menuItemClass,
      menuIconClass,
      mounted,
      notificationsHref,
      t
    ]
  );
  return /* @__PURE__ */ jsxs("div", { className: "relative", children: [
    /* @__PURE__ */ jsx(
      IconButton,
      {
        ref: buttonRef,
        variant: "ghost",
        size: "sm",
        onClick: () => setOpen(!open),
        "aria-expanded": open,
        "aria-haspopup": "menu",
        "data-testid": "profile-dropdown-trigger",
        title: email || t("ui.userMenu.userFallback", "User"),
        children: /* @__PURE__ */ jsx(User, { className: "size-4" })
      }
    ),
    open && /* @__PURE__ */ jsxs(
      "div",
      {
        ref: menuRef,
        className: "absolute right-0 top-full z-popover mt-2 w-64 overflow-hidden rounded-lg border bg-popover p-0 shadow-lg",
        role: "menu",
        "data-testid": "profile-dropdown",
        children: [
          (displayName || email) && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 border-b bg-muted/30 px-3 py-3", children: [
            /* @__PURE__ */ jsx("div", { className: "flex size-9 shrink-0 items-center justify-center rounded-full bg-accent-indigo/10 text-accent-indigo", children: /* @__PURE__ */ jsx(User, { className: "size-4", "aria-hidden": "true" }) }),
            /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [
              displayName ? /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-medium leading-5 text-foreground", children: displayName }) : null,
              email ? /* @__PURE__ */ jsx("span", { className: cn(
                "truncate text-xs leading-4",
                displayName ? "text-muted-foreground" : "text-foreground font-medium"
              ), children: email }) : null,
              !displayName && email ? /* @__PURE__ */ jsx("span", { className: "truncate text-overline uppercase tracking-wider text-muted-foreground/80", children: t("ui.userMenu.loggedInAs", "Logged in") }) : null
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col p-1.5", children: [
            mergedMenuItems.map((item) => /* @__PURE__ */ jsxs(React.Fragment, { children: [
              item.separator ? /* @__PURE__ */ jsx("div", { className: "my-1 h-px bg-border", "aria-hidden": "true" }) : null,
              item.source === "injected" ? item.href || item.onClick || item.label || item.labelKey ? renderInjectedItem(item) : null : renderBuiltInItem(item.id)
            ] }, item.id)),
            /* @__PURE__ */ jsx(
              InjectionSpot,
              {
                spotId: BACKEND_TOPBAR_PROFILE_MENU_INJECTION_SPOT_ID,
                context: injectionContext
              }
            )
          ] })
        ]
      }
    )
  ] });
}
export {
  ProfileDropdown
};
//# sourceMappingURL=ProfileDropdown.js.map
