"use client";

import {
  createContext,
  useContext,
  useState,
  useCallback,
  useEffect,
  type ReactNode,
} from "react";
import { useRouter } from "next/navigation";
import {
  type Locale,
  type Translations,
  getTranslations,
  isRTL,
  LOCALE_COOKIE,
  runTranslationAudit,
} from "./i18n";

interface LanguageContextValue {
  locale: Locale;
  t: Translations;
  isRtl: boolean;
  setLocale: (locale: Locale) => void;
}

const LanguageContext = createContext<LanguageContextValue | null>(null);

export function LanguageProvider({
  children,
  initialLocale,
}: {
  children: ReactNode;
  initialLocale: Locale;
}) {
  const router = useRouter();
  const [locale, setLocaleState] = useState<Locale>(initialLocale);

  // Run audit once in the browser so warnings appear in the browser console
  useEffect(() => {
    runTranslationAudit();
  }, []);

  const setLocale = useCallback(
    (newLocale: Locale) => {
      setLocaleState(newLocale);
      // Persist in cookie (1 year)
      document.cookie = `${LOCALE_COOKIE}=${newLocale}; path=/; max-age=${
        60 * 60 * 24 * 365
      }; SameSite=Lax`;
      // Update document direction and lang
      document.documentElement.lang = newLocale;
      document.documentElement.dir = isRTL(newLocale) ? "rtl" : "ltr";
      router.refresh();
    },
    [router],
  );

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

export function useLanguage(): LanguageContextValue {
  const ctx = useContext(LanguageContext);
  if (!ctx) throw new Error("useLanguage must be used within LanguageProvider");
  return ctx;
}
