import { createContext, useMemo } from 'react';
import type { ReactNode } from 'react';
import type { I18nContextValue, InterpolationParams, TranslationMap } from './types';
import { interpolate, resolveKey } from './resolve';

export const I18nContext = createContext<I18nContextValue>({
  t: (key: string) => key,
  locale: 'en',
});

type I18nProviderProps = {
  translations: TranslationMap;
  locale: string;
  children: ReactNode;
};

export const I18nProvider = ({ translations, locale, children }: I18nProviderProps) => {
  const value = useMemo<I18nContextValue>(() => {
    const t = (key: string, params?: InterpolationParams) =>
      interpolate(resolveKey(translations, locale, key), params);
    return { t, locale };
  }, [translations, locale]);

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