import { describe, it, expect, afterEach } from 'vitest';
import { lockBodyScroll, unlockBodyScroll, _lockCount } from './scroll-lock';

describe('scroll-lock', () => {
    afterEach(() => {
        // Drain any leftover locks so tests are independent.
        while (_lockCount() > 0) unlockBodyScroll();
        document.body.style.overflow = '';
    });

    it('locks body scroll on first lock and restores on last unlock', () => {
        document.body.style.overflow = 'auto';
        lockBodyScroll();
        expect(document.body.style.overflow).toBe('hidden');
        unlockBodyScroll();
        // Restores the pre-lock value.
        expect(document.body.style.overflow).toBe('auto');
        expect(_lockCount()).toBe(0);
    });

    it('is ref-counted: stacked overlays keep the lock until all release', () => {
        lockBodyScroll();
        lockBodyScroll();
        expect(_lockCount()).toBe(2);
        unlockBodyScroll();
        // Still locked — one overlay remains open.
        expect(document.body.style.overflow).toBe('hidden');
        unlockBodyScroll();
        expect(document.body.style.overflow).toBe('');
    });

    it('ignores an unbalanced unlock', () => {
        unlockBodyScroll();
        expect(_lockCount()).toBe(0);
    });
});
