import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import HttpBackend from "i18next-http-backend";
import { I18n } from "@/types/global";


export function setupI18n(i18nProps: I18n) {
    const { locale, available, fallback, assetsBase, assetsVersion, defaultNS, namespaces } = i18nProps;

    if (i18n.isInitialized) {
        if (locale && i18n.language !== locale) i18n.changeLanguage(locale);
        return i18n;
    }

    const v = assetsVersion ? `?v=${assetsVersion}` : "";

    i18n
        .use(HttpBackend)
        .use(initReactI18next)
        .init({
            lng: locale,
            fallbackLng: fallback,
            supportedLngs: available,
            ns: namespaces,
            defaultNS,
            load: "languageOnly",
            interpolation: { escapeValue: false },
            backend: { loadPath: `${assetsBase}/{{lng}}/{{ns}}.json${v}` },
            react: { useSuspense: true },
            parseMissingKeyHandler: (key) => `[MISSING:${key}]`,
        });

    return i18n;
}
