import _createForOfIteratorHelperLoose from "@babel/runtime/helpers/esm/createForOfIteratorHelperLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
var _class, _Popup;
import React from 'react';
import { Transition } from 'react-transition-group';
import warning from 'warning';
import { globalObject } from '@skbkontur/global-object';
import { getDOMRect } from "../../../lib/dom/getDOMRect";
import * as LayoutEvents from "../../../lib/LayoutEvents";
import { ZIndex } from "../../ZIndex";
import { RenderContainer } from "../../RenderContainer";
import { getRandomID, isFunction, isNonNullable, isNullable, isRefableElement } from "../../../lib/utils";
import { isIE11, isEdge } from "../../../lib/client";
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { isTestEnv } from "../../../lib/currentEnvironment";
import { CommonWrapper } from "../../CommonWrapper";
import { cx } from "../../../lib/theming/Emotion";
import { responsiveLayout } from "../../../components/ResponsiveLayout/decorator";
import { MobilePopup } from "../../MobilePopup";
import { getRootNode, rootNode } from "../../../lib/rootNode";
import { isInstanceWithAnchorElement } from "../../../lib/InstanceWithAnchorElement";
import { createPropsGetter } from "../../../lib/createPropsGetter";
import { isInstanceOf } from "../../../lib/isInstanceOf";
import { getFullReactUIFlagsContext, ReactUIFeatureFlagsContext } from "../../../lib/featureFlagsContext";
import { mergeRefs } from "../../../lib/mergeRefs";
import { getVisualStateDataAttributes } from "../../CommonWrapper/utils/getVisualStateDataAttributes";
import { PopupPinNew } from "../PopupPinNew";
import { PopupHelper } from "../PopupHelper";
import { styles } from "../Popup.styles";
import { PopupPin } from "../PopupPin";
var POPUP_BORDER_DEFAULT_COLOR = 'transparent';
var TRANSITION_TIMEOUT = {
  enter: 0,
  exit: 200
};
export var PopupNonPinnablePositions = ['middle center', 'middle left', 'middle right'];
export var PopupPinnablePositions = ['top center', 'top left', 'top right', 'bottom center', 'bottom left', 'bottom right', 'left middle', 'left top', 'left bottom', 'right middle', 'right top', 'right bottom'];
export var PopupPositions = [].concat(PopupPinnablePositions, PopupNonPinnablePositions);
export var DefaultPosition = PopupPositions[0];
export var DUMMY_LOCATION = {
  position: DefaultPosition,
  coordinates: {
    top: -9999,
    left: -9999
  },
  isFullyVisible: false
};
export var PopupDataTids = {
  root: 'Popup__root',
  content: 'PopupContent',
  contentInner: 'PopupContentInner',
  popupPin: 'PopupPin__root'
};
export var PopupIds = {
  root: PopupDataTids.root
};
export var Popup = responsiveLayout(_class = rootNode(_class = (_Popup = /*#__PURE__*/function (_React$Component) {
  function Popup() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.getProps = createPropsGetter(Popup.defaultProps);
    _this.state = {
      location: _this.props.opened ? DUMMY_LOCATION : null
    };
    _this.locationUpdateId = null;
    _this.refForTransition = /*#__PURE__*/React.createRef();
    _this.hasAnchorElementListeners = false;
    _this.rootId = PopupIds.root + getRandomID();
    _this.anchorElement = null;
    _this.absoluteParent = null;
    _this.renderInPortal = function (anchor, ref) {
      var location = _this.state.location;
      return /*#__PURE__*/(
        React.createElement(RenderContainer, {
          anchor: anchor,
          ref: ref
        }, _this.isMobileLayout && !_this.props.withoutMobile ? _this.renderMobile() : location && _this.renderContent(location))
      );
    };
    _this.renderWithoutPortal = function (anchor, ref) {
      var location = _this.state.location;
      return /*#__PURE__*/(
        React.createElement(EmptyWrapper, {
          ref: ref
        }, anchor, location && /*#__PURE__*/
        React.createElement("div", {
          ref: _this.updateAbsoluteElement,
          className: styles.absoluteParent()
        }, _this.renderContent(location)))
      );
    };
    _this.updateAnchorElement = function (instance) {
      var childDomNode = isInstanceWithAnchorElement(instance) ? instance.getAnchorElement() : getRootNode(instance);
      var anchorElement = _this.anchorElement;
      if (childDomNode !== anchorElement) {
        _this.removeEventListeners(anchorElement);
        _this.anchorElement = childDomNode;
        _this.addEventListeners(childDomNode);
      }
    };
    _this.updateAbsoluteElement = function (instance) {
      _this.absoluteParent = instance;
    };
    _this.handleMouseEnter = function (event) {
      if (_this.props.onMouseEnter) {
        _this.props.onMouseEnter(event);
      }
    };
    _this.handleMouseLeave = function (event) {
      if (_this.props.onMouseLeave) {
        _this.props.onMouseLeave(event);
      }
    };
    _this.handleClick = function (event) {
      if (_this.props.onClick) {
        _this.props.onClick(event);
      }
    };
    _this.handleFocus = function (event) {
      if (_this.props.onFocus) {
        _this.props.onFocus(event);
      }
    };
    _this.handleBlur = function (event) {
      if (_this.props.onBlur) {
        _this.props.onBlur(event);
      }
    };
    _this.calculateWidth = function (width) {
      if (typeof width === 'string' && width.includes('%')) {
        var anchorWidth = getDOMRect(_this.anchorElement).width;
        return width.replace(/(\d)+%/g, function (percent) {
          return anchorWidth * parseFloat(percent) / 100 + "px";
        });
      }
      return width;
    };
    _this.content = function (children) {
      var backgroundColor = _this.props.backgroundColor;
      var _this$getProps = _this.getProps(),
        width = _this$getProps.width,
        minWidth = _this$getProps.minWidth;
      return /*#__PURE__*/(
        React.createElement("div", {
          className: styles.content(_this.theme),
          "data-tid": PopupDataTids.content,
          ref: mergeRefs(_this.refForTransition, _this.refPopupContentElement)
        }, /*#__PURE__*/

        React.createElement("div", {
          className: styles.contentInner(_this.theme),
          style: {
            backgroundColor: backgroundColor,
            width: _this.calculateWidth(width),
            minWidth: _this.calculateWidth(minWidth)
          },
          "data-tid": PopupDataTids.contentInner
        }, children))
      );
    };
    _this.prepareDataVisualState = function () {
      var _this$state$location;
      var position = (_this$state$location = _this.state.location) == null ? void 0 : _this$state$location.position;
      if (position) {
        var _getVisualStateDataAt;
        var attrName = "position-" + position.replace(' ', '-');
        return getVisualStateDataAttributes((_getVisualStateDataAt = {}, _getVisualStateDataAt[attrName] = true, _getVisualStateDataAt));
      }
      return {};
    };
    _this.resetLocation = function () {
      _this.cancelDelayedUpdateLocation();
      _this.state.location !== null && _this.setState({
        location: null
      });
    };
    _this.refPopupContentElement = function (element) {
      _this.lastPopupContentElement = element;
    };
    _this.handleLayoutEvent = function () {
      if (!_this.state.location) {
        return;
      }
      _this.updateLocation();
    };
    _this.updateLocation = function () {
      var popupContentElement = _this.lastPopupContentElement;
      if (!popupContentElement) {
        return;
      }
      var location = _this.getLocation(popupContentElement, _this.state.location);
      if (location) {
        _this.props.onPositionChange == null || _this.props.onPositionChange(location.position, location.isFullyVisible);
      }
      if (!_this.locationEquals(_this.state.location, location)) {
        _this.setState({
          location: location
        });
      }
    };
    _this.getRelativeShift = function () {
      var _this2 = _this,
        absoluteParent = _this2.absoluteParent;
      if (!_this.props.disablePortal || !absoluteParent) {
        return {
          top: 0,
          left: 0
        };
      }
      var rect = PopupHelper.getElementAbsoluteRect(absoluteParent);
      return {
        top: -rect.top,
        left: -rect.left
      };
    };
    return _this;
  }
  _inheritsLoose(Popup, _React$Component);
  var _proto = Popup.prototype;
  _proto.componentDidMount = function componentDidMount() {
    this.updateLocation();
    this.layoutEventsToken = LayoutEvents.addListener(this.handleLayoutEvent);
    if (!this.hasAnchorElementListeners) {
      this.addEventListeners(this.anchorElement);
    }
  };
  Popup.getDerivedStateFromProps = function getDerivedStateFromProps(props, state) {
    /**
    * Delaying updateLocation to ensure it happens after props update
    */
    if (props.opened) {
      if (!state.location) {
        return {
          location: DUMMY_LOCATION
        };
      }
    } else if (state.location) {
      return {
        location: DUMMY_LOCATION
      };
    }
    return state;
  };
  _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
    var hadNoLocation = prevState.location === DUMMY_LOCATION;
    var hasLocation = this.state.location !== DUMMY_LOCATION;
    var wasClosed = prevProps.opened && !this.props.opened;
    if (this.isMobileLayout && prevState.location === null && this.state.location === null) {
      this.setState({
        location: DUMMY_LOCATION
      });
    }
    if (this.props.opened && hadNoLocation && hasLocation && this.props.onOpen) {
      this.props.onOpen();
    }
    if (wasClosed && !hasLocation && this.props.onClose) {
      this.props.onClose();
    }
    if (this.props.opened) {
      this.delayUpdateLocation();
    }
  };
  _proto.componentWillUnmount = function componentWillUnmount() {
    this.cancelDelayedUpdateLocation();
    if (this.hasAnchorElementListeners) {
      this.removeEventListeners(this.anchorElement);
    }
    if (this.layoutEventsToken) {
      this.layoutEventsToken.remove();
      this.layoutEventsToken = null;
    }
    if (this.state.location && this.props.onClose) {
      this.props.onClose();
    }
  };
  _proto.render = function render() {
    var _this3 = this;
    return /*#__PURE__*/React.createElement(ReactUIFeatureFlagsContext.Consumer, null, function (flags) {
      _this3.featureFlags = getFullReactUIFlagsContext(flags);
      return /*#__PURE__*/React.createElement(ThemeContext.Consumer, null, function (theme) {
        _this3.theme = theme;
        return _this3.renderMain();
      });
    });
  };
  _proto.renderMobile = function renderMobile() {
    var opened = this.props.opened;
    var children = this.renderChildren();
    return children ? /*#__PURE__*/React.createElement(CommonWrapper, {
      rootNodeRef: this.setRootNode
    }, /*#__PURE__*/React.createElement(MobilePopup, {
      opened: opened,
      withoutRenderContainer: true,
      onCloseRequest: this.props.mobileOnCloseRequest
    }, this.content(children))) : null;
  };
  _proto.renderMain = function renderMain() {
    var _anchor;
    var anchorElement = this.props.anchorElement;
    var useWrapper = this.getProps().useWrapper;
    var anchor = null;
    if (isInstanceOf(anchorElement, globalObject.Element)) {
      this.updateAnchorElement(anchorElement);
    } else if ( /*#__PURE__*/React.isValidElement(anchorElement)) {
      anchor = useWrapper ? /*#__PURE__*/React.createElement("span", null, anchorElement) : anchorElement;
    } else {
      anchor = /*#__PURE__*/React.createElement("span", null, anchorElement);
    }
    var anchorWithRef = anchor && /*#__PURE__*/React.isValidElement(anchor) && isRefableElement(anchor) ? /*#__PURE__*/React.cloneElement(anchor, {
      ref: mergeRefs((_anchor = anchor) == null ? void 0 : _anchor.ref, this.updateAnchorElement)
    }) : null; // we need to get anchor's DOM node
    // so we either set our own ref on it via cloning
    // or relay on findDOMNode (inside getRootNode)
    // which should be called within updateAnchorElement
    // in the case when the anchor is not refable
    var canGetAnchorNode = !!anchorWithRef || isInstanceOf(anchorElement, globalObject.Element);
    var renderRef = canGetAnchorNode ? null : this.updateAnchorElement;
    var renderAnchor = anchorWithRef || anchor;
    return this.props.disablePortal ? this.renderWithoutPortal(renderAnchor, renderRef) : this.renderInPortal(renderAnchor, renderRef);
  };
  _proto.addEventListeners = function addEventListeners(element) {
    if (element && isInstanceOf(element, globalObject.Element)) {
      // @ts-expect-error: Type ElementEventMap is missing events: https://github.com/skbkontur/retail-ui/pull/2946#discussion_r931072657
      element.addEventListener('mouseenter', this.handleMouseEnter); // @ts-expect-error: See the comment above
      element.addEventListener('mouseleave', this.handleMouseLeave); // @ts-expect-error: See the comment above
      element.addEventListener('click', this.handleClick);
      element.addEventListener('focusin', this.handleFocus);
      element.addEventListener('focusout', this.handleBlur);
      this.hasAnchorElementListeners = true;
    }
  };
  _proto.removeEventListeners = function removeEventListeners(element) {
    if (element && isInstanceOf(element, globalObject.Element)) {
      // @ts-expect-error: Type ElementEventMap is missing events: https://github.com/skbkontur/retail-ui/pull/2946#discussion_r931072657
      element.removeEventListener('mouseenter', this.handleMouseEnter); // @ts-expect-error: See the comment above
      element.removeEventListener('mouseleave', this.handleMouseLeave); // @ts-expect-error: See the comment above
      element.removeEventListener('click', this.handleClick);
      element.removeEventListener('focusin', this.handleFocus);
      element.removeEventListener('focusout', this.handleBlur);
      this.hasAnchorElementListeners = false;
    }
  };
  _proto.renderContent = function renderContent(location) {
    var _this4 = this;
    var _this$props = this.props,
      maxWidth = _this$props.maxWidth,
      opened = _this$props.opened;
    var _this$getProps2 = this.getProps(),
      hasShadow = _this$getProps2.hasShadow,
      disableAnimations = _this$getProps2.disableAnimations,
      ignoreHover = _this$getProps2.ignoreHover;
    var children = this.renderChildren();
    var relativeShift = this.getRelativeShift();
    var _PopupHelper$getPosit = PopupHelper.getPositionObject(location.position),
      direction = _PopupHelper$getPosit.direction;
    var rootStyle = {
      maxWidth: maxWidth,
      top: location.coordinates.top + relativeShift.top,
      left: location.coordinates.left + relativeShift.left
    };
    return /*#__PURE__*/React.createElement(Transition, {
      timeout: TRANSITION_TIMEOUT,
      appear: !disableAnimations,
      "in": Boolean(opened && children),
      mountOnEnter: true,
      unmountOnExit: true,
      enter: !disableAnimations,
      exit: !disableAnimations,
      onExited: this.resetLocation,
      nodeRef: this.refForTransition
    }, function (state) {
      var _this4$props$id, _extends2, _ref;
      return /*#__PURE__*/React.createElement(CommonWrapper, _extends({}, _this4.props, {
        rootNodeRef: _this4.setRootNode
      }, _this4.prepareDataVisualState()), /*#__PURE__*/React.createElement(ZIndex, {
        id: (_this4$props$id = _this4.props.id) != null ? _this4$props$id : _this4.rootId,
        "data-tid": PopupDataTids.root,
        priority: _this4.props.priority,
        className: cx(_extends((_extends2 = {}, _extends2[styles.popup(_this4.theme)] = true, _extends2[styles.shadow(_this4.theme)] = hasShadow, _extends2[styles.popupIgnoreHover()] = ignoreHover, _extends2), disableAnimations ? {} : (_ref = {}, _ref[styles["transition-enter-" + direction](_this4.theme)] = true, _ref[styles.transitionEnter()] = state === 'entering', _ref[styles.transitionEnterActive()] = state === 'entered', _ref[styles.transitionExit()] = state === 'exiting', _ref))),
        style: rootStyle,
        onMouseEnter: _this4.handleMouseEnter,
        onMouseLeave: _this4.handleMouseLeave
      }, _this4.content(children), (!_this4.isMobileLayout || _this4.props.withoutMobile) && _this4.renderPin(location.position)));
    });
  };
  _proto.renderChildren = function renderChildren() {
    return isFunction(this.props.children) ? this.props.children() : this.props.children;
  };
  _proto.renderPin = function renderPin(positionName) {
    var isDefaultBorderColor = this.theme.popupBorderColor === POPUP_BORDER_DEFAULT_COLOR;
    var pinBorder = isIE11 && isDefaultBorderColor ? 'rgba(0, 0, 0, 0.09)' : this.theme.popupBorderColor;
    var _this$props2 = this.props,
      pinSize = _this$props2.pinSize,
      backgroundColor = _this$props2.backgroundColor,
      borderColor = _this$props2.borderColor;
    var _this$getProps3 = this.getProps(),
      hasShadow = _this$getProps3.hasShadow,
      hasPin = _this$getProps3.hasPin;
    var position = PopupHelper.getPositionObject(positionName);
    return hasPin && !PopupNonPinnablePositions.includes(positionName) && (this.featureFlags.popupFixPinTearing ? /*#__PURE__*/React.createElement(PopupPinNew, {
      popupElement: this.lastPopupContentElement,
      popupPosition: positionName,
      size: pinSize || parseInt(this.theme.popupPinSize),
      offset: this.getPinOffset(position.align),
      backgroundColor: backgroundColor || this.theme.popupBackground
    }) : /*#__PURE__*/React.createElement(PopupPin, {
      popupElement: this.lastPopupContentElement,
      popupPosition: positionName,
      size: pinSize || parseInt(this.theme.popupPinSize),
      offset: this.getPinOffset(position.align),
      borderWidth: hasShadow ? 1 : 0,
      backgroundColor: backgroundColor || this.theme.popupBackground,
      borderColor: borderColor || pinBorder
    }));
  };
  _proto.delayUpdateLocation = function delayUpdateLocation() {
    this.cancelDelayedUpdateLocation();
    this.locationUpdateId = globalObject.requestAnimationFrame == null ? void 0 : globalObject.requestAnimationFrame(this.updateLocation);
  };
  _proto.cancelDelayedUpdateLocation = function cancelDelayedUpdateLocation() {
    if (this.locationUpdateId) {
      globalObject.cancelAnimationFrame == null || globalObject.cancelAnimationFrame(this.locationUpdateId);
      this.locationUpdateId = null;
    }
  };
  _proto.locationEquals = function locationEquals(x, y) {
    if (x === y) {
      return true;
    }
    if (isNullable(x) || isNullable(y)) {
      return false;
    }
    if (!isIE11 && !isEdge) {
      return x.coordinates.left === y.coordinates.left && x.coordinates.top === y.coordinates.top && x.position === y.position;
    } // Для ie/edge обновляем позицию только при разнице минимум в 1. Иначе есть вероятность
    // уйти в бесконечный ререндер
    return x.position === y.position && Math.abs(x.coordinates.top - y.coordinates.top) <= 1 && Math.abs(x.coordinates.left - y.coordinates.left) <= 1;
  };
  _proto.reorderPropsPositionsWithPriorityPos = function reorderPropsPositionsWithPriorityPos() {
    var positions = this.props.positions ? this.props.positions : PopupPinnablePositions;
    var pos_ = '';
    if (this.props.pos) {
      pos_ = this.props.pos;
    } else {
      pos_ = positions[0];
    }
    var index = positions.findIndex(function (position) {
      return position.startsWith(pos_);
    });
    if (index === -1) {
      warning(false, 'Unexpected position ' + pos_ + ' passed to Popup. Expected one of: ' + positions.join(', '));
      return positions;
    }
    return [].concat(positions.slice(index), positions.slice(0, index));
  };
  _proto.getLocation = function getLocation(popupElement, location) {
    var _this$getProps4 = this.getProps(),
      tryPreserveFirstRenderedPosition = _this$getProps4.tryPreserveFirstRenderedPosition;
    var positions = this.reorderPropsPositionsWithPriorityPos();
    var anchorElement = this.anchorElement;
    warning(anchorElement && isInstanceOf(anchorElement, globalObject.Element), 'Anchor element is not defined or not instance of Element');
    if (!(anchorElement && isInstanceOf(anchorElement, globalObject.Element))) {
      return location;
    }
    var anchorRect = PopupHelper.getElementAbsoluteRect(anchorElement);
    var popupRect = PopupHelper.getElementAbsoluteRect(popupElement);
    var position;
    var coordinates;
    if (location && location !== DUMMY_LOCATION && location.position) {
      position = location.position;
      coordinates = this.getCoordinates(anchorRect, popupRect, position);
      var isFullyVisible = PopupHelper.isFullyVisible(coordinates, popupRect);
      var canBecomeVisible = !isFullyVisible && PopupHelper.canBecomeFullyVisible(position, coordinates);
      if (
      // если нужно сохранить первоначальную позицию и Попап целиком
      // находится в пределах вьюпорта (или может быть проскроллен в него)
      tryPreserveFirstRenderedPosition && (isFullyVisible || canBecomeVisible) ||
      // если Попап целиком во вьюпорте и в самой приоритетной позиции
      // (иначе нужно попытаться позицию сменить)
      isFullyVisible && position === positions[0]) {
        // сохраняем текущую позицию
        return {
          coordinates: coordinates,
          position: position,
          isFullyVisible: true
        };
      }
    }
    for (var _iterator = _createForOfIteratorHelperLoose(positions), _step; !(_step = _iterator()).done;) {
      position = _step.value;
      coordinates = this.getCoordinates(anchorRect, popupRect, position);
      if (PopupHelper.isFullyVisible(coordinates, popupRect)) {
        return {
          coordinates: coordinates,
          position: position,
          isFullyVisible: true
        };
      }
    }
    position = positions[0];
    coordinates = this.getCoordinates(anchorRect, popupRect, position);
    return {
      coordinates: coordinates,
      position: position,
      isFullyVisible: false
    };
  };
  _proto.getPinnedPopupOffset = function getPinnedPopupOffset(anchorRect, position) {
    if (!this.getProps().hasPin || /center|middle/.test(position.align)) {
      return 0;
    }
    var anchorSize = /top|bottom/.test(position.direction) ? anchorRect.width : anchorRect.height;
    var pinSize = this.props.pinSize;
    return Math.max(0, this.getPinOffset(position.align) + (pinSize || parseInt(this.theme.popupPinSize)) - anchorSize / 2);
  };
  _proto.getCoordinates = function getCoordinates(anchorRect, popupRect, positionName) {
    var marginFromProps = this.props.margin;
    var margin = isNonNullable(marginFromProps) && !isNaN(marginFromProps) ? marginFromProps : parseInt(this.theme.popupMargin) || 0;
    var position = PopupHelper.getPositionObject(positionName);
    var popupOffset = this.getProps().popupOffset + this.getPinnedPopupOffset(anchorRect, position);
    switch (position.direction) {
      case 'top':
        return {
          top: anchorRect.top - popupRect.height - margin,
          left: this.getHorizontalPosition(anchorRect, popupRect, position.align, popupOffset)
        };
      case 'middle':
        return {
          top: anchorRect.top + anchorRect.height / 2 - popupRect.height / 2,
          left: this.getHorizontalPosition(anchorRect, popupRect, position.align, popupOffset)
        };
      case 'bottom':
        return {
          top: anchorRect.top + anchorRect.height + margin,
          left: this.getHorizontalPosition(anchorRect, popupRect, position.align, popupOffset)
        };
      case 'left':
        return {
          top: this.getVerticalPosition(anchorRect, popupRect, position.align, popupOffset),
          left: anchorRect.left - popupRect.width - margin
        };
      case 'right':
        return {
          top: this.getVerticalPosition(anchorRect, popupRect, position.align, popupOffset),
          left: anchorRect.left + anchorRect.width + margin
        };
      default:
        throw new Error("Unexpected direction '" + position.direction + "'");
    }
  };
  _proto.getPinOffset = function getPinOffset(align) {
    var pinOffset = this.props.pinOffset;
    switch (align) {
      case 'top':
      case 'bottom':
        return pinOffset || parseInt(this.theme.popupPinOffsetY);
      case 'left':
      case 'right':
        return pinOffset || parseInt(this.theme.popupPinOffsetX);
      case 'center':
      case 'middle':
        return 0;
      default:
        throw new Error("Unexpected align '" + align + "'");
    }
  };
  _proto.getHorizontalPosition = function getHorizontalPosition(anchorRect, popupRect, align, popupOffset) {
    switch (align) {
      case 'left':
        return anchorRect.left - popupOffset;
      case 'center':
        return anchorRect.left - (popupRect.width - anchorRect.width) / 2;
      case 'right':
        return anchorRect.left - (popupRect.width - anchorRect.width) + popupOffset;
      default:
        throw new Error("Unexpected align '" + align + "'");
    }
  };
  _proto.getVerticalPosition = function getVerticalPosition(anchorRect, popupRect, align, popupOffset) {
    switch (align) {
      case 'top':
        return anchorRect.top - popupOffset;
      case 'middle':
        return anchorRect.top - (popupRect.height - anchorRect.height) / 2;
      case 'bottom':
        return anchorRect.top - (popupRect.height - anchorRect.height) + popupOffset;
      default:
        throw new Error("Unexpected align '" + align + "'");
    }
  };
  return Popup;
}(React.Component), _Popup.__KONTUR_REACT_UI__ = 'Popup', _Popup.displayName = 'Popup', _Popup.defaultProps = {
  popupOffset: 0,
  hasPin: false,
  hasShadow: false,
  disableAnimations: isTestEnv,
  useWrapper: false,
  ignoreHover: false,
  disablePortal: false,
  width: 'auto',
  priority: ZIndex.priorities.Popup
}, _Popup.defaultRootNode = null, _Popup)) || _class) || _class;

// Нужно, чтобы получать по рефу dom-элемент, в который зарендерится anchor
var EmptyWrapper = /*#__PURE__*/function (_React$Component2) {
  function EmptyWrapper() {
    return _React$Component2.apply(this, arguments) || this;
  }
  _inheritsLoose(EmptyWrapper, _React$Component2);
  var _proto2 = EmptyWrapper.prototype;
  _proto2.render = function render() {
    return this.props.children;
  };
  return EmptyWrapper;
}(React.Component);