import { defineNuxtPlugin, useRuntimeConfig } from '#app'
import { createI18n } from 'vue-i18n'
import en from '~/locales/en'
import ca from '~/locales/ca'
import es from '~/locales/es'

const locales = ['en', 'ca', 'es'] as const
type LocaleType = (typeof locales)[number]

function getSavedLocale(): LocaleType {
  if (typeof window !== 'undefined') {
    const saved = localStorage.getItem('quibot-locale')
    if (saved && locales.includes(saved as LocaleType)) {
      return saved as LocaleType
    }
  }
  return 'en'
}

export default defineNuxtPlugin((nuxtApp) => {
  const locale = getSavedLocale()
  const i18n = createI18n({
    legacy: false,
    locale,
    fallbackLocale: 'en',
    messages: { en, ca, es },
  })

  nuxtApp.vueApp.use(i18n)

  // Expose setLocale for global access
  nuxtApp.provide('setLocale', (l: LocaleType) => {
    if (locales.includes(l)) {
      i18n.global.locale.value = l
      localStorage.setItem('quibot-locale', l)
    }
  })
})
