import { useCallback, useEffect, useState } from 'react';

const eventListerOptions = {
  passive: true,
};

const useVisualViewportSize = () => {
  const windowExists = typeof window !== 'undefined';
  const [windowSize, setWindowSize] = useState({
    width: windowExists ? window.visualViewport?.width || 0 : 0,
    height: windowExists ? window.visualViewport?.height || 0 : 0,
    top: windowExists ? window.visualViewport?.offsetTop || 0 : 0,
  });

  const setSize = useCallback(() => {
    if (!windowExists) return;
    setWindowSize({ width: window.visualViewport?.width || 0, height: window.visualViewport?.height || 0, top: window.visualViewport?.offsetTop || 0 });
  }, []);

  useEffect(() => {
    if (!windowExists) return;

    setSize();

    window.visualViewport?.addEventListener('resize', setSize, eventListerOptions);
    window.visualViewport?.addEventListener('scroll', setSize, eventListerOptions);

    return () => {
      window.visualViewport?.removeEventListener('resize', setSize);
      window.visualViewport?.removeEventListener('scroll', setSize);
    }
  }, [setSize]);

  return windowSize;
}

export default useVisualViewportSize;
