import { zhCN } from "./locales/zh-CN";
import { zhTW } from "./locales/zh-TW";
import { enUS } from "./locales/en-US";

// t() 仍是纯函数，方便 lib 层非 React 上下文里调用。
// 切换语言由 store 触发：store.setLocale 会同时同步到此模块（写 localStorage
// + 更新 module state）；UI 通过 RouterProvider key={locale} 强制重挂载。

// zhCN 用 as const 锁定 key 集合作为类型推导基准，但值仍按 string 处理，
// 否则 Partial<TranslationDict> 会要求其他 locale 重复同样的 literal。
export type TranslationKey = keyof typeof zhCN;
export type TranslationDict = Record<TranslationKey, string>;
export type Locale = "zh-CN" | "zh-TW" | "en-US";

export const SUPPORTED_LOCALES: readonly Locale[] = [ "zh-CN", "zh-TW", "en-US" ] as const;

const dictionaries: Record<Locale, Partial<TranslationDict>> = {
    "zh-CN": zhCN,
    "zh-TW": zhTW,
    "en-US": enUS,
};

const STORAGE_KEY = "cdrop.locale";

function readStorageLocale(): Locale | null
{
    if (typeof window === "undefined") { return null; }
    const v = window.localStorage.getItem(STORAGE_KEY);
    if (v === "zh-CN" || v === "zh-TW" || v === "en-US") { return v; }
    return null;
}

// 默认 locale：遍历 navigator.languages，先撞到一个中文标签（zh*）就按下面
// 的细分逻辑判定简繁；先撞到 en 取英文；二者都没有则回退英文。
//
// 中文细分：
//   1. 标签内含 "hans" → 简体；含 "hant" → 繁体
//   2. 区域子标签：cn / sg → 简体；tw / hk / mo → 繁体
//   3. 都不命中 → 简体（覆盖裸 "zh" 与未知地区）
function detectBrowserLocale(): Locale
{
    if (typeof navigator === "undefined") { return "en-US"; }
    const langs = navigator.languages && navigator.languages.length > 0
        ? navigator.languages
        : ( navigator.language ? [ navigator.language ] : [] );
    for (const raw of langs)
    {
        const l = raw.toLowerCase();
        if (l.startsWith("zh")) { return classifyChinese(l); }
        if (l.startsWith("en")) { return "en-US"; }
    }
    return "en-US";
}

function classifyChinese(lower: string): Locale
{
    if (lower.includes("hans")) { return "zh-CN"; }
    if (lower.includes("hant")) { return "zh-TW"; }
    const parts = lower.split("-");
    for (const p of parts)
    {
        if (p === "cn" || p === "sg") { return "zh-CN"; }
        if (p === "tw" || p === "hk" || p === "mo") { return "zh-TW"; }
    }
    return "zh-CN";
}

let currentLocale: Locale = readStorageLocale() ?? detectBrowserLocale();
if (typeof document !== "undefined")
{
    document.documentElement.lang = currentLocale;
}

const PLACEHOLDER = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;

export function setLocale(locale: Locale): void
{
    currentLocale = locale;
    if (typeof window !== "undefined")
    {
        window.localStorage.setItem(STORAGE_KEY, locale);
    }
    if (typeof document !== "undefined")
    {
        document.documentElement.lang = locale;
    }
}

export function getLocale(): Locale
{
    return currentLocale;
}

export function t(key: TranslationKey, vars?: Record<string, string | number>): string
{
    // currentLocale 缺失的 key 自动 fallback 到 zh-CN。
    const template = dictionaries[currentLocale][key] ?? zhCN[key];
    if (!vars) { return template; }
    return template.replace(PLACEHOLDER, (_, name: string) =>
    {
        const v = vars[name];
        return v === undefined ? "" : String(v);
    });
}
