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

import en from './locales/en.json';
import hu from './locales/hu.json';
import de from './locales/de.json';

// Detect browser language on first visit
const storedLanguage = localStorage.getItem('i18nextLng');
if (!storedLanguage) {
  const browserLang = navigator.language.split('-')[0]; // Get 'hu' from 'hu-HU'
  const supportedLanguages = ['en', 'hu', 'de'];
  if (supportedLanguages.includes(browserLang)) {
    localStorage.setItem('i18nextLng', browserLang);
  }
}

i18n
  .use(LanguageDetector) // Detects user language
  .use(initReactI18next) // Passes i18n down to react-i18next
  .init({
    resources: {
      en: { translation: en },
      hu: { translation: hu },
      de: { translation: de }
    },
    fallbackLng: 'en', // Use English if detected language is not available
    debug: false,

    interpolation: {
      escapeValue: false // React already protects from XSS
    },

    detection: {
      order: ['querystring', 'localStorage', 'navigator', 'htmlTag'],
      caches: ['localStorage'],
      lookupLocalStorage: 'i18nextLng',
      lookupQuerystring: 'lng'
    }
  });

export default i18n;
