// Global lock counter so nested modals don't prematurely restore scroll
let lockCount = 0;
let originalOverflow = "";

export interface ScrollLock {
  lock: () => void;
  unlock: () => void;
}

/**
 * Prevents body scroll. Uses a reference count so nested overlays
 * (e.g. a dialog inside a drawer) don't prematurely restore scrolling.
 */
export function createScrollLock(): ScrollLock {
  let locked = false;

  return {
    lock() {
      if (locked) return;
      locked = true;
      if (lockCount === 0) {
        originalOverflow = document.body.style.overflow;
        document.body.style.overflow = "hidden";
      }
      lockCount++;
    },
    unlock() {
      if (!locked) return;
      locked = false;
      lockCount = Math.max(0, lockCount - 1);
      if (lockCount === 0) {
        document.body.style.overflow = originalOverflow;
        originalOverflow = "";
      }
    },
  };
}
