import type { LangDict, Locales } from "~/i18n/locales";
import { en } from "~/i18n/en";
import { it } from "~/i18n/it";
import {
  createContext,
  useContext,
  useMemo,
  type FC,
  type ReactNode,
} from "react";

type I18nContextType = {
  locale: Locales;
};

const I18nContext = createContext<I18nContextType>({
  locale: "it",
});

export const I18nProvider: FC<{
  children: ReactNode;
  locale: string | undefined;
}> = ({ children, locale }) => {
  return (
    <I18nContext.Provider value={{ locale: validateLocale(locale) }}>
      {children}
    </I18nContext.Provider>
  );
};

export const useTranslation = () => {
  const { locale } = useContext(I18nContext);
  return useMemo(() => {
    return (
      locale === "en" ? { locale: "en", t: en } : { locale: "it", t: it }
    ) as {
      locale: Locales;
      t: LangDict;
    };
  }, [locale]);
};
const validateLocale = (locale: string | undefined): Locales => {
  if (locale === "en") return "en";
  return "it";
};
