import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react"; import { LOCALES, translate, type Locale, type MessageKey } from "./messages"; const STORAGE_KEY = "ui_locale"; function detectInitialLocale(): Locale { const stored = localStorage.getItem(STORAGE_KEY); if (stored && (LOCALES as string[]).includes(stored)) return stored as Locale; const browser = navigator.language?.slice(0, 2); if (browser && (LOCALES as string[]).includes(browser)) return browser as Locale; return "en"; } interface LanguageContextValue { locale: Locale; setLocale: (locale: Locale) => void; t: (key: MessageKey, vars?: Record) => string; } const LanguageContext = createContext(undefined); export function LanguageProvider({ children }: { children: ReactNode }) { const [locale, setLocaleState] = useState(detectInitialLocale); const setLocale = useCallback((next: Locale) => { setLocaleState(next); localStorage.setItem(STORAGE_KEY, next); }, []); const t = useCallback( (key: MessageKey, vars?: Record) => translate(locale, key, vars), [locale], ); const value = useMemo(() => ({ locale, setLocale, t }), [locale, setLocale, t]); return {children}; } export function useI18n(): LanguageContextValue { const ctx = useContext(LanguageContext); if (!ctx) throw new Error("useI18n must be used within a LanguageProvider"); return ctx; }