import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
import { useLocation } from "react-router-dom";
import type { Locale, Localized } from "@/types/sections";
import { detectLocaleFromPath } from "./routes";

interface LocaleContextValue {
  locale: Locale;
  setLocale: (l: Locale) => void;
  t: <T>(value: Localized<T>) => T;
}

const LocaleContext = createContext<LocaleContextValue | null>(null);

export function LocaleProvider({ children }: { children: ReactNode }) {
  const location = useLocation();
  const pathLocale = detectLocaleFromPath(location.pathname);

  const [locale, setLocaleState] = useState<Locale>(pathLocale);

  // Keep locale in sync with the URL (URL is the source of truth).
  useEffect(() => {
    if (pathLocale !== locale) setLocaleState(pathLocale);
  }, [pathLocale, locale]);

  // Keep <html lang> attribute in sync.
  useEffect(() => {
    document.documentElement.lang = locale === "fr" ? "fr-CA" : "en-CA";
  }, [locale]);

  const value = useMemo<LocaleContextValue>(
    () => ({
      locale,
      setLocale: setLocaleState,
      t: <T,>(v: Localized<T>) => v[locale],
    }),
    [locale],
  );

  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}

export function useLocale() {
  const ctx = useContext(LocaleContext);
  if (!ctx) throw new Error("useLocale must be used within <LocaleProvider>");
  return ctx;
}