import { defineBoot } from '#q-app/wrappers'
import { createI18n } from 'vue-i18n'
import messages from 'src/i18n'

let i18n = null

export default defineBoot(({ app }) => {
  const getLocale = () => {
    const saved = localStorage.getItem('lang')
    if (saved && messages[saved]) return saved
    
    const browserLang = navigator.language
    if (messages[browserLang]) return browserLang
    
    const shortLang = browserLang.split('-')[0]
    return Object.keys(messages).find(lang => lang.startsWith(shortLang)) || 'en-US'
  }

  const locale = getLocale()
  
  i18n = createI18n({
    locale,
    fallbackLocale: 'en-US',
    legacy: false,
    messages
  })

  localStorage.setItem('lang', locale)
  document.documentElement.lang = locale
  app.use(i18n)
})

export const setGlobalLocale = (newLocale) => {
  if (i18n && i18n.global) {
    i18n.global.locale.value = newLocale
    localStorage.setItem('lang', newLocale)
    document.documentElement.lang = newLocale
  }
}