// ============================================================
// i18n — 轻量国际化模块
// 职责：提供翻译函数和 React Context，根据 locale 返回对应语言文本
// ============================================================

import { createContext, useContext } from "react";
import { zhCN } from "./zh-CN";
import { enUS } from "./en-US";
import { jaJP } from "./ja-JP";

export type Locale = "zh-CN" | "en-US" | "ja-JP";

export type TranslationMap = Record<string, string>;

const translations: Record<Locale, TranslationMap> = {
  "zh-CN": zhCN,
  "en-US": enUS,
  "ja-JP": jaJP,
};

/** 翻译函数：根据 key 和 locale 返回翻译文本 */
export function t(key: string, locale: Locale): string {
  return translations[locale]?.[key] ?? translations["zh-CN"][key] ?? key;
}

/** 从 config.language 值解析为合法 Locale */
export function parseLocale(lang: string): Locale {
  if (lang === "en-US" || lang === "ja-JP") return lang;
  return "zh-CN";
}

// ---- React Context ----

export interface I18nContextValue {
  locale: Locale;
  t: (key: string) => string;
}

export const I18nContext = createContext<I18nContextValue>({
  locale: "zh-CN",
  t: (key) => t(key, "zh-CN"),
});

/** 组件内获取 i18n 的便捷 Hook */
export function useI18n() {
  return useContext(I18nContext);
}
