import { createI18n } from 'vue-i18n'
import { enUS } from './locales/en-US'
import { zhCN } from './locales/zh-CN'

export const I18N_LOCALE_KEY = 'jgjs-locale-v1'
export const DEFAULT_LOCALE = 'zh-CN'

const messages = {
  'zh-CN': zhCN,
  'en-US': enUS
} as const

export type AppLocale = keyof typeof messages

const getInitialLocale = (): AppLocale => {
  if (typeof window === 'undefined') return DEFAULT_LOCALE
  const saved = String(localStorage.getItem(I18N_LOCALE_KEY) || '').trim() as AppLocale
  if (saved in messages) return saved
  const language = String(navigator.language || '').toLowerCase()
  return language.startsWith('en') ? 'en-US' : DEFAULT_LOCALE
}

export const i18n = createI18n({
  legacy: false,
  locale: getInitialLocale(),
  fallbackLocale: DEFAULT_LOCALE,
  messages
})

export const setAppLocale = (locale: AppLocale) => {
  i18n.global.locale.value = locale
  if (typeof window !== 'undefined') {
    localStorage.setItem(I18N_LOCALE_KEY, locale)
  }
}

