// src/i18n/index.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

// Only load German synchronously (default language)
import translationDE from './locales/de';

// Lazy load other languages when needed
const loadLanguage = async (lng: string) => {
    if (lng === 'en' && !i18n.hasResourceBundle('en', 'translation')) {
        const { default: translationEN } = await import('./locales/en');
        i18n.addResourceBundle('en', 'translation', translationEN, true, true);
    } else if (lng === 'sr' && !i18n.hasResourceBundle('sr', 'translation')) {
        const { default: translationSR } = await import('./locales/sr');
        i18n.addResourceBundle('sr', 'translation', translationSR, true, true);
    }
};

i18n
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        resources: {
            de: {
                translation: translationDE
            }
        },
        fallbackLng: 'de',
        supportedLngs: ['de', 'en', 'sr'],
        interpolation: {
            escapeValue: false
        }
    });

// Load language bundle when language changes
i18n.on('languageChanged', loadLanguage);

// Load initial language if not German
if (i18n.language && i18n.language !== 'de') {
    loadLanguage(i18n.language);
}

export default i18n;