import * as React from 'react';
import { useEffect, useRef, useState } from 'react';
import { ShopUtils } from '@assets/js-shop/ShopUtils';

interface ICartFocusOpenedStyleProps {
   open: boolean;
   toggleMobileAdded: (c: boolean) => void;
   toggleCart: (c: boolean) => void;
}

// Add focus-opened class to body when cart or mobileAdded is opened. And close them if screen size is changed
export default function CartOpenedFocusClass(props: ICartFocusOpenedStyleProps) {

   const wasMobile = useRef(ShopUtils.isScreenPhoneSizeWidth());

   useEffect(() => {
      window.addEventListener('resize', onWindowResize);
      return () => {
         window.removeEventListener('resize', onWindowResize);
      };
   }, []);

   useEffect(() => {
      try {
         const isCookiebarAlreadyOpened: HTMLDivElement = document.body.querySelector('.focus-cookiebara.active');
         if (!isCookiebarAlreadyOpened) {
            $('body').toggleClass('focus-opened modal-opened', props.open);
         }
      } catch (err) {
      }
   }, [props.open]);

   // close cart and mobileAdded after changing screen size from phone to full and via versa
   const onWindowResize = () => {
      const isMobile = ShopUtils.isScreenPhoneSizeWidth();
      if (isMobile !== wasMobile.current) {
         props.toggleCart(false);
         props.toggleMobileAdded(false);
      }
      wasMobile.current = isMobile;
   };

   return <></>;
}
