import { createContext, createSignal, useContext, type ParentProps } from "solid-js";
import type { LocaleCode } from "@ben-to/i18n/dictionary";

export type AppLocaleValue = Readonly<{
  locale: () => LocaleCode;
  setLocale: (code: LocaleCode) => void;
}>;

const AppLocaleContext = createContext<AppLocaleValue>();

export function AppLocaleProvider(props: ParentProps) {
  const [locale, setLocale] = createSignal<LocaleCode>("fr");
  const value: AppLocaleValue = {
    locale,
    setLocale
  };
  return <AppLocaleContext.Provider value={value}>{props.children}</AppLocaleContext.Provider>;
}

export function useAppLocale(): AppLocaleValue {
  const ctx = useContext(AppLocaleContext);
  if (!ctx) {
    throw new Error("useAppLocale doit être utilisé sous AppLocaleProvider");
  }
  return ctx;
}
