import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';

import en from './en';
import zh from './zh';

export const LanguageAbbreviation = Object.freeze({
  En: 'en',
  Zh: 'zh',
} as const)

export type LanguageAbbreviationType = (typeof LanguageAbbreviation)[keyof typeof LanguageAbbreviation]

const resources = {
  [LanguageAbbreviation.En]: en,
  [LanguageAbbreviation.Zh]: zh,
};

// 语言变更时同步更新 dayjs 语言
const updateDayjsLocale = (lng: string) => {
  if (lng === LanguageAbbreviation.Zh) {
    dayjs.locale('zh-cn');
  } else {
    dayjs.locale('en');
  }
};

i18n
  .use(initReactI18next)
  .use(LanguageDetector)
  .init({
    detection: {
      lookupLocalStorage: 'lng',
      order: ['localStorage', 'navigator', 'htmlTag'],
      caches: ['localStorage'],
    },
    supportedLngs: Object.values(LanguageAbbreviation),
    resources,
    fallbackLng: LanguageAbbreviation.En,
    defaultNS: 'translation',
    interpolation: {
      escapeValue: false,
    },
  });

// 监听语言变更
i18n.on('languageChanged', updateDayjsLocale);

// 初始化时设置 dayjs 语言
updateDayjsLocale(i18n.language);

export default i18n;