import { EffectCallback, useEffect } from 'react';

export const useScrollLock = (lock: boolean) => {
  useEffect((): ReturnType<EffectCallback> => {
    const isLockAlready = document.body.style.position === 'fixed';
    if (lock && !isLockAlready) {
      const { scrollY } = window;
      Object.assign(document.body.style, {
        position: 'fixed',
        top: `-${scrollY}px`,
        left: 0,
        right: 0,
      });

      return () => {
        Object.assign(document.body.style, {
          position: '',
          top: '',
          left: '',
          right: '',
        });
        window.scrollTo(0, scrollY);
      };
    }
  }, [lock]);
};
