  import { useEffect } from 'react';
  import { initReactI18next, useTranslation } from 'react-i18next';
  import i18n from 'i18next';
  import translationEN from '../translate/en.json';
  import translationAR from '../translate/ar.json';
  import translationDE from '../translate/de.json';


  let language = localStorage.getItem('language') ?? 'en';

  i18n.use(initReactI18next).init({
      resources: {
        en: {
          translation: translationEN
        },
        ar: {
          translation: translationAR
        },
        de: {
          translation: translationDE
        }
      },
      lng: language ?? "en", 
      interpolation: {
        escapeValue: false
      }
    });

  //   console.log(navigator.language,"navigator.language");

  export function useLanguage() {
    useEffect(() => {
      // Define a function to handle language change events
      const handleLanguageChange = () => {
        const newLanguage = localStorage.getItem('language') ?? 'en';
        changeLanguage(newLanguage);
      };
  
      // Add an event listener to detect changes in localStorage
      window.addEventListener('storage', handleLanguageChange);
  
      // Clean up by removing the event listener when the component unmounts
      return () => {
        window.removeEventListener('storage', handleLanguageChange);
      };
    }, []);
  
    const changeLanguage = (newLanguage:any) => {
      i18n.changeLanguage(newLanguage);
      localStorage.setItem('language', newLanguage);
      applyLanguageStyles(newLanguage);
      // Refresh the page to apply the language changes
      window.location.reload();
    };
  
    return { changeLanguage };
  }
  
  function applyLanguageStyles(language:any) {
    if (language === 'ar') {
      document.body.setAttribute('dir', 'rtl');
      document.body.classList.remove('de');
      document.body.classList.add('ar');
    } else if (language === 'en') {
      document.body.setAttribute('dir', 'ltr');
      document.body.classList.remove('ar', 'de');
      document.body.classList.add('en');
    } else if (language === 'de') {
      document.body.setAttribute('dir', 'ltr');
      document.body.classList.remove('ar');
      document.body.classList.add('de');
    }
  }

  export function useLanguageMenu() {
    const { t } = useTranslation();

    const languageOptions = [
      { code: 'ar', icon: '/Layout/Ar.svg', label: t('Arabic') },
      { code: 'en', icon: '/Layout/En.svg', label: t('English') },
      { code: 'de', icon: '/Layout/De.svg', label: t('German') }
    ];

    return { languageOptions };
  }
