"use client"; import { useState } from "react"; import { usePathname } from "next/navigation"; import { useI18n } from "@/lib/i18n/client"; import { LOCALES, LOCALE_NAMES, type Locale, setLocale as saveLocalePreference } from "@/lib/i18n/config"; import { localePath, stripLocalePrefix } from "@/lib/i18n/navigation"; interface LanguageSwitcherProps { className?: string; /** "compact" = icon + short label, fits a header next to other icons. * "full" = icon + full label + chevron, for a settings panel row. */ variant?: "compact" | "full"; } const SHORT_LOCALE_NAMES: Record = { "zh-CN": "中文", en: "EN", ja: "日本語", }; export function LanguageSwitcher({ className = "", variant = "full" }: LanguageSwitcherProps) { const { locale, t } = useI18n(); const pathname = usePathname(); const [isOpen, setIsOpen] = useState(false); const currentLocaleName = LOCALE_NAMES[locale] || locale; const currentShortName = SHORT_LOCALE_NAMES[locale] || locale; function switchTo(newLocale: Locale) { const basePath = stripLocalePrefix(pathname); const newPath = localePath(basePath, newLocale); // Only persist to localStorage — do NOT update React state (setLocale) // because that triggers a re-render with isLoading=true before the // browser navigates away, flashing translation keys for one frame. saveLocalePreference(newLocale); window.location.href = newPath; } return (
{isOpen && ( <>
setIsOpen(false)} aria-hidden="true" />
{LOCALES.map((loc) => ( ))}
)}
); }