"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,
      },
      fallbackLng: language,
      interpolation: {
        escapeValue: false,
      },
      ns: namespaces,
    });
    return instance as i18n;
    // No need to check dependencies since this
    // should only be created once from the server
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

export default I18nProvider;
