import { createI18n } from 'vue-i18n'
import de from './locales/de'
import en from './locales/en'
import es from './locales/es'
import fr from './locales/fr'
import ar from './locales/ar'
import ru from './locales/ru'
import pl from './locales/pl'

export const SUPPORTED_LOCALES = [
  { code: 'de', name: 'Deutsch', flag: 'DE' },
  { code: 'es', name: 'Español', flag: 'ES' },
  { code: 'en', name: 'English', flag: 'GB' },
  { code: 'ar', name: 'العربية', flag: 'SA', rtl: true },
  { code: 'ru', name: 'Русский', flag: 'RU' },
  { code: 'fr', name: 'Français', flag: 'FR' },
  { code: 'pl', name: 'Polski', flag: 'PL' },
] as const

export type LocaleCode = typeof SUPPORTED_LOCALES[number]['code']

// Get saved locale or browser default
function getDefaultLocale(): LocaleCode {
  const saved = localStorage.getItem('locale') as LocaleCode
  if (saved && SUPPORTED_LOCALES.some(l => l.code === saved)) {
    return saved
  }
  
  // Try browser language
  const browserLang = navigator.language.split('-')[0]
  const match = SUPPORTED_LOCALES.find(l => l.code === browserLang)
  if (match) {
    return match.code
  }
  
  return 'de' // Default to German
}

const i18n = createI18n({
  legacy: false,
  locale: getDefaultLocale(),
  fallbackLocale: 'de',
  messages: {
    de,
    en,
    es,
    fr,
    ar,
    ru,
    pl,
  },
})

// Update document direction for RTL languages
export function setLocale(locale: LocaleCode) {
  const localeInfo = SUPPORTED_LOCALES.find(l => l.code === locale)
  if (localeInfo) {
    i18n.global.locale.value = locale
    localStorage.setItem('locale', locale)
    document.documentElement.dir = localeInfo.rtl ? 'rtl' : 'ltr'
    document.documentElement.lang = locale
  }
}

// Initialize direction on load
const currentLocale = SUPPORTED_LOCALES.find(l => l.code === getDefaultLocale())
if (currentLocale?.rtl) {
  document.documentElement.dir = 'rtl'
}
document.documentElement.lang = getDefaultLocale()

export default i18n
