import { createI18n } from "vue-i18n";

type LocaleCode = "zh" | "en";
type LocaleMessages = Record<string, unknown>;

const LOCALE_KEY = "hwlab_locale";
const DEFAULT_LOCALE: LocaleCode = "zh";

const localeLoaders: Record<LocaleCode, () => Promise<{ default: LocaleMessages }>> = {
  zh: () => import("./locales/zh"),
  en: () => import("./locales/en")
};

export const i18n = createI18n({ legacy: false, locale: getLocale(), fallbackLocale: DEFAULT_LOCALE, messages: {} });
const loadedLocales = new Set<LocaleCode>();

function isLocaleCode(value: string): value is LocaleCode {
  return value === "zh" || value === "en";
}

export function getLocale(): LocaleCode {
  const saved = typeof localStorage !== "undefined" ? localStorage.getItem(LOCALE_KEY) : null;
  if (saved && isLocaleCode(saved)) return saved;
  const browserLang = typeof navigator !== "undefined" ? navigator.language.toLowerCase() : "";
  return browserLang.startsWith("en") ? "en" : DEFAULT_LOCALE;
}

export async function loadLocaleMessages(locale: LocaleCode): Promise<void> {
  if (loadedLocales.has(locale)) return;
  const module = await localeLoaders[locale]();
  i18n.global.setLocaleMessage(locale, module.default);
  loadedLocales.add(locale);
}

export async function initI18n(): Promise<void> {
  const locale = getLocale();
  await loadLocaleMessages(locale);
  document.documentElement.setAttribute("lang", locale === "zh" ? "zh-CN" : "en");
}

export default i18n;
