import { useEffect } from "react";

// Ref-counted lock of the <html> scroll. MUI's Dialog only locks <body>, but
// GlobalStyles.tsx sets `html { overflow-x: hidden }`, which (per the CSS spec)
// forces html's overflow-y to `auto` — making <html> the vertical scroll
// container.
// So body-locking alone leaves the page scrollable behind the modal. We lock
// <html> directly and pad for the removed scrollbar to avoid a layout shift.
let lockCount = 0;
let prevOverflow = "";
let prevPaddingRight = "";

export default function useDialogScrollLock(open: boolean) {
  useEffect(() => {
    if (!open) return;
    const el = document.documentElement;
    if (lockCount === 0) {
      const scrollbarWidth = window.innerWidth - el.clientWidth;
      prevOverflow = el.style.overflow;
      prevPaddingRight = el.style.paddingRight;
      el.style.overflow = "hidden";
      if (scrollbarWidth > 0) el.style.paddingRight = `${scrollbarWidth}px`;
    }
    lockCount += 1;
    return () => {
      lockCount -= 1;
      if (lockCount === 0) {
        el.style.overflow = prevOverflow;
        el.style.paddingRight = prevPaddingRight;
      }
    };
  }, [open]);
}
