import { createI18n } from 'vue-i18n'
import { useStorage } from '@vueuse/core'

// Import base locale
import en from './locales/en'

// Define available locales
export const AVAILABLE_LOCALES = ['en', 'es', 'fr', 'de', 'zh'] as const
export type AvailableLocale = typeof AVAILABLE_LOCALES[number]

// Type for our messages
export type MessageSchema = typeof en

// Create persistent storage for user's locale preference
const savedLocale = useStorage<AvailableLocale>('user-locale', 'en')

// Async locale loading
async function loadLocale(locale: AvailableLocale): Promise<MessageSchema> {
  try {
    const messages = await import(`./locales/${locale}.ts`)
    return messages.default
  } catch (error) {
    console.error(`Failed to load locale ${locale}:`, error)
    return en // Fallback to English
  }
}

// Create i18n instance with type casting to avoid TypeScript errors
export const i18n = createI18n({
  legacy: false,
  locale: savedLocale.value,
  fallbackLocale: 'en',
  messages: {
    en: en // Explicitly set the English messages
  }
} as any) // Type assertion to bypass type checking for now

// Function to change locale
export async function changeLocale(locale: AvailableLocale) {
  try {
    // Only load if it's not already loaded
    if (!i18n.global.availableLocales.includes(locale)) {
      const messages = await loadLocale(locale)
      i18n.global.setLocaleMessage(locale, messages)
    }
    
    // Set the locale
    // @ts-ignore - We know the global.locale object has a writable value property
    i18n.global.locale.value = locale
    savedLocale.value = locale
    document.querySelector('html')?.setAttribute('lang', locale)
  } catch (error) {
    console.error(`Failed to change locale to ${locale}:`, error)
  }
}

// Type guard for available locales
export function isAvailableLocale(locale: string): locale is AvailableLocale {
  return AVAILABLE_LOCALES.includes(locale as AvailableLocale)
}

// Initialize with saved locale if different from default
if (savedLocale.value !== 'en') {
  changeLocale(savedLocale.value)
} 