import { createI18n } from 'vue-i18n'
import { Locale } from 'vant'

// 1. 同步引入中文 (兜底防乱码)
import defaultZhCN from './lang/zh-CN'
import defaultVantZhCN from 'vant/es/locale/lang/zh-CN'

const i18n = createI18n({
  legacy: false,
  locale: 'zh-CN', // 初始设为中文
  fallbackLocale: 'zh-CN',
  globalInjection: true,
  messages: {
    'zh-CN': { ...defaultVantZhCN, ...defaultZhCN }
  }
})

// 2. Vant 语言包映射 (8国语言)
const vantLocales = {
  'en-US': () => import('vant/es/locale/lang/en-US'),
  'de-DE': () => import('vant/es/locale/lang/de-DE'),
  'es-ES': () => import('vant/es/locale/lang/es-ES'),
  'fr-FR': () => import('vant/es/locale/lang/fr-FR'),
  'pt-PT': () => import('vant/es/locale/lang/pt-BR'),
  'id-ID': () => import('vant/es/locale/lang/id-ID'),
  'ru-RU': () => import('vant/es/locale/lang/ru-RU'),
}

// 3. 核心加载函数
export async function loadLanguageAsync(lang) {
  if (lang === 'zh-CN') {
    setI18nLanguage('zh-CN')
    return 'zh-CN'
  }

  if (i18n.global.availableLocales.includes(lang)) {
    setI18nLanguage(lang)
    return lang
  }

  try {
    const [userMsg, vantMsg] = await Promise.all([
      import(`./lang/${lang}.js`),
      vantLocales[lang] ? vantLocales[lang]() : Promise.resolve({ default: {} })
    ])

    const messages = { ...vantMsg.default, ...userMsg.default }
    i18n.global.setLocaleMessage(lang, messages)

    setI18nLanguage(lang, vantMsg.default)
    return lang
  } catch (e) {
    console.error('Language load failed:', e)
    return 'zh-CN'
  }
}

function setI18nLanguage(lang, vantMsg) {
  i18n.global.locale.value = lang
  localStorage.setItem('app-lang', lang)
  document.querySelector('html').setAttribute('lang', lang)

  if (lang === 'zh-CN') {
    Locale.use('zh-CN', defaultVantZhCN)
  } else if (vantMsg) {
    Locale.use(lang, vantMsg)
  } else if (vantLocales[lang]) {
    vantLocales[lang]().then(mod => Locale.use(lang, mod.default))
  }
}

export default i18n