"use client";

import { createContext, useContext, useEffect, useState, useCallback } from "react";
import { defaultLocale, locales, type Locale } from "@i18n/config";

interface LocaleContextValue {
  locale: Locale;
  setLocale: (locale: Locale) => void;
}

const LocaleContext = createContext<LocaleContextValue>({
  locale: defaultLocale,
  setLocale: () => {},
});

function getLocaleFromCookie(): Locale {
  if (typeof document === "undefined") return defaultLocale;
  const match = document.cookie.match(/(?:^|; )locale=([^;]*)/);
  const raw = match ? decodeURIComponent(match[1]) : defaultLocale;
  return (locales as readonly string[]).includes(raw) ? (raw as Locale) : defaultLocale;
}

export function LocaleProvider({ children }: { children: React.ReactNode }) {
  const [locale, setLocaleState] = useState<Locale>(defaultLocale);

  useEffect(() => {
    setLocaleState(getLocaleFromCookie());
  }, []);

  const setLocale = useCallback((newLocale: Locale) => {
    // Persist in cookie (1 year, SameSite=Lax)
    document.cookie = `locale=${encodeURIComponent(newLocale)}; path=/; max-age=${60 * 60 * 24 * 365}; SameSite=Lax`;
    setLocaleState(newLocale);
    // Reload to let next-intl pick up the new locale server-side
    window.location.reload();
  }, []);

  return (
    <LocaleContext.Provider value={{ locale, setLocale }}>
      {children}
    </LocaleContext.Provider>
  );
}

export function useLocale() {
  return useContext(LocaleContext);
}
