// frontend/src/i18n/index.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import ICU from 'i18next-icu';
import { resources, defaultLanguage, supportedLanguages } from '../locales';

// Get saved language from localStorage or default
const getSavedLanguage = () => {
  try {
    const stored = localStorage.getItem('ui-storage');
    if (stored) {
      const { state } = JSON.parse(stored);
      if (state?.language && supportedLanguages.includes(state.language)) {
        console.log(`🔍 Found stored language: ${state.language}`);
        return state.language;
      }
    }
  } catch (error) {
    console.warn('Failed to parse stored language:', error);
  }
  console.log(`📌 Using default language: ${defaultLanguage}`);
  return defaultLanguage;
};

const initialLanguage = getSavedLanguage();

i18n
  .use(ICU)
  .use(initReactI18next)
  .init({
    resources,
    lng: initialLanguage,
    fallbackLng: defaultLanguage,

    interpolation: {
      escapeValue: false, // React already does escaping
    },

    // Enable debug in development
    debug: process.env.NODE_ENV === 'development',

    // Default namespace
    defaultNS: 'common',

    // Fallback namespace
    fallbackNS: 'common',

    // Key separator for nested keys
    keySeparator: '.',

    // Namespace separator
    nsSeparator: ':',

    // React options
    react: {
      useSuspense: false,
      bindI18n: 'languageChanged loaded',
      bindI18nStore: 'added removed',
    },

    // Return key with namespace if translation is missing
    saveMissing: process.env.NODE_ENV === 'development',
  })
  .then(() => {
    console.log(`🚀 i18n initialized with language: ${initialLanguage}`);
  });

// Listen for language changes and update UI store
i18n.on('languageChanged', (lng) => {
  if (typeof window !== 'undefined') {
    // Update document direction for RTL languages
    document.dir = i18n.dir(lng);

    // Update UI store to keep it in sync (without triggering i18n again)
    import('../stores/ui.store').then(({ useUIStore }) => {
      const currentLanguage = useUIStore.getState().language;
      if (currentLanguage !== lng) {
        // Set directly to avoid recursive calls
        useUIStore.setState({ language: lng as any });
      }
    });
  }
});

export default i18n;