"use client"; import { useEffect, useRef, useState } from "react"; import { usePathname } from "next/navigation"; import { ChevronDown, Globe } from "lucide-react"; import { LOCALES, getLocalizedHref } from "@/i18n/links"; export { LOCALES, getLocalizedHref }; export default function LanguageSelector() { const pathname = usePathname() || ""; const [open, setOpen] = useState(false); const [hash, setHash] = useState(""); const containerRef = useRef(null); // Detecta locale da URL atual const currentLocaleCode = LOCALES.find((l) => pathname === `/${l.code}` || pathname.startsWith(`/${l.code}/`))?.code || "pt"; const currentLocale = LOCALES.find((l) => l.code === currentLocaleCode) || LOCALES[0]; useEffect(() => { if (typeof window !== "undefined") { setHash(window.location.hash || ""); } }, [pathname]); useEffect(() => { function onPointerDown(e) { if (containerRef.current && !containerRef.current.contains(e.target)) { setOpen(false); } } function onKeyDown(e) { if (e.key === "Escape") { setOpen(false); } } document.addEventListener("mousedown", onPointerDown); document.addEventListener("keydown", onKeyDown); return () => { document.removeEventListener("mousedown", onPointerDown); document.removeEventListener("keydown", onKeyDown); }; }, []); const handleSelect = (code) => { if (typeof document !== "undefined") { document.cookie = `NEXT_LOCALE=${code}; path=/; max-age=31536000; SameSite=Lax`; } setOpen(false); }; return (
{open && (
{LOCALES.map((loc) => { const isActive = loc.code === currentLocaleCode; const href = `${getLocalizedHref(pathname, loc.code)}${hash}`; return ( handleSelect(loc.code)} className={`flex min-h-[44px] items-center justify-between rounded-xl px-3 py-2 text-sm transition-colors ${ isActive ? "bg-accent-soft text-accent font-semibold" : "text-ink-soft hover:bg-surface-2 hover:text-ink" }`} > {loc.label} {loc.short} ); })}
)}
); }