import * as React from 'react';
import { createPortal } from 'react-dom';
import { useMemo } from 'react';
import { RemoveScroll } from 'react-remove-scroll';
import { baseClassName, default as Backdrop } from './Backdrop';
import { createUuid } from '../utils/uuid';
import { isBrowserDocumentAvailable } from '../../View/UIHelper';
import { useStacking } from '../WindowModal/useStacking';
import { Flex } from '../Flex';
import clsx from 'clsx';
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 = 1;
    const stacking = useStacking();
    const zIndex = stacking.zIndex;
    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: clsx('twa:fixed twa:inset-0 twa:z-1000 twa:font-(family-name:--ab__font-family)', baseClassName, className) }, children)))) : null, portalElement);
};
