import { useLayoutEffect } from 'react';
import { useTranslation } from 'react-i18next';

/**
 * This component listens to i18next language changes and applies
 * side effects to the document. It renders no visible UI.
 */
export const LanguageManager = () => {
  const { i18n, t } = useTranslation();

  useLayoutEffect(() => {
    const handleLanguageChange = (lng: string) => {
      document.documentElement.setAttribute('dir', i18n.dir(lng));
      document.documentElement.setAttribute('lang', lng);
      document.title = t('app.title', { lng });
    };

    // Set initial values on component mount
    handleLanguageChange(i18n.language);

    // Listen for future language changes
    i18n.on('languageChanged', handleLanguageChange);

    // Cleanup the event listener on unmount
    return () => {
      i18n.off('languageChanged', handleLanguageChange);
    };
  }, [i18n, t]);

  return null;
};
