
import { createI18n } from "vue-i18n";
import { localeMap } from "./config";
import { setHtmlPageLang, setLoadLocalePool } from "./helper";
import { useLocaleStoreWithOut } from "../store/modules/locale";
import enUS from "./lang/en_US";
import zhCN from "./lang/zh_CN";

/** Vite/ESM：default 导出即 { message, ... }；部分 webpack 链路上可能再包一层 .default，两处都兼容 */
function getLocaleMessages(mod: typeof zhCN | typeof enUS) {
  type Bundle = { message?: Record<string, unknown> };
  const withMaybeDefault = mod as Bundle & { default?: Bundle };
  const bundle = withMaybeDefault.default ?? withMaybeDefault;
  return bundle.message ?? {};
}

function createI18nOptions() {
  const localeStore = useLocaleStoreWithOut();
  const locale = localeStore.getLocale;
  const defaultLocal = locale == "zh_CN" ? zhCN : enUS;
  const message = getLocaleMessages(defaultLocal);

  setHtmlPageLang(locale);
  setLoadLocalePool((loadLocalePool) => {
    loadLocalePool.push(locale);
  });

  return {
    locale,
    legacy: false,
    fallbackLocale: localeMap.zh_CN, // set fallback locale
    messages: {
      [locale]: message as { [key: string]: string },
    },
    globalInjection: true,
    silentTranslationWarn: true, // true - warning off
    missingWarn: false,
    silentFallbackWarn: true,
  };
}

const options = createI18nOptions();
export const i18n = createI18n(options);

// setup i18n instance with global
// export function setupI18n(app: App) {
//   app.use(i18n);
// }
