"use client";

import {
  createContext,
  useCallback,
  useContext,
  useMemo,
  useState,
  type ReactNode,
} from "react";
import {
  DEFAULT_LOCALE,
  type AppLocale,
  isAppLocale,
  resolveAppLocale,
} from "./config";

interface LocaleContextValue {
  locale: AppLocale;
  setLocale: (locale: AppLocale) => void;
}

const LocaleContext = createContext<LocaleContextValue | null>(null);

const STORAGE_KEY = "agnet-locale";

function readStoredLocale(): AppLocale {
  if (typeof window === "undefined") return DEFAULT_LOCALE;
  const stored = localStorage.getItem(STORAGE_KEY);
  return stored && isAppLocale(stored) ? stored : DEFAULT_LOCALE;
}

interface Props {
  children: ReactNode;
  initialLocale?: AppLocale | string | null;
}

export function LocaleProvider({ children, initialLocale }: Props) {
  const [locale, setLocaleState] = useState<AppLocale>(() =>
    initialLocale ? resolveAppLocale(initialLocale) : readStoredLocale(),
  );

  const setLocale = useCallback((next: AppLocale) => {
    setLocaleState(next);
    if (typeof window !== "undefined") {
      localStorage.setItem(STORAGE_KEY, next);
    }
  }, []);

  const value = useMemo(() => ({ locale, setLocale }), [locale, setLocale]);

  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}

export function useLocale(): LocaleContextValue {
  const ctx = useContext(LocaleContext);
  if (!ctx) {
    return {
      locale: DEFAULT_LOCALE,
      setLocale: () => {},
    };
  }
  return ctx;
}
