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

import enTranslation from './locales/en/translation.json';
import arTranslation from './locales/ar/translation.json';
import { getFrappeTranslations } from './services/translationService';

// Initialize i18n with static translations first (fallback)
i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources: {
      en: {
        translation: enTranslation
      },
      ar: {
        translation: arTranslation
      }
    },
    fallbackLng: 'en',
    defaultNS: 'translation',
    interpolation: {
      escapeValue: false
    },
    detection: {
      order: ['localStorage', 'navigator'],
      caches: ['localStorage']
    }
  });

// Load translations from Frappe and merge with static translations
export async function loadFrappeTranslations() {
  try {
    // Only load translations if user is logged in (to avoid 403 errors)
    const user = localStorage.getItem('user');
    if (!user) {
      // User not logged in yet, skip loading translations from Frappe
      // They will be loaded after login
      return;
    }

    // Load English translations from Frappe
    const enFrappeTranslations = await getFrappeTranslations('en');
    if (Object.keys(enFrappeTranslations).length > 0) {
      i18n.addResourceBundle('en', 'translation', enFrappeTranslations, true, true);
    }

    // Load Arabic translations from Frappe
    const arFrappeTranslations = await getFrappeTranslations('ar');
    if (Object.keys(arFrappeTranslations).length > 0) {
      i18n.addResourceBundle('ar', 'translation', arFrappeTranslations, true, true);
    }

    console.log('✓ Translations loaded from Frappe');
  } catch (error) {
    // Silently fail - will use static translations
    console.warn('⚠ Could not load translations from Frappe, using static translations:', error);
  }
}

// Auto-load translations when i18n is ready (only if user is logged in)
i18n.on('initialized', () => {
  loadFrappeTranslations();
});

export default i18n;


