import { createContext, useContext, useState, useCallback, type ReactNode } from "react"; import type { Locale, Translations } from "./types"; import { en } from "./en"; import { zh } from "./zh"; const TRANSLATIONS: Record = { en, zh }; const STORAGE_KEY = "hermes-locale"; function getInitialLocale(): Locale { try { const stored = localStorage.getItem(STORAGE_KEY); if (stored === "en" || stored === "zh") return stored; } catch { // SSR or privacy mode } return "en"; } interface I18nContextValue { locale: Locale; setLocale: (l: Locale) => void; t: Translations; } const I18nContext = createContext({ locale: "en", setLocale: () => {}, t: en, }); export function I18nProvider({ children }: { children: ReactNode }) { const [locale, setLocaleState] = useState(getInitialLocale); const setLocale = useCallback((l: Locale) => { setLocaleState(l); try { localStorage.setItem(STORAGE_KEY, l); } catch { // ignore } }, []); const value: I18nContextValue = { locale, setLocale, t: TRANSLATIONS[locale], }; return ( {children} ); } export function useI18n() { return useContext(I18nContext); }