"use client";
import { 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 } 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 { Button } from "../primitives/button.js";
import { IconButton } from "../primitives/icon-button.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 = "w-full text-left text-sm cursor-pointer px-3 py-2 rounded hover:bg-accent inline-flex items-center gap-2.5 outline-none focus-visible:ring-1 focus-visible:ring-ring";
  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);
      if (item.href) {
        return /* @__PURE__ */ jsxs(
          Link,
          {
            href: item.href,
            className: menuItemClass,
            role: "menuitem",
            "data-menu-item-id": item.id,
            onClick: () => setOpen(false),
            children: [
              icon,
              /* @__PURE__ */ jsx("span", { children: label })
            ]
          },
          item.id
        );
      }
      return /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          className: "w-full justify-start",
          role: "menuitem",
          "data-menu-item-id": item.id,
          onClick: () => {
            item.onClick?.();
            setOpen(false);
          },
          children: [
            icon,
            /* @__PURE__ */ jsx("span", { children: label })
          ]
        },
        item.id
      );
    },
    [menuItemClass, 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: "size-4" }),
              /* @__PURE__ */ jsx("span", { 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: "size-4" }),
              /* @__PURE__ */ jsx("span", { children: t("ui.profileMenu.notifications", "Notification Preferences") })
            ]
          },
          id
        );
      }
      if (id === "theme-toggle") {
        return mounted ? /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            className: "w-full justify-between",
            role: "menuitem",
            onClick: handleThemeToggle,
            children: [
              /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2.5", children: [
                isDark ? /* @__PURE__ */ jsx(Moon, { className: "size-4" }) : /* @__PURE__ */ jsx(Sun, { className: "size-4" }),
                /* @__PURE__ */ jsx("span", { children: t("ui.profileMenu.theme", "Dark Mode") })
              ] }),
              /* @__PURE__ */ jsx("div", { className: `w-8 h-4 rounded-full transition-colors ${isDark ? "bg-primary" : "bg-muted"} relative`, children: /* @__PURE__ */ jsx("div", { className: `absolute top-0.5 w-3 h-3 rounded-full bg-background shadow transition-transform ${isDark ? "translate-x-4" : "translate-x-0.5"}` }) })
            ]
          },
          id
        ) : null;
      }
      if (id === "language") {
        return /* @__PURE__ */ jsxs("div", { className: "relative", children: [
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              className: "w-full justify-between",
              role: "menuitem",
              onClick: () => setLanguageOpen(!languageOpen),
              "aria-expanded": languageOpen,
              children: [
                /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2.5", children: [
                  /* @__PURE__ */ jsx(Globe, { className: "size-4" }),
                  /* @__PURE__ */ jsx("span", { children: t("ui.profileMenu.language", "Language") })
                ] }),
                /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: localeLabels[currentLocale] })
              ]
            }
          ),
          languageOpen && /* @__PURE__ */ jsx("div", { className: "mt-1 ml-6 space-y-0.5 border-l pl-2", children: locales.map((locale) => /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              className: `w-full justify-start gap-2 ${locale === currentLocale ? "text-primary font-medium" : ""}`,
              onClick: () => handleLocaleChange(locale),
              children: [
                /* @__PURE__ */ jsx("span", { children: localeLabels[locale] }),
                locale === currentLocale && /* @__PURE__ */ jsx(Check, { className: "size-3.5" })
              ]
            },
            locale
          )) })
        ] }, id);
      }
      if (id === "sign-out") {
        return /* @__PURE__ */ jsx("form", { action: "/api/auth/logout", method: "POST", children: /* @__PURE__ */ jsxs(
          Button,
          {
            variant: "ghost",
            size: "sm",
            className: "w-full justify-start",
            type: "submit",
            role: "menuitem",
            children: [
              /* @__PURE__ */ jsx(LogOut, { className: "size-4" }),
              /* @__PURE__ */ jsx("span", { children: t("ui.userMenu.logout", "Sign Out") })
            ]
          }
        ) }, id);
      }
      return null;
    },
    [
      changePasswordHref,
      currentLocale,
      handleThemeToggle,
      isDark,
      languageOpen,
      menuItemClass,
      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 mt-1 w-56 rounded-md border bg-background p-1 shadow-lg z-50",
        role: "menu",
        "data-testid": "profile-dropdown",
        children: [
          (displayName || email) && /* @__PURE__ */ jsxs("div", { className: "px-3 py-2.5 border-b mb-1", children: [
            displayName && /* @__PURE__ */ jsxs("div", { className: "font-medium text-sm flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(User, { className: "size-4" }),
              displayName
            ] }),
            displayName && email && /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground mt-0.5 ml-6", children: email }),
            !displayName && email && /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
              t("ui.userMenu.loggedInAs", "Logged in as:"),
              " ",
              email
            ] })
          ] }),
          mergedMenuItems.map((item) => /* @__PURE__ */ jsxs(React.Fragment, { children: [
            item.separator ? /* @__PURE__ */ jsx("div", { className: "my-1 border-t" }) : 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
