function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import React, { createContext, useState, useContext, useRef } from "react";
import { canUseDOM, safeUseId } from "../../utils";
import { Portal } from "../Portal";
import { hasModals } from "../Modal/ModalContext";
import { ClientOnlyPortal } from "./ClientOnlyPortal";
import { StyledPortal } from "./Popup.styles";
export var POPUP_PORTAL_ID = 'plasma-popup-root';
var initialItems = new Map();
var PopupContext = /*#__PURE__*/ createContext({
    items: initialItems,
    rootId: POPUP_PORTAL_ID,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    register: function register(_info) {
        throw new Error('Function not implemented. Add PopupProvider');
    },
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    unregister: function unregister(_id) {
        throw new Error('Function not implemented. Add PopupProvider');
    }
});
export var usePopupContext = function usePopupContext() {
    return useContext(PopupContext);
};
// TODO: #1599
export var PopupProvider = function PopupProvider(param) {
    var children = param.children, providerFrame = param.providerFrame, UNSAFE_SSR_ENABLED = param.UNSAFE_SSR_ENABLED;
    var prevBodyOverflowY = useRef(canUseDOM ? document.body.style.overflowY : '');
    var _useState = _sliced_to_array(useState(initialItems), 2), items = _useState[0], setItems = _useState[1];
    var uuid = safeUseId();
    var rootId = "".concat(POPUP_PORTAL_ID, "-").concat(uuid);
    var register = function register(info) {
        if (!canUseDOM) {
            return;
        }
        setItems(function(prevItems) {
            var _info_info;
            var newItems = new Map(prevItems);
            if (((_info_info = info.info) === null || _info_info === void 0 ? void 0 : _info_info.isModal) && !hasModals(Array.from(prevItems.values()))) {
                prevBodyOverflowY.current = document.body.style.overflowY;
                document.body.style.overflowY = 'hidden';
            }
            newItems.set(info.id, info);
            return newItems;
        });
    };
    var unregister = function unregister(id) {
        if (!canUseDOM) {
            return;
        }
        setItems(function(prevItems) {
            if (!prevItems.has(id)) {
                return prevItems;
            }
            var newItems = new Map(prevItems);
            var prevHasModals = hasModals(Array.from(newItems.values()));
            newItems.delete(id);
            if (prevHasModals && !hasModals(Array.from(newItems.values()))) {
                document.body.style.overflowY = prevBodyOverflowY.current;
            }
            return newItems;
        });
    };
    var context = {
        items: items,
        rootId: rootId,
        register: register,
        unregister: unregister
    };
    var getDefaultPortal = function getDefaultPortal() {
        if (typeof providerFrame !== 'string' && providerFrame && providerFrame.current && canUseDOM) {
            return /*#__PURE__*/ React.createElement(Portal, {
                container: providerFrame.current
            }, /*#__PURE__*/ React.createElement(StyledPortal, {
                id: rootId
            }));
        }
        var withFrameId = typeof providerFrame === 'string' && providerFrame !== 'document';
        var containerElement = withFrameId && canUseDOM && document.getElementById(providerFrame);
        if (containerElement) {
            return /*#__PURE__*/ React.createElement(Portal, {
                container: containerElement
            }, /*#__PURE__*/ React.createElement(StyledPortal, {
                id: rootId
            }));
        }
        return /*#__PURE__*/ React.createElement(Portal, {
            container: document.body
        }, /*#__PURE__*/ React.createElement(StyledPortal, {
            id: rootId
        }));
    };
    return /*#__PURE__*/ React.createElement(PopupContext.Provider, {
        value: context
    }, children, UNSAFE_SSR_ENABLED ? /*#__PURE__*/ React.createElement(ClientOnlyPortal, null, /*#__PURE__*/ React.createElement(StyledPortal, {
        id: rootId
    })) : getDefaultPortal());
};
