import { useEffect, useRef, 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 rafRef = useRef<number | null>(null);

  useEffect(() => {
    if (typeof window === 'undefined') return;

    const setSize = () => {
      setWindowSize((prev) => {
        const next = {
          width: window.visualViewport?.width || 0,
          height: window.visualViewport?.height || 0,
          top: window.visualViewport?.offsetTop || 0,
        };
        if (
          prev.width === next.width &&
          prev.height === next.height &&
          prev.top === next.top
        ) {
          return prev;
        }
        return next;
      });
    };

    const scheduleSetSize = () => {
      if (rafRef.current !== null) return;
      rafRef.current = window.requestAnimationFrame(() => {
        rafRef.current = null;
        setSize();
      });
    };

    setSize();

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

    return () => {
      window.visualViewport?.removeEventListener('resize', scheduleSetSize);
      if (rafRef.current !== null) {
        window.cancelAnimationFrame(rafRef.current);
        rafRef.current = null;
      }
    };
  }, []);

  return windowSize;
}

export default useVisualViewportSize;
