import { createContext, useContext, useEffect, useState, ReactNode } from "react";
import { en, ar } from "../lib/i18n/translations";

type Language = "en" | "ar";

interface LanguageContextType {
  language: Language;
  t: typeof en;
  setLanguage: (lang: Language) => void;
  dir: "ltr" | "rtl";
}

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

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [language, setLanguage] = useState<Language>(() => {
    const saved = localStorage.getItem("language");
    return (saved as Language) || "ar"; // Default to Arabic for EHSAN POC
  });

  useEffect(() => {
    localStorage.setItem("language", language);
    const dir = language === "ar" ? "rtl" : "ltr";
    document.documentElement.dir = dir;
    document.documentElement.lang = language;
  }, [language]);

  const value = {
    language,
    t: language === "ar" ? ar : en,
    setLanguage,
    dir: (language === "ar" ? "rtl" : "ltr") as "ltr" | "rtl",
  };

  return (
    <LanguageContext.Provider value={value}>
      {children}
    </LanguageContext.Provider>
  );
}

export function useLanguage() {
  const context = useContext(LanguageContext);
  if (context === undefined) {
    throw new Error("useLanguage must be used within a LanguageProvider");
  }
  return context;
}
