import { useEffect } from 'react';
import { I18nextProvider, useTranslation } from 'react-i18next';
import i18n from '@/i18n';
import { analytics } from '@/components/analytics/analytics-service';

function I18nInit({ children }: { children: React.ReactNode }) {
  const { i18n: i18nInstance } = useTranslation();

  useEffect(() => {
    // Track language changes
    const handleLanguageChanged = (lng: string) => {
      analytics.trackFeatureUsage('language_change', { language: lng });
      // Update document lang attribute for accessibility
      document.documentElement.lang = lng;
    };

    i18nInstance.on('languageChanged', handleLanguageChanged);
    
    // Set initial lang
    document.documentElement.lang = i18nInstance.language;

    return () => {
      i18nInstance.off('languageChanged', handleLanguageChanged);
    };
  }, [i18nInstance]);

  return <>{children}</>;
}

export function I18nProvider({ children }: { children: React.ReactNode }) {
  return (
    <I18nextProvider i18n={i18n}>
      <I18nInit>{children}</I18nInit>
    </I18nextProvider>
  );
}
