import { createI18n } from 'vue-i18n'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import zhTw from 'element-plus/es/locale/lang/zh-tw'
import en from 'element-plus/es/locale/lang/en'

import zhCN from './locales/zh-CN'
import zhTW from './locales/zh-TW'
import enUS from './locales/en'
import { isLocaleCode, type LocaleCode } from './types'

export const LOCALE_STORAGE_KEY = 'prism_locale'
export const DEFAULT_LOCALE: LocaleCode = 'zh-CN'

export const elementLocales = {
  'zh-CN': zhCn,
  'zh-TW': zhTw,
  en,
} as const

function readStoredLocale(): LocaleCode {
  const stored = localStorage.getItem(LOCALE_STORAGE_KEY)
  return stored && isLocaleCode(stored) ? stored : DEFAULT_LOCALE
}

const i18n = createI18n({
  legacy: false,
  locale: readStoredLocale(),
  fallbackLocale: DEFAULT_LOCALE,
  messages: {
    'zh-CN': zhCN,
    'zh-TW': zhTW,
    en: enUS,
  },
})

export function applyDocumentLocale(locale: LocaleCode) {
  document.documentElement.lang = locale
}

export function setI18nLocale(locale: LocaleCode) {
  i18n.global.locale.value = locale
  applyDocumentLocale(locale)
}

export default i18n
