import * as React from 'react';
import { createPortal } from 'react-dom';
import { useMemo } from 'react';
import join from '../utils/join';
import { RemoveScroll } from 'react-remove-scroll';
import { Flex } from 'rebass';
import { baseClassName, default as Backdrop } from './Backdrop';
import { createUuid } from '../utils/uuid';
import { isBrowserDocumentAvailable } from '../../View/UIHelper';
let portalElement;
let loadingScreenPortalElement;
export const ensurePortalElement = () => {
    if (!isBrowserDocumentAvailable()) {
        return null;
    }
    if (portalElement) {
        return portalElement;
    }
    portalElement = document.createElement('div');
    document.body.appendChild(portalElement);
    return portalElement;
};
export const ensureLoadingScreenPortalElement = () => {
    if (!isBrowserDocumentAvailable()) {
        return null;
    }
    if (loadingScreenPortalElement) {
        return loadingScreenPortalElement;
    }
    loadingScreenPortalElement = document.createElement('div');
    document.body.appendChild(loadingScreenPortalElement);
    return loadingScreenPortalElement;
};
let globalCounter = 0;
export const Modal = (props) => {
    ensurePortalElement();
    const { className, style, children, isOpen, onBringToFront, ...boxProps } = props;
    const uuid = useMemo(() => createUuid(), []);
    const counter = useMemo(() => globalCounter++, [isOpen]);
    const openTimestamp = counter;
    const backdropZIndexOffset = props.backdropZIndexOffset || 1;
    const zIndex = (props.baseZIndex || 2000) + counter;
    return createPortal(isOpen ? (React.createElement(React.Fragment, null,
        React.createElement(Backdrop, { timestamp: openTimestamp, uuid: uuid, zIndex: zIndex - backdropZIndexOffset, onBringToFront: onBringToFront }),
        React.createElement(RemoveScroll, null,
            React.createElement(Flex, { alignItems: "center", justifyContent: "center", flexDirection: "column", ...boxProps, style: { zIndex, ...style }, className: join(baseClassName, className) }, children)))) : null, portalElement);
};
