import { initReactI18next } from 'react-i18next';

import i18n from 'i18next';
import i18NextBrowserLanguagedetector from 'i18next-browser-languagedetector';
import i18NextHttpBackend from 'i18next-http-backend';
import '@humanddev/material-hu/vite/hu-translations/clientSocketHandler';

const skipFromHuTranslations: string[] = [];

const isProd = import.meta.env.PROD;
const version = import.meta.env.VITE_TRANSLATIONS_VERSION || Date.now();

const huTranslationsPath = isProd
  ? '/assets/translations/locale'
  : '/node_modules/@humanddev/hu-translations/locale';

const supportedLanguages = [
  'es',
  'en',
  'pt',
  'pt-br',
  'it',
  'fr',
  'bg',
  'no',
  'is',
  'pl',
  'sv',
  'th',
  'uk',
  'ru',
  'ro',
  'da',
  'fi',
  'de',
  'nl',
  'id',
];

i18n
  .use(initReactI18next)
  .use(i18NextBrowserLanguagedetector)
  .use(i18NextHttpBackend)
  .init({
    partialBundledLanguages: true,
    supportedLngs: supportedLanguages,
    fallbackNS: 'general',
    fallbackLng: {
      'pt-br': ['pt'],
      default: ['en'],
    },
    defaultNS: 'general',
    ns: ['general'],
    lowerCaseLng: true,
    detection: {
      order: ['localStorage', 'navigator'],
      lookupLocalStorage: 'i18nextLng',
      caches: ['localStorage'],
    },
    interpolation: {
      escapeValue: false,
    },
    react: {
      useSuspense: true,
    },
    resources: {},
    backend: {
      loadPath: `${huTranslationsPath}/{{lng}}/{{ns}}.json`,
      request: (
        options: any,
        url: string,
        payload: any,
        callback: (error: any, data: any) => void,
      ) => {
        const filePath = url.split('locale/')[1];
        const namespace = filePath.replace('.json', '').split('/')[1];

        const mainUrl = `${huTranslationsPath}/${filePath}?c=${version}`;

        const getData = async () => {
          try {
            let data: Record<string, any> = {};

            if (!skipFromHuTranslations.includes(namespace)) {
              const adjustedMainUrl = mainUrl.replace('/pt-br/', '/pt_BR/');
              const mainData = await fetch(adjustedMainUrl)
                .then(res => res.json())
                .catch(error => {
                  console.error('Error loading translation file:', mainUrl);
                  throw error;
                });

              data = {
                ...data,
                ...mainData,
              };
            }

            callback(null, { status: 200, data });
          } catch (error) {
            callback(error, null);
          }
        };

        getData();
      },
    },
  });
