"use client";

import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { bn, en, type Dictionary } from "@/lib/i18n";
import { applyAcademicLabels as applyAcademicLabelsToDict } from "@/lib/academic-labels";
import type { Locale } from "@/lib/utils";

interface LanguageContextValue {
  locale: Locale;
  /** localized dictionary with the institution's academic-term renames merged in */
  t: Dictionary;
  /** localized dictionary without renames (Control Panel needs the defaults) */
  rawT: Dictionary;
  setLocale: (locale: Locale) => void;
  toggle: () => void;
  /** portal layout: apply the institution's academic-term renames (null clears) */
  applyAcademicLabels: (labels: Record<string, string> | null) => void;
}

const LanguageContext = createContext<LanguageContextValue>({
  locale: "en",
  t: en,
  rawT: en,
  setLocale: () => {},
  toggle: () => {},
  applyAcademicLabels: () => {},
});

export function LanguageProvider({ children }: { children: React.ReactNode }) {
  const [locale, setLocaleState] = useState<Locale>("en");
  const [academicLabels, setAcademicLabelsState] = useState<Record<string, string> | null>(null);

  useEffect(() => {
    const stored = window.localStorage.getItem("ems_locale") as Locale | null;
    if (stored === "bn" || stored === "en") setLocaleState(stored);
  }, []);

  useEffect(() => {
    document.documentElement.lang = locale === "bn" ? "bn" : "en";
    window.localStorage.setItem("ems_locale", locale);
  }, [locale]);

  const setLocale = useCallback((next: Locale) => setLocaleState(next), []);
  const toggle = useCallback(
    () => setLocaleState((prev) => (prev === "en" ? "bn" : "en")),
    []
  );

  const applyAcademicLabels = useCallback((labels: Record<string, string> | null) => {
    setAcademicLabelsState((prev) => {
      const next = labels && Object.keys(labels).length > 0 ? labels : null;
      if (JSON.stringify(prev) === JSON.stringify(next)) return prev;
      return next;
    });
  }, []);

  const baseT = locale === "bn" ? bn : en;
  const t = useMemo(
    () => (academicLabels ? applyAcademicLabelsToDict(baseT, academicLabels, locale) : baseT),
    [baseT, academicLabels, locale]
  );

  return (
    <LanguageContext.Provider value={{ locale, t, rawT: baseT, setLocale, toggle, applyAcademicLabels }}>
      {children}
    </LanguageContext.Provider>
  );
}

export function useLang() {
  return useContext(LanguageContext);
}
