import { defineTrait } from '../define.js';

let lockCount = 0;
let savedOverflow = '';

export const scrollLock = defineTrait({
  name: 'scroll-lock',
  category: 'layout-measurement',
  description: 'Disables background scrolling',
  attributes: ['data-scroll-lock-active'],
  events: [],
  config: [],
  setup({ host }) {
    if (lockCount === 0) {
      savedOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
    }
    lockCount++;
    host.setAttribute('data-scroll-lock-active', '');

    return () => {
      lockCount--;
      if (lockCount === 0) {
        document.body.style.overflow = savedOverflow;
      }
      host.removeAttribute('data-scroll-lock-active');
    };
  },
});
