"use client";
import React, { createContext, useContext, useState, useEffect } from "react";
import { es } from "@/lang/es";
import { ca } from "@/lang/ca";
import { en } from "@/lang/en";

type Language = "es" | "ca" | "en";

const dictionaries = { es, ca, en };

interface LanguageContextType {
  locale: Language;
  setLocale: (lang: Language) => void;
  t: typeof es; 
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

export const LanguageProvider = ({ children }: { children: React.ReactNode }) => {
  const [locale, setLocaleState] = useState<Language>("es");


  useEffect(() => {
    const savedLang = localStorage.getItem("language") as Language;
    if (savedLang && (savedLang === "es" || savedLang === "ca" || savedLang === "en")) {
      setLocaleState(savedLang);
    }
  }, []);

  const setLocale = (lang: Language) => {
    setLocaleState(lang);
    localStorage.setItem("language", lang);
  };

  const t = dictionaries[locale];

  return (
    <LanguageContext.Provider value={{ locale, setLocale, t }}>
      {children}
    </LanguageContext.Provider>
  );
};

export const useLanguage = () => {
  const context = useContext(LanguageContext);
  if (!context) throw new Error("useLanguage debe usarse dentro de un LanguageProvider");
  return context;
};