import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useUIStore } from '../stores/ui.store';
import { type SupportedLanguage } from '../locales';

/**
 * Hook for managing language switching with proper synchronization
 * between i18n and UI store
 */
export function useLanguageSwitcher() {
  const { i18n } = useTranslation();
  const { language: uiLanguage, setLanguage: setUILanguage } = useUIStore();
  const [isChanging, setIsChanging] = useState(false);

  const changeLanguage = useCallback(async (newLanguage: SupportedLanguage) => {
    try {
      setIsChanging(true);
      // Only change i18n language - let the i18n event handler update UI store
      await i18n.changeLanguage(newLanguage);
      setIsChanging(false);
    } catch (error) {
      console.error('Failed to change language:', error);
      setIsChanging(false);
    }
  }, [i18n]);

  return {
    currentLanguage: i18n.language as SupportedLanguage,
    changeLanguage,
    isChanging,
  };
}