import { useState, useEffect, useCallback } from 'react';
import { translations, type Language, type TranslationKey, getStoredLanguage, storeLanguage } from '@/lib/i18n';

export function useI18n() {
  const [lang, setLangState] = useState<Language>(getStoredLanguage);

  const setLang = useCallback((newLang: Language) => {
    setLangState(newLang);
    storeLanguage(newLang);
    document.documentElement.lang = newLang;
    document.documentElement.dir = newLang === 'ar' ? 'rtl' : 'ltr';
  }, []);

  useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
  }, [lang]);

  const t = useCallback((key: TranslationKey): string => {
    return translations[lang][key] || translations.en[key] || key;
  }, [lang]);

  return { lang, setLang, t, isRtl: lang === 'ar' };
}
