import _defineProperty from "@babel/runtime/helpers/defineProperty";
import React, { PureComponent } from 'react';
import { PlainOutsideClickTargetRefContext } from './PlainOutsideClickTargetRefContext';
export default function withOuterListeners(Component) {
  return class WithOutsideClick extends PureComponent {
    constructor(...args) {
      super(...args);
      _defineProperty(this, "outsideClickTargetRef", /*#__PURE__*/React.createRef());
      _defineProperty(this, "handleClick", evt => {
        var _this$outsideClickTar;
        const domNode = (_this$outsideClickTar = this.outsideClickTargetRef.current) === null || _this$outsideClickTar === void 0 ? void 0 : _this$outsideClickTar.deref();
        if (!domNode || evt.target instanceof Node && !domNode.contains(evt.target)) {
          var _this$props$handleCli, _this$props;
          (_this$props$handleCli = (_this$props = this.props).handleClickOutside) === null || _this$props$handleCli === void 0 ? void 0 : _this$props$handleCli.call(_this$props, evt);
        }
      });
      _defineProperty(this, "handleKeydown", evt => {
        if (evt.code === 'Escape' && this.props.handleEscapeKeydown) {
          this.props.handleEscapeKeydown(evt);
        }
      });
      _defineProperty(this, "setOutsideClickTargetRef", el => {
        this.outsideClickTargetRef.current = el && new WeakRef(el);
      });
    }
    componentDidMount() {
      if (this.props.handleClickOutside) {
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        document.addEventListener('click', this.handleClick, false);
      }
      if (this.props.handleEscapeKeydown) {
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        document.addEventListener('keydown', this.handleKeydown, false);
      }
    }
    componentWillUnmount() {
      if (this.props.handleClickOutside) {
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        document.removeEventListener('click', this.handleClick, false);
      }
      if (this.props.handleEscapeKeydown) {
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        document.removeEventListener('keydown', this.handleKeydown, false);
      }
    }
    render() {
      return /*#__PURE__*/React.createElement(PlainOutsideClickTargetRefContext.Provider, {
        value: this.setOutsideClickTargetRef
      }, /*#__PURE__*/React.createElement(Component
      // Ignored via go/ees005
      // eslint-disable-next-line react/jsx-props-no-spreading
      , this.props));
    }
  };
}
// eslint-disable-next-line @atlaskit/editor/no-re-export
export { PlainOutsideClickTargetRefContext } from './PlainOutsideClickTargetRefContext';