"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Modal = exports.ensureLoadingScreenPortalElement = exports.ensurePortalElement = 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");
const join_1 = tslib_1.__importDefault(require("../utils/join"));
const react_remove_scroll_1 = require("react-remove-scroll");
const rebass_1 = require("rebass");
const Backdrop_1 = tslib_1.__importStar(require("./Backdrop"));
const uuid_1 = require("../utils/uuid");
const UIHelper_1 = require("../../View/UIHelper");
const useStacking_1 = require("../WindowModal/useStacking");
let portalElement;
let loadingScreenPortalElement;
const ensurePortalElement = () => {
    if (!(0, UIHelper_1.isBrowserDocumentAvailable)()) {
        return null;
    }
    if (portalElement) {
        return portalElement;
    }
    portalElement = document.createElement('div');
    document.body.appendChild(portalElement);
    return portalElement;
};
exports.ensurePortalElement = ensurePortalElement;
const ensureLoadingScreenPortalElement = () => {
    if (!(0, UIHelper_1.isBrowserDocumentAvailable)()) {
        return null;
    }
    if (loadingScreenPortalElement) {
        return loadingScreenPortalElement;
    }
    loadingScreenPortalElement = document.createElement('div');
    document.body.appendChild(loadingScreenPortalElement);
    return loadingScreenPortalElement;
};
exports.ensureLoadingScreenPortalElement = ensureLoadingScreenPortalElement;
let globalCounter = 0;
const Modal = (props) => {
    (0, exports.ensurePortalElement)();
    const { className, style, children, isOpen, onBringToFront, ...boxProps } = props;
    const uuid = (0, react_1.useMemo)(() => (0, uuid_1.createUuid)(), []);
    const counter = (0, react_1.useMemo)(() => globalCounter++, [isOpen]);
    const openTimestamp = counter;
    const backdropZIndexOffset = 1;
    const stacking = (0, useStacking_1.useStacking)();
    const zIndex = stacking.zIndex;
    return (0, react_dom_1.createPortal)(isOpen ? (React.createElement(React.Fragment, null,
        React.createElement(Backdrop_1.default, { timestamp: openTimestamp, uuid: uuid, zIndex: zIndex - backdropZIndexOffset, onBringToFront: onBringToFront }),
        React.createElement(react_remove_scroll_1.RemoveScroll, null,
            React.createElement(rebass_1.Flex, { alignItems: "center", justifyContent: "center", flexDirection: "column", ...boxProps, style: { zIndex, ...style }, className: (0, join_1.default)(Backdrop_1.baseClassName, className) }, children)))) : null, portalElement);
};
exports.Modal = Modal;
