import { createI18n } from 'vue-i18n';
import en from './en';
import fr from './fr';

export type AppLocale = 'en' | 'fr';

const STORAGE_KEY = 'arb-lang';

// Détection fidèle au design : localStorage prioritaire, sinon langue navigateur
// (fr → FR, sinon EN).
function initialLocale(): AppLocale {
  let saved: string | null = null;
  try {
    saved = localStorage.getItem(STORAGE_KEY);
  } catch {
    /* localStorage indisponible (mode privé, etc.) */
  }
  if (saved === 'fr' || saved === 'en') return saved;
  const nav = (typeof navigator !== 'undefined' && navigator.language ? navigator.language : '').toLowerCase();
  return nav.indexOf('fr') === 0 ? 'fr' : 'en';
}

export const i18n = createI18n({
  legacy: false,
  locale: initialLocale(),
  fallbackLocale: 'en',
  messages: { en, fr },
});

export function setLocale(locale: AppLocale): void {
  i18n.global.locale.value = locale;
  try {
    localStorage.setItem(STORAGE_KEY, locale);
  } catch {
    /* ignore */
  }
}
