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

export const useTranslation = () => {
  // Initialize on server with default language to avoid using localStorage during SSR
  const [currentLanguage, setCurrentLanguage] = useState<Language>(defaultLanguage);

  // On client, read saved language from localStorage
  useEffect(() => {
    try {
      const saved = (typeof window !== 'undefined' && localStorage.getItem('language')) as Language | null;
      if (saved && translations[saved]) {
        setCurrentLanguage(saved);
      }
    } catch (e) {
      // ignore (e.g., localStorage not available)
    }
  }, []);

  // Persist language changes on client
  useEffect(() => {
    try {
      if (typeof window !== 'undefined') {
        localStorage.setItem('language', currentLanguage);
      }
    } catch (e) {
      // ignore
    }
  }, [currentLanguage]);

  // 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[], []);

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

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