import { createI18n } from "vue-i18n";
import { isSupportedLocale } from "./locales.ts";
import { messages } from "./messages.ts";
import { readStoredLocale, writeStoredLocale } from "./storage.ts";
import { defaultLocale } from "./types.ts";
import type { SupportedLocale } from "./types.ts";
import { syncVantLocale } from "./vant.ts";

function setDocumentLanguage(locale: SupportedLocale): void {
  if (typeof document === "undefined") {
    return;
  }

  document.documentElement.lang = locale;
}

const storedLocale = readStoredLocale();
const initialLocale = storedLocale ?? defaultLocale;
if (!storedLocale) {
  writeStoredLocale(defaultLocale);
}

syncVantLocale(initialLocale);
setDocumentLanguage(initialLocale);

export const i18n = createI18n({
  legacy: false,
  locale: initialLocale,
  fallbackLocale: defaultLocale,
  messages,
});

export function getCurrentLocale(): SupportedLocale {
  const locale = i18n.global.locale.value;
  return isSupportedLocale(locale) ? locale : defaultLocale;
}

export function setLocale(locale: string): void {
  if (!isSupportedLocale(locale)) {
    return;
  }

  i18n.global.locale.value = locale;
  writeStoredLocale(locale);
  syncVantLocale(locale);
  setDocumentLanguage(locale);
}
