import { useEffect } from "react";
import { useTranslation as useI18NextTranslation } from "react-i18next";
import { PACKAGE_NAME } from "../index.ts";
import enResources from "./en.json" with { type: "json" };
import esResources from "./es.json" with { type: "json" };

const addMissingBundles = (i18n: any) => {
  const needsEn = !i18n.hasResourceBundle("en", PACKAGE_NAME);
  const needsEs = !i18n.hasResourceBundle("es", PACKAGE_NAME);

  if (needsEn) {
    i18n.addResourceBundle("en", PACKAGE_NAME, enResources, true, true);
  }

  if (needsEs) {
    i18n.addResourceBundle("es", PACKAGE_NAME, esResources, true, true);
  }
};

export const useTranslation = () => {
  const { i18n } = useI18NextTranslation();

  useEffect(() => {
    addMissingBundles(i18n);
  }, [i18n]);

  return useI18NextTranslation(PACKAGE_NAME);
};
