import { useLayoutEffect, useState } from 'react';

export type ViewerViewport = { w: number; h: number };

function readViewport(): ViewerViewport {
  const vv = window.visualViewport;
  return {
    w: Math.round(vv?.width ?? window.innerWidth),
    h: Math.round(vv?.height ?? window.innerHeight),
  };
}

/** Tracks layout size; updates on resize, orientation, fullscreen, and visualViewport changes. */
export function useViewerViewport(): ViewerViewport {
  const [viewport, setViewport] = useState<ViewerViewport>(() =>
    typeof window !== 'undefined' ? readViewport() : { w: 1200, h: 800 },
  );

  useLayoutEffect(() => {
    const update = () => setViewport(readViewport());
    update();
    window.addEventListener('resize', update);
    window.addEventListener('orientationchange', update);
    document.addEventListener('fullscreenchange', update);
    window.visualViewport?.addEventListener('resize', update);
    window.visualViewport?.addEventListener('scroll', update);
    return () => {
      window.removeEventListener('resize', update);
      window.removeEventListener('orientationchange', update);
      document.removeEventListener('fullscreenchange', update);
      window.visualViewport?.removeEventListener('resize', update);
      window.visualViewport?.removeEventListener('scroll', update);
    };
  }, []);

  return viewport;
}
