import React, { createContext, useCallback, useContext, useMemo, useState, } from "react"; import { languageForHomePathname } from "./languageRoutes"; import type { Dict } from "./locales/types"; import { zhDict } from "./locales/zh-CN"; import { enDict } from "./locales/en"; import { jaDict } from "./locales/ja"; import { koDict } from "./locales/ko"; import { viDict } from "./locales/vi"; import { idDict } from "./locales/id"; import { msDict } from "./locales/ms"; export type Lang = "zh-CN" | "en" | "ja" | "ko" | "vi" | "id" | "ms"; const dict: Record = { "zh-CN": zhDict, en: enDict, ja: jaDict, ko: koDict, vi: viDict, id: idDict, ms: msDict, }; /** Fixed locale lookup (admin UI uses Simplified Chinese). */ export function tLang(lang: Lang, key: string): string { return dict[lang][key] || dict.en[key] || key; } type Ctx = { lang: Lang; setLang: (l: Lang) => void; t: (k: string) => string }; const I18nCtx = createContext(null); const LANG_KEY = "ark_lang"; export function I18nProvider({ children }: { children: React.ReactNode }) { const [lang, setLangState] = useState(() => { const routeLang = languageForHomePathname(window.location.pathname); if (routeLang) return routeLang; if (window.location.pathname === "/") return "en"; const s = localStorage.getItem(LANG_KEY); if (s === "zh" || s === "zh-TW") return "zh-CN"; if ( s === "zh-CN" || s === "en" || s === "ja" || s === "ko" || s === "vi" || s === "id" || s === "ms" ) return s; return "en"; }); const setLang = useCallback((l: Lang) => { localStorage.setItem(LANG_KEY, l); setLangState(l); }, []); const t = useCallback( (k: string) => dict[lang][k] || dict.en[k] || k, [lang], ); const v = useMemo(() => ({ lang, setLang, t }), [lang, t]); return {children}; } export function useI18n() { const v = useContext(I18nCtx); if (!v) throw new Error("I18nProvider missing"); return v; } export function langQuery(lang: Lang) { return lang; }