import { useEffect } from "react";
import { TranslationContainer, useTranslation } from "react-i18n-lite";
import { LOCALE_STORAGE_KEY, locales, resolveDefaultLanguage, type SupportedLanguage } from "../locales";

function LanguagePersistence() {
  const { language, setLanguage } = useTranslation();

  useEffect(() => {
    const saved = localStorage.getItem(LOCALE_STORAGE_KEY) as SupportedLanguage | null;
    if (saved === "en-US" || saved === "es-ES") {
      setLanguage(saved);
    }
  }, [setLanguage]);

  useEffect(() => {
    localStorage.setItem(LOCALE_STORAGE_KEY, language);
    document.documentElement.lang = language.startsWith("es") ? "es" : "en";
  }, [language]);

  return null;
}

export function I18nProvider({ children }: { children: React.ReactNode }) {
  return (
    <TranslationContainer locales={locales} defaultLanguage={resolveDefaultLanguage()}>
      <LanguagePersistence />
      {children}
    </TranslationContainer>
  );
}
