import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    supportedLngs: ['en', 'ru'],
    debug: false,
    interpolation: {
      escapeValue: false,
    },
    detection: {
      order: ['localStorage', 'navigator'],
      caches: ['localStorage'],
      lookupLocalStorage: 'i18nextLng',
    },
    resources: {},
  });

async function loadTranslations(lng: string): Promise<void> {
  try {
    const response = await fetch(`/locales/${lng}/translation.json`);
    const translations = await response.json();
    i18n.addResourceBundle(lng, 'translation', translations, true, true);
  } catch {
    // Silently fall back to bundled resources
  }
}

async function initTranslations(): Promise<void> {
  await Promise.all([loadTranslations('en'), loadTranslations('ru')]);
}

export { initTranslations };
export default i18n;
