import type { Language } from '@/types/language';
import { changeLanguage } from 'i18next';
import { useLayoutEffect, type JSX, type PropsWithChildren } from 'react';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { LangaugeContext } from '@/contexts/LangaugeContext';

export const LanguageProvider = (props: PropsWithChildren): JSX.Element => {
  const [currentLanguage, setCurrentLangauge] = useLocalStorage<Language>(
    'language',
    'fa',
  );

  useLayoutEffect(() => {
    changeLanguage(currentLanguage);
    document.documentElement.dir = currentLanguage === 'fa' ? 'rtl' : 'ltr';
    document.documentElement.lang = currentLanguage;
  }, [currentLanguage]);

  return (
    <LangaugeContext.Provider
      value={{
        language: currentLanguage,
        changeLanguage: setCurrentLangauge,
      }}
    >
      {props.children}
    </LangaugeContext.Provider>
  );
};
