"use client"; import { useState, useEffect, useRef } from "react"; import { LOCALES, LOCALE_COOKIE, normalizeLocale } from "@/i18n/config"; import { reloadTranslations } from "@/i18n/runtime"; function getLocaleFromCookie() { if (typeof document === "undefined") return "en"; const cookie = document.cookie .split(";") .find((c) => c.trim().startsWith(`${LOCALE_COOKIE}=`)); const value = cookie ? decodeURIComponent(cookie.split("=")[1]) : "en"; return normalizeLocale(value); } // Locale display names - will be translated by runtime i18n const getLocaleName = (locale) => { const names = { "en": "English", "vi": "Tiếng Việt", "zh-CN": "简体中文" }; return names[locale] || locale; }; export default function LanguageSwitcher({ className = "" }) { const [locale, setLocale] = useState("en"); const [isPending, setIsPending] = useState(false); const [isOpen, setIsOpen] = useState(false); const dropdownRef = useRef(null); useEffect(() => { setLocale(getLocaleFromCookie()); }, []); // Close dropdown when clicking outside useEffect(() => { function handleClickOutside(event) { if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { setIsOpen(false); } } document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, []); const handleSetLocale = async (nextLocale) => { if (nextLocale === locale || isPending) return; setIsPending(true); setIsOpen(false); try { await fetch("/api/locale", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ locale: nextLocale }), }); // Reload translations without full page reload await reloadTranslations(); setLocale(nextLocale); } catch (err) { console.error("Failed to set locale:", err); } finally { setIsPending(false); } }; return (