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 _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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 _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
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 _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _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, { forwardRef, useCallback, useMemo } from "react";
import { safeUseId } from "../../utils";
import { component } from "../../engines";
import { useFocusTrap, useForkRef } from "../../hooks";
import { IconClose } from "../_Icon";
import { popupConfig, usePopupContext } from "../Popup";
import { Overlay } from "../Overlay";
import { DEFAULT_Z_INDEX } from "../Popup/utils";
import { classes, tokens } from "./Modal.tokens";
import { useModal } from "./hooks";
import { base as viewCSS } from "./variations/_view/base";
import { getIdLastModal } from "./ModalContext";
import { CloseButton, ModalBody, ModalContent, base } from "./Modal.styles";
// issue #823
var Popup = component(popupConfig);
/**
 * Modal.
 * Управляет показом/скрытием, подложкой и анимацией визуальной части модального окна.
 */ export var modalRoot = function modalRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), id = _ref2.id, withAnimation = _ref2.withAnimation, onClose = _ref2.onClose, onOverlayClick = _ref2.onOverlayClick, onEscKeyDown = _ref2.onEscKeyDown, _ref_closeOnEsc = _ref2.closeOnEsc, closeOnEsc = _ref_closeOnEsc === void 0 ? true : _ref_closeOnEsc, _ref_closeOnOverlayClick = _ref2.closeOnOverlayClick, closeOnOverlayClick = _ref_closeOnOverlayClick === void 0 ? true : _ref_closeOnOverlayClick, withBlur = _ref2.withBlur, _ref_isFocusTrapped = _ref2.isFocusTrapped, isFocusTrapped = _ref_isFocusTrapped === void 0 ? true : _ref_isFocusTrapped, initialFocusRef = _ref2.initialFocusRef, focusAfterRef = _ref2.focusAfterRef, zIndex = _ref2.zIndex, popupInfo = _ref2.popupInfo, children = _ref2.children, view = _ref2.view, opened = _ref2.opened, isOpen = _ref2.isOpen, hasBody = _ref2.hasBody, hasClose = _ref2.hasClose, resizable = _ref2.resizable, draggable = _ref2.draggable, overlay = _ref2.overlay, rest = _object_without_properties(_ref2, [
            "id",
            "withAnimation",
            "onClose",
            "onOverlayClick",
            "onEscKeyDown",
            "closeOnEsc",
            "closeOnOverlayClick",
            "withBlur",
            "isFocusTrapped",
            "initialFocusRef",
            "focusAfterRef",
            "zIndex",
            "popupInfo",
            "children",
            "view",
            "opened",
            "isOpen",
            "hasBody",
            "hasClose",
            "resizable",
            "draggable",
            "overlay"
        ]), _rest1 = _sliced_to_array(_rest, 1), outerRootRef = _rest1[0];
        var innerIsOpen = Boolean(isOpen || opened);
        var innerHasClose = hasClose === undefined && hasBody || hasClose;
        var trapRef = useFocusTrap(isFocusTrapped, initialFocusRef, focusAfterRef, true, !isFocusTrapped);
        var popupController = usePopupContext();
        var innerRef = useForkRef(trapRef, outerRootRef);
        var uniqId = safeUseId();
        var innerId = id || uniqId;
        var overlayBackgroundToken = withBlur ? "var(".concat(tokens.modalOverlayWithBlurColor, ")") : "var(".concat(tokens.modalOverlayColor, ")");
        var modalInfo = useModal({
            id: innerId,
            isOpen: innerIsOpen,
            closeOnEsc: closeOnEsc,
            onEscKeyDown: onEscKeyDown,
            onClose: onClose,
            popupInfo: popupInfo
        }).modalInfo;
        var transparent = useMemo(function() {
            return getIdLastModal(Array.from(popupController.items.values())) !== innerId;
        }, [
            innerId,
            popupController.items
        ]);
        var onModalOverlayKeyDown = useCallback(function(event) {
            if (onOverlayClick) {
                onOverlayClick(event);
                return;
            }
            if (onClose) {
                onClose();
            }
        }, [
            closeOnOverlayClick,
            onOverlayClick,
            onClose
        ]);
        var overlayNode = /*#__PURE__*/ React.createElement(Overlay, {
            className: classes.overlay,
            zIndex: zIndex || DEFAULT_Z_INDEX,
            backgroundColorProperty: overlayBackgroundToken,
            withBlur: withBlur,
            transparent: transparent,
            isClickable: closeOnOverlayClick,
            onOverlayClick: onModalOverlayKeyDown
        });
        return /*#__PURE__*/ React.createElement(Popup, _object_spread({
            id: innerId,
            opened: innerIsOpen,
            ref: innerRef,
            popupInfo: modalInfo,
            withAnimation: withAnimation,
            zIndex: zIndex,
            overlay: /*#__PURE__*/ React.createElement(Root, {
                view: view
            }, overlay || overlayNode),
            draggable: draggable,
            resizable: resizable
        }, rest), hasBody ? /*#__PURE__*/ React.createElement(Root, {
            view: view
        }, /*#__PURE__*/ React.createElement(ModalBody, null, /*#__PURE__*/ React.createElement(ModalContent, null, innerHasClose && /*#__PURE__*/ React.createElement(CloseButton, {
            onClick: onClose,
            "data-test": "modal-close"
        }, /*#__PURE__*/ React.createElement(IconClose, {
            size: "s",
            color: "currentColor"
        })), children))) : /*#__PURE__*/ React.createElement(React.Fragment, null, children));
    });
};
export var modalConfig = {
    name: 'Modal',
    tag: 'div',
    layout: modalRoot,
    base: base,
    variations: {
        view: {
            css: viewCSS
        }
    },
    defaults: {
        view: 'default'
    }
};
