"use client";

import { createInstance, i18n } from "i18next";
import React, { useMemo } from "react";
import { I18nextProvider } from "react-i18next";

interface Props {
  children: React.ReactNode;
  language: string;
  resources: { [ns: string]: any };
  namespaces: string[];
}

export const I18nContext = React.createContext(null);

const I18nProvider: React.FC<Props> = ({
  children,
  language,
  resources,
  namespaces,
}) => {
  const i18n = useMemo<i18n>(() => {
    const instance = createInstance();
    instance.init({
      resources: {
        [language]: resources,
      },
      lng: language,
      fallbackLng: language,
      defaultNS: namespaces[0],
      fallbackNS: namespaces,
      interpolation: {
        escapeValue: false,
      },
      ns: namespaces,
    });
    return instance as i18n;
  }, [language, resources, namespaces]);

  return <I18nextProvider i18n={i18n}>{children}</I18nextProvider>;
};

export default I18nProvider;
