// Sistema i18n — Context + Provider + hook useLang
// translations.js deve essere caricato prima di questo file

const LangContext = React.createContext(null);

function LangProvider({ children }) {
  const [lang, setLangState] = React.useState(() => {
    // Prima priorità: preferenza salvata dall'utente
    const saved = localStorage.getItem('langPref');
    if (saved === 'it' || saved === 'de') return saved;
    // Seconda priorità: lingua del browser
    const browser = (navigator.language || 'it').toLowerCase();
    return browser.startsWith('de') ? 'de' : 'it';
  });

  const setLang = (newLang) => {
    setLangState(newLang);
    localStorage.setItem('langPref', newLang);
    document.documentElement.lang = newLang;
  };

  // Sincronizza l'attributo lang sull'html al mount e ad ogni cambio
  React.useEffect(() => {
    document.documentElement.lang = lang;
  }, [lang]);

  // Risolve una chiave puntata tipo "rsvp.fields.name" nel dizionario attivo
  const t = (key) => {
    const keys = key.split('.');
    let value = window.TRANSLATIONS[lang];
    for (const k of keys) {
      if (value && typeof value === 'object') value = value[k];
      else return key;
    }
    return (value !== undefined && value !== null) ? value : key;
  };

  return (
    <LangContext.Provider value={{ lang, setLang, t }}>
      {children}
    </LangContext.Provider>
  );
}

function useLang() {
  const ctx = React.useContext(LangContext);
  if (!ctx) throw new Error('useLang deve essere usato dentro LangProvider');
  return ctx;
}

function formatDate(isoDate, lang, options = { day: 'numeric', month: 'long', year: 'numeric' }) {
  const locale = lang === 'de' ? 'de-DE' : 'it-IT';
  return new Intl.DateTimeFormat(locale, options).format(new Date(isoDate));
}

window.LangProvider = LangProvider;
window.useLang = useLang;
window.formatDate = formatDate;
