// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
"use client";
import { createContext, useContext, useEffect, useState } from "react";
import { t as translate, type Lang, type TKey } from "@/lib/i18n";

const Ctx = createContext<{
  lang: Lang;
  setLang: (l: Lang) => void;
  t: (k: TKey) => string;
}>({ lang: "fr", setLang: () => {}, t: (k) => translate("fr", k) });

export function LangProvider({ children }: { children: React.ReactNode }) {
  const [lang, setLangState] = useState<Lang>("fr");
  useEffect(() => {
    const saved = window.localStorage.getItem("vp-lang");
    if (saved !== "en" && saved !== "fr") return;
    const id = setTimeout(() => setLangState(saved), 0);
    return () => clearTimeout(id);
  }, []);
  const setLang = (l: Lang) => {
    setLangState(l);
    window.localStorage.setItem("vp-lang", l);
  };
  return (
    <Ctx.Provider value={{ lang, setLang, t: (k) => translate(lang, k) }}>
      {children}
    </Ctx.Provider>
  );
}

export function useLang() {
  return useContext(Ctx);
}

export function LangToggle() {
  const { lang, setLang } = useLang();
  return (
    <button
      onClick={() => setLang(lang === "fr" ? "en" : "fr")}
      className="vp-mono min-h-[36px] rounded-full border-[1.5px] border-ink bg-surface px-4 py-1.5 text-[12px] font-bold uppercase tracking-[0.08em] text-ink transition-all hover:bg-ink hover:text-lime"
      aria-label="Changer de langue / Switch language"
    >
      {lang === "fr" ? "EN" : "FR"}
    </button>
  );
}
