"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTargetZIndex = useTargetZIndex;
const react_1 = require("react");
const react_use_1 = require("react-use");
const get_target_z_index_1 = require("../utils/get-target-z-index.js");
const events = new Set([
    'resize',
    'scroll',
    'touchstart',
    'touchmove',
    'touchend',
    'pageshow',
    'load',
    'orientationchange',
]);
function useTargetZIndex(dataLayoutSelector, offset = 10) {
    const [zIndex, setZIndex] = (0, react_1.useState)(() => (0, get_target_z_index_1.getTargetZIndex)(dataLayoutSelector, offset));
    const zIndexRef = (0, react_use_1.useLatest)(zIndex);
    (0, react_use_1.useEffectOnce)(() => {
        let rafId = null;
        recalculate();
        for (const eventName of events) {
            window.addEventListener(eventName, scheduleRecalculate, true);
        }
        return () => {
            if (rafId !== null) {
                cancelAnimationFrame(rafId);
            }
            for (const eventName of events) {
                window.removeEventListener(eventName, scheduleRecalculate, true);
            }
        };
        function scheduleRecalculate() {
            if (rafId !== null) {
                cancelAnimationFrame(rafId);
            }
            rafId = requestAnimationFrame(recalculate);
        }
        function recalculate() {
            rafId = null;
            const newZIndex = (0, get_target_z_index_1.getTargetZIndex)(dataLayoutSelector, offset);
            if (newZIndex !== zIndexRef.current) {
                setZIndex(newZIndex);
            }
        }
    });
    return zIndex;
}
//# sourceMappingURL=useTargetZIndex.js.map
