var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React from 'react';
import isEqual from 'lodash.isequal';
import warning from 'warning';
import { isBrowser } from '../../lib/globalObject.js';
import { callChildRef } from '../../lib/callChildRef/callChildRef.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { isInstanceOf } from '../../lib/isInstanceOf.js';
import { LoaderDataTids } from '../../components/Loader/index.js';
import { PORTAL_INLET_ATTR, PORTAL_OUTLET_ATTR } from '../RenderContainer/index.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { incrementZIndex, removeZIndex, upperBorder, componentPriorities } from './ZIndexStorage.js';
var DEFAULT_ZINDEX_CONTEXT = { parentLayerZIndex: 0, maxZIndex: Infinity };
var ZIndexContext = React.createContext(DEFAULT_ZINDEX_CONTEXT);
ZIndexContext.displayName = 'ZIndexContext';
var ZIndex = /** @class */ (function (_super) {
    __extends(ZIndex, _super);
    function ZIndex() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            zIndex: 0,
            DOMZIndexContext: null,
        };
        _this.getProps = createPropsGetter(ZIndex_1.defaultProps);
        _this.zIndexContext = null;
        _this.wrapperRef = function (element) {
            var wrapperRef = _this.props.wrapperRef;
            _this.setRootNode(element);
            wrapperRef && callChildRef(wrapperRef, element);
            element && _this.tryGetContextByDOM(element);
        };
        _this.increment = function () {
            var _a = _this.getProps(), priority = _a.priority, delta = _a.delta;
            return incrementZIndex(priority, delta, _this.globalObject);
        };
        _this.findClosestWithZIndex = function (el) { return el === null || el === void 0 ? void 0 : el.closest('[style*=z-index]'); };
        _this.tryGetContextByDOM = function (element) {
            var _a, _b, _c;
            if (_this.props.applyZIndex &&
                isEqual(DEFAULT_ZINDEX_CONTEXT, _this.zIndexContext) &&
                _this.state.DOMZIndexContext === null) {
                var DOMZIndexContext = DEFAULT_ZINDEX_CONTEXT;
                var portal = (_a = element.parentElement) === null || _a === void 0 ? void 0 : _a.closest("[".concat(PORTAL_OUTLET_ATTR, "]"));
                if (isInstanceOf(portal, _this.globalObject.HTMLElement)) {
                    var portalID = portal.getAttribute(PORTAL_OUTLET_ATTR);
                    var noscript = (_b = _this.globalObject.document) === null || _b === void 0 ? void 0 : _b.querySelector("noscript[".concat(PORTAL_INLET_ATTR, "=\"").concat(portalID, "\"]"));
                    var parent_1 = _this.findClosestWithZIndex(noscript === null || noscript === void 0 ? void 0 : noscript.parentElement);
                    while (isInstanceOf(parent_1, _this.globalObject.HTMLElement)) {
                        var styleZIndex = parent_1.style.zIndex;
                        if (styleZIndex) {
                            var newZIndex = Number(parent_1.style.zIndex);
                            if (!Number.isNaN(newZIndex)) {
                                var maxZIndex = Infinity;
                                if (((_c = parent_1.parentElement) === null || _c === void 0 ? void 0 : _c.dataset.tid) === LoaderDataTids.veil) {
                                    maxZIndex = _this.calcZIndex(newZIndex, maxZIndex);
                                }
                                DOMZIndexContext = { maxZIndex: maxZIndex, parentLayerZIndex: newZIndex };
                                break;
                            }
                        }
                        parent_1 = _this.findClosestWithZIndex(parent_1.parentElement);
                    }
                }
                _this.setState({ DOMZIndexContext: DOMZIndexContext });
            }
        };
        return _this;
    }
    ZIndex_1 = ZIndex;
    ZIndex.prototype.validateProps = function (delta) {
        warning((delta || ZIndex_1.defaultProps.delta) > 0, "[ZIndex]: Prop 'delta' must be greater than 0, received ".concat(delta));
        warning(Math.trunc(delta || ZIndex_1.defaultProps.delta) === delta, "[ZIndex]: Prop 'delta' must be integer, received ".concat(delta));
    };
    ZIndex.prototype.componentDidMount = function () {
        this.state.zIndex = this.increment();
    };
    ZIndex.prototype.componentDidUpdate = function (prevProps) {
        var props = this.getProps();
        this.validateProps(props.delta);
        if (prevProps.priority !== props.priority || prevProps.delta !== props.delta) {
            removeZIndex(this.state.zIndex, this.globalObject);
            this.setState({ zIndex: this.increment() });
        }
    };
    ZIndex.prototype.componentWillUnmount = function () {
        removeZIndex(this.state.zIndex, this.globalObject);
    };
    ZIndex.prototype.render = function () {
        var _this = this;
        var _a = this.getProps(), style = _a.style, children = _a.children, delta = _a.delta, priority = _a.priority, applyZIndex = _a.applyZIndex, coverChildren = _a.coverChildren, createStackingContext = _a.createStackingContext, wrapperRef = _a.wrapperRef, useWrapper = _a.useWrapper, rest = __rest(_a, ["style", "children", "delta", "priority", "applyZIndex", "coverChildren", "createStackingContext", "wrapperRef", "useWrapper"]);
        var wrapperStyle = {};
        return (React.createElement(ZIndexContext.Consumer, null, function (context) {
            _this.zIndexContext = context;
            var currentZIndexContext = _this.state.DOMZIndexContext && isEqual(context, DEFAULT_ZINDEX_CONTEXT)
                ? _this.state.DOMZIndexContext
                : context;
            var parentLayerZIndex = currentZIndexContext.parentLayerZIndex, maxZIndex = currentZIndexContext.maxZIndex;
            var newZIndexContext = currentZIndexContext;
            var newZIndex = 0;
            if (applyZIndex) {
                newZIndex = _this.calcZIndex(parentLayerZIndex, maxZIndex);
                wrapperStyle.zIndex = newZIndex;
                newZIndexContext = coverChildren
                    ? { parentLayerZIndex: parentLayerZIndex, maxZIndex: newZIndex }
                    : { parentLayerZIndex: newZIndex, maxZIndex: Number.isFinite(maxZIndex) ? newZIndex : Infinity };
                if (createStackingContext) {
                    isBrowser(_this.globalObject) && 'isolation' in _this.globalObject.document.body.style
                        ? (wrapperStyle.isolation = 'isolate')
                        : (wrapperStyle.transform = 'rotate(0)');
                }
            }
            var child = !useWrapper ? (children) : (React.createElement("div", __assign({ style: __assign(__assign({}, style), wrapperStyle), ref: _this.wrapperRef }, rest), children));
            return React.createElement(ZIndexContext.Provider, { value: newZIndexContext }, child);
        }));
    };
    ZIndex.prototype.calcZIndex = function (parentLayerZIndex, maxZIndex) {
        var newZIndex = this.state.zIndex;
        if (Number.isFinite(maxZIndex)) {
            var allowedValuesIntervalLength = maxZIndex - parentLayerZIndex;
            var scale = upperBorder / allowedValuesIntervalLength;
            newZIndex = Math.ceil(newZIndex / scale);
        }
        newZIndex += parentLayerZIndex;
        return newZIndex;
    };
    var ZIndex_1;
    ZIndex.priorities = componentPriorities;
    ZIndex.__KONTUR_REACT_UI__ = 'ZIndex';
    ZIndex.displayName = 'ZIndex';
    ZIndex.defaultProps = {
        delta: 10,
        priority: 0,
        style: {},
        applyZIndex: true,
        coverChildren: false,
        createStackingContext: false,
        useWrapper: true,
    };
    ZIndex = ZIndex_1 = __decorate([
        withRenderEnvironment,
        rootNode
    ], ZIndex);
    return ZIndex;
}(React.Component));
export { ZIndex };
//# sourceMappingURL=ZIndex.js.map