"use client";

import React, { createContext, useContext, useState, useEffect, useCallback } from "react";

type Language = "en" | "ku";
type Direction = "ltr" | "rtl";

interface LangContextType {
  lang: Language;
  dir: Direction;
  setLanguage: (language: Language) => void;
}

const LangContext = createContext<LangContextType | undefined>(undefined);

export function LangProvider({ children }: { children: React.ReactNode }) {
  const [lang, setLang] = useState<Language>(() => {
    if (typeof window !== "undefined") {
      return (localStorage.getItem("lang") as Language) || "en";
    }
    return "en";
  });
  const [dir, setDir] = useState<Direction>(() => {
    if (typeof window !== "undefined") {
      const storedLang = localStorage.getItem("lang");
      return storedLang === "ku" ? "rtl" : "ltr";
    }
    return "ltr";
  });

  useEffect(() => {
    if (typeof document !== "undefined") {
      document.documentElement.setAttribute("lang", lang);
      document.documentElement.setAttribute("dir", dir);
      localStorage.setItem("lang", lang);
    }
  }, [lang, dir]);

  const updateLanguage = useCallback((newLang: Language) => {
    setLang(newLang);
    setDir(newLang === "ku" ? "rtl" : "ltr");
  }, []);

  return (
    <LangContext.Provider value={{ lang, dir, setLanguage: updateLanguage }}>
      {children}
    </LangContext.Provider>
  );
}

export function useLang() {
  const context = useContext(LangContext);
  if (context === undefined) {
    throw new Error("useLang must be used within a LangProvider");
  }
  return context;
}