import { useCallback, useLayoutEffect, useRef } from 'react';
import { getScrollbarWidth, testElForOverflow } from '../utils';
import useConfiguration from './useConfiguration';
const useScrollToggle = (selector = ':root') => {
    const scrollbarWidthRef = useRef(0);
    const styleRef = useRef(null);
    const { styleSheetTarget } = useConfiguration();
    const enableScroll = useCallback(() => {
        // No need to short circuit if called repetitively, will just perform a simple null set on the ref.
        styleRef.current?.remove();
        styleRef.current = null;
    }, []);
    const disableScroll = useCallback(() => {
        // If we have a ref to the style el we can assume styles to disable overflow are in the DOM. No need for a DOM query.
        if (styleRef.current)
            return;
        const scrollEl = document.querySelector(selector);
        if (!scrollEl)
            return;
        const [overflowX, overflowY] = testElForOverflow(scrollEl);
        if (!overflowX && !overflowY)
            return;
        styleRef.current = document.createElement('style');
        styleRef.current.nonce = window.__webpack_nonce__;
        // TODO: Read current padding and add scrollbar width.
        styleRef.current.textContent = `
      ${selector} {
        ${overflowY ? `padding-inline-end: ${scrollbarWidthRef.current}px !important` : ''};
        ${overflowX ? `padding-block-end: ${scrollbarWidthRef.current}px !important` : ''};
        overflow: hidden !important;
      }
    `;
        (styleSheetTarget ?? document.head).append(styleRef.current);
    }, [selector]);
    useLayoutEffect(() => {
        scrollbarWidthRef.current = getScrollbarWidth();
        // To be safe, clean up when the calling component unmounts just in case it did not do so.
        return enableScroll;
        // As enableScroll is memoized with no deps, the cleanup **should** only run once on unmount. If that changes, adjust here accordingly.
    }, [enableScroll]);
    return { enableScroll, disableScroll };
};
export default useScrollToggle;
//# sourceMappingURL=useScrollToggle.js.map