import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
import { translations, type Lang, type Dict } from "./translations";

type Ctx = { lang: Lang; setLang: (l: Lang) => void; t: Dict };

const I18nContext = createContext<Ctx | null>(null);

export function I18nProvider({ children }: { children: ReactNode }) {
  const [lang, setLangState] = useState<Lang>("es");

  useEffect(() => {
    if (typeof window === "undefined") return;
    const htmlLang = document.documentElement.lang;
    if (htmlLang === "fr" || htmlLang === "en" || htmlLang === "es") {
      setLangState(htmlLang as Lang);
    }
    const saved = window.localStorage.getItem("mc-lang") as Lang | null;
    if (saved === "fr" || saved === "en" || saved === "es") setLangState(saved);
  }, []);

  const setLang = (l: Lang) => {
    setLangState(l);
    if (typeof window !== "undefined") window.localStorage.setItem("mc-lang", l);
    if (typeof document !== "undefined") document.documentElement.lang = l;
  };

  const value = useMemo<Ctx>(() => {
    const dict = translations[lang];
    if (!dict) return { lang: "es", setLang, t: translations.es };
    return { lang, setLang, t: dict };
  }, [lang]);
  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}

export function useI18n() {
  const ctx = useContext(I18nContext);
  if (!ctx) throw new Error("useI18n must be used within I18nProvider");
  return ctx;
}
