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 ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(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, { memo, useRef, useCallback, useEffect } from 'react';
import styled from 'styled-components';
import { usePopper } from 'react-popper';
import { useForkRef } from '../../hooks';
var StyledRoot = styled.div.withConfig({
    displayName: "Popup__StyledRoot",
    componentId: "sc-7a6b6e85-0"
})([
    "position:relative;box-sizing:border-box;display:inline-flex;"
]);
var StyledPopup = styled.div.withConfig({
    displayName: "Popup__StyledPopup",
    componentId: "sc-7a6b6e85-1"
})([
    "position:absolute;z-index:1;padding:var(--plasma-popup-padding);margin:var(--plasma-popup-margin);width:var(--plasma-popup-width);"
]);
export var getPlacement = function getPlacement(placement) {
    return "".concat(placement, "-start");
};
var getAutoPlacements = function getAutoPlacements(placements) {
    return (placements || []).map(function(placement) {
        return getPlacement(placement);
    });
};
/**
 * Всплывающее окно с возможностью позиционирования
 * и вызова по клику либо ховеру.
 * @deprecated Используйте Popover
 */ export var Popup = /*#__PURE__*/ memo(/*#__PURE__*/ React.forwardRef(function(_0, _1) {
    var _ref = [
        _0,
        _1
    ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), disclosure = _ref2.disclosure, children = _ref2.children, isOpen = _ref2.isOpen, opened = _ref2.opened, trigger = _ref2.trigger, _ref_placement = _ref2.placement, placement = _ref_placement === void 0 ? 'auto' : _ref_placement, onToggle = _ref2.onToggle, rest = _object_without_properties(_ref2, [
        "disclosure",
        "children",
        "isOpen",
        "opened",
        "trigger",
        "placement",
        "onToggle"
    ]), _rest1 = _sliced_to_array(_rest, 1), outerRootRef = _rest1[0];
    var innerIsOpen = Boolean(isOpen || opened);
    var rootRef = useRef(null);
    var popupRef = useRef(null);
    var handleRef = useForkRef(rootRef, outerRootRef);
    var isAutoArray = Array.isArray(placement);
    var isAuto = isAutoArray || placement === 'auto';
    var _usePopper = usePopper(rootRef.current, popupRef.current, {
        placement: getPlacement(isAutoArray ? 'auto' : placement),
        modifiers: [
            {
                name: 'flip',
                enabled: isAuto,
                options: {
                    allowedAutoPlacements: getAutoPlacements(isAutoArray ? placement : [])
                }
            }
        ]
    }), styles = _usePopper.styles, attributes = _usePopper.attributes, forceUpdate = _usePopper.forceUpdate;
    var onDocumentClick = useCallback(function(event) {
        var _rootRef_current;
        var targetIsRoot = event.target === rootRef.current;
        var rootHasTarget = (_rootRef_current = rootRef.current) === null || _rootRef_current === void 0 ? void 0 : _rootRef_current.contains(event.target);
        if (!targetIsRoot && !rootHasTarget) {
            onToggle === null || onToggle === void 0 ? void 0 : onToggle(false, event);
        }
    }, [
        onToggle
    ]);
    var onClick = useCallback(function(event) {
        if (trigger === 'click') {
            var _popupRef_current;
            var targetIsPopup = event.target === popupRef.current;
            var rootHasTarget = (_popupRef_current = popupRef.current) === null || _popupRef_current === void 0 ? void 0 : _popupRef_current.contains(event.target);
            if (!targetIsPopup && !rootHasTarget) {
                onToggle === null || onToggle === void 0 ? void 0 : onToggle(!innerIsOpen, event);
            }
        }
    }, [
        trigger,
        innerIsOpen,
        onToggle
    ]);
    var onMouseEnter = useCallback(function(event) {
        if (trigger === 'hover') {
            onToggle === null || onToggle === void 0 ? void 0 : onToggle(true, event);
        }
    }, [
        trigger,
        onToggle
    ]);
    var onMouseLeave = useCallback(function(event) {
        if (trigger === 'hover') {
            onToggle === null || onToggle === void 0 ? void 0 : onToggle(false, event);
        }
    }, [
        trigger,
        onToggle
    ]);
    var onFocus = useCallback(function(event) {
        if (trigger === 'hover') {
            onToggle === null || onToggle === void 0 ? void 0 : onToggle(true, event);
        }
    }, [
        trigger,
        onToggle
    ]);
    var onBlur = useCallback(function(event) {
        if (trigger === 'hover') {
            onToggle === null || onToggle === void 0 ? void 0 : onToggle(false, event);
        }
    }, [
        trigger,
        onToggle
    ]);
    useEffect(function() {
        document.addEventListener('click', onDocumentClick);
        return function() {
            return document.removeEventListener('click', onDocumentClick);
        };
    }, []);
    useEffect(function() {
        if (!innerIsOpen || !forceUpdate) {
            return;
        }
        /*
                 * INFO: Метод forceUpdate содержит в себе flushSync и приводит
                 * к повторному рендеру компонента, который уже находится в процессе рендера.
                 * Данный хак, нужен для того, чтобы это поведение избежать и перенаправить
                 * вызов метода в очередь микрозадач.
                 */ Promise.resolve().then(forceUpdate);
    }, [
        innerIsOpen,
        forceUpdate
    ]);
    return /*#__PURE__*/ React.createElement(StyledRoot, _object_spread({
        ref: handleRef,
        onClick: onClick,
        onMouseEnter: onMouseEnter,
        onMouseLeave: onMouseLeave,
        onFocus: onFocus,
        onBlur: onBlur
    }, rest), disclosure, children && /*#__PURE__*/ React.createElement(StyledPopup, _object_spread_props(_object_spread({}, attributes.popper), {
        ref: popupRef,
        style: _object_spread({}, styles.popper, {
            display: innerIsOpen ? 'block' : 'none'
        })
    }), children));
}));
