"use client";

import { GlobeIcon } from "@/components/header/icons";
import { useDismiss } from "@/components/header/useDismiss";
import { AppLocale, usePathname, useRouter } from "@/i18n/routing";
import clsx from "clsx";
import { useLocale, useTranslations } from "next-intl";
import { useCallback, useRef, useState } from "react";

// Same fixed native labels and order as the admin/store dashboards.
const LANGUAGES: { code: AppLocale; label: string }[] = [
  { code: "en", label: "English (UK)" },
  { code: "ar", label: "العربية (AR)" },
  { code: "pl", label: "Polski (PL)" },
  { code: "uk", label: "Українська (UK)" },
];

export function LanguageDropdown() {
  const locale = useLocale();
  const t = useTranslations("settings");
  const router = useRouter();
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const close = useCallback(() => setOpen(false), []);
  useDismiss(ref, open, close);

  const change = (next: AppLocale) => {
    setOpen(false);
    if (next !== locale) router.replace(pathname, { locale: next });
  };

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        aria-haspopup="menu"
        aria-expanded={open}
        aria-label={t("locale")}
        onClick={() => setOpen((v) => !v)}
        className="flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-orange-100 hover:text-foreground"
      >
        <GlobeIcon className="h-6 w-6" />
      </button>
      {open ? (
        <div
          role="menu"
          className="absolute end-0 z-50 mt-2 w-44 overflow-hidden rounded-lg border bg-popover py-1 shadow-lg"
        >
          {LANGUAGES.map(({ code, label }) => (
            <button
              key={code}
              type="button"
              role="menuitem"
              onClick={() => change(code)}
              className={clsx(
                "block w-full px-4 py-2 text-start text-sm hover:bg-gray-100 hover:font-bold",
                code === locale && "font-semibold text-Base",
              )}
            >
              {label}
            </button>
          ))}
        </div>
      ) : null}
    </div>
  );
}
