"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updatePositionInStack = exports.baseClassName = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_dom_1 = require("react-dom");
const react_1 = require("react");
exports.baseClassName = 'ab-Modal';
const Backdrop = (props) => {
    const { uuid, timestamp } = props;
    const [backdropVisible, setBackdropVisible] = React.useState(false);
    const [zIndex, setZIndex] = (0, react_1.useState)(-1);
    (0, react_1.useLayoutEffect)(() => {
        (0, exports.updatePositionInStack)(uuid, {
            timestamp,
            baseZIndex: props.zIndex,
            setBackdropOrder: (visible, zIndex) => {
                (0, react_dom_1.unstable_batchedUpdates)(() => {
                    setBackdropVisible(visible);
                    setZIndex(zIndex);
                    if (visible && props.onBringToFront) {
                        props.onBringToFront();
                    }
                });
            },
        });
        return () => (0, exports.updatePositionInStack)(uuid, null);
    }, []);
    return backdropVisible ? (React.createElement("div", { "data-id": uuid, style: { zIndex }, className: `${exports.baseClassName}-backdrop` })) : null;
};
const stack = {};
const updatePositionInStack = (id, data) => {
    stack[id] = data;
    if (!data) {
        delete stack[id];
    }
    const pairs = Object.keys(stack).map((key) => {
        const data = stack[key];
        return {
            key,
            ...data,
        };
    });
    // sort pairs in ascending order
    pairs.sort((p1, p2) => p1.timestamp - p2.timestamp);
    const last = pairs.pop();
    pairs.forEach((data) => {
        data.setBackdropOrder(false, -1);
    });
    if (last) {
        last.setBackdropOrder(true, last.baseZIndex);
    }
};
exports.updatePositionInStack = updatePositionInStack;
exports.default = Backdrop;
