// Ref-counted body scroll lock shared by overlay components (Modal, Sheet).
// A counter keeps the lock held while any overlay is open, so closing one of
// two stacked overlays doesn't prematurely restore background scrolling.

let count = 0;
let previousOverflow = '';

/** Lock body scroll (idempotent per caller — pair every call with `unlock`). */
export function lockBodyScroll(): void {
    if (typeof document === 'undefined') return;
    if (count === 0) {
        previousOverflow = document.body.style.overflow;
        document.body.style.overflow = 'hidden';
    }
    count += 1;
}

/** Release one lock; body scroll is restored once the last one is released. */
export function unlockBodyScroll(): void {
    if (typeof document === 'undefined') return;
    if (count === 0) return;
    count -= 1;
    if (count === 0) {
        document.body.style.overflow = previousOverflow;
    }
}

/** Test-only: current lock depth. */
export function _lockCount(): number {
    return count;
}
