"use client";
import {
  createContext,
  useContext,
  useEffect,
  useState,
  ReactNode,
  createElement,
} from "react";
import enStrings from "./en.json";
import hiStrings from "./hi.json";
import guStrings from "./gu.json";

export type Language = "en" | "hi" | "gu";

const STRINGS: Record<Language, Record<string, string>> = {
  en: enStrings as Record<string, string>,
  hi: hiStrings as Record<string, string>,
  gu: guStrings as Record<string, string>,
};

const LANG_KEY = "doliplay_lang";

interface I18nContextType {
  lang: Language;
  setLang: (lang: Language) => void;
  t: (key: string) => string;
}

const I18nContext = createContext<I18nContextType>({
  lang: "en",
  setLang: () => { },
  t: (key) => (enStrings as Record<string, string>)[key] ?? key,
});

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [lang, setLangState] = useState<Language>("en");

  useEffect(() => {
    const saved = localStorage.getItem(LANG_KEY) as Language | null;
    if (saved && STRINGS[saved]) setLangState(saved);
  }, []);

  const setLang = (l: Language) => {
    setLangState(l);
    localStorage.setItem(LANG_KEY, l);
  };

  const t = (key: string): string =>
    STRINGS[lang][key] ?? STRINGS["en"][key] ?? key;

  return createElement(I18nContext.Provider, { value: { lang, setLang, t } }, children);
}

export const useTranslation = () => useContext(I18nContext);
