import { useState, useEffect, useCallback } from 'react';
import type { SupportedLanguage } from '@avanzacast/shared-types';
import { 
  getLanguage, 
  saveLanguage, 
  translate, 
  AVAILABLE_LANGUAGES 
} from '@avanzacast/shared-utils';

interface UseLanguageReturn {
  language: SupportedLanguage;
  availableLanguages: typeof AVAILABLE_LANGUAGES;
  setLanguage: (lang: SupportedLanguage) => void;
  t: (key: string) => string;
}

/**
 * Hook compartido para manejar internacionalización en todos los módulos
 */
export function useLanguage(): UseLanguageReturn {
  const [language, setLanguageState] = useState<SupportedLanguage>(() => getLanguage());

  // Función para cambiar el idioma
  const setLanguage = useCallback((lang: SupportedLanguage) => {
    saveLanguage(lang);
    setLanguageState(lang);
    
    // Actualizar el atributo lang del HTML
    if (typeof document !== 'undefined') {
      document.documentElement.lang = lang;
    }
  }, []);

  // Cargar idioma guardado al montar
  useEffect(() => {
    const savedLang = getLanguage();
    if (savedLang !== language) {
      setLanguageState(savedLang);
    }
    
    // Configurar idioma en el HTML
    if (typeof document !== 'undefined') {
      document.documentElement.lang = savedLang;
    }
  }, []);

  // Función de traducción
  const t = useCallback((key: string) => {
    return translate(key, language);
  }, [language]);

  return {
    language,
    availableLanguages: AVAILABLE_LANGUAGES,
    setLanguage,
    t,
  };
}
