import { useState, useEffect, useMemo } from 'react';
import type { Language, Translation } from '../types/i18n';
import { translations, defaultLanguage } from '../data/translations';

export const useTranslation = () => {
  const [currentLanguage, setCurrentLanguage] = useState<Language>(() => {
    // Récupérer la langue depuis localStorage ou utiliser la langue par défaut
    const saved = localStorage.getItem('language') as Language;
    return saved && translations[saved] ? saved : defaultLanguage;
  });

  // Memoize the translation object to prevent unnecessary re-renders
  const t = useMemo<Translation>(() => translations[currentLanguage], [currentLanguage]);

  // Memoize available languages array
  const availableLanguages = useMemo(() => Object.keys(translations) as Language[], []);

  useEffect(() => {
    localStorage.setItem('language', currentLanguage);
  }, [currentLanguage]);

  const changeLanguage = (language: Language) => {
    if (translations[language]) {
      setCurrentLanguage(language);
    }
  };

  return {
    t,
    currentLanguage,
    changeLanguage,
    availableLanguages
  };
};
