import { createI18n } from 'vue-i18n'
import en from './locales/en.json'
import cn from './locales/cn.json'

function LocaleLanguage() {
  // 优先使用sessionStorage中存储的语言设置
  const storedLang = sessionStorage.getItem('lang')
  if (storedLang && (storedLang === 'en' || storedLang === 'cn')) {
    return storedLang
  }

  // 如果没有存储的语言设置，则使用浏览器语言
  let lang = 'cn'
  if (navigator.languages.includes('zh')) {
    lang = 'cn'
  } else if (!navigator.languages.includes('zh')) {
    lang = 'en'
  }

  if (lang.indexOf('en') != -1) {
    return 'en'
  } else if (lang.indexOf('cn') != -1) {
    return 'cn'
  } else {
    return 'cn'
  }
}

const i18n = createI18n({
  locale: LocaleLanguage(),
  fallbackLocale: import.meta.env.VITE_APP_I18N_FALLBACK_LOCALE || 'cn',
  globalInjection: true,
  legacy: false,
  silentTranslationWarn: true,
  missingWarn: false,
  silentFallbackWarn: true,
  fallbackWarn: false,
  messages: {
    en,
    cn,
  },
})

export default i18n
