var _excluded = ["children", "className"];

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

import React, { forwardRef, useContext, useEffect, useImperativeHandle, useRef, useState } from 'react';
import cls from 'clsx';
import { createPopper, offsetModifier } from '@vant/popperjs';
import { extend, pick } from '../utils';
import { BORDER_BOTTOM } from '../utils/constant';
import useClickAway from '../hooks/use-click-away';
import Popup from '../popup';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
var popupProps = ['overlay', 'duration', 'overlayStyle', 'overlayClass', 'closeOnClickOverlay', 'teleport', 'onClose', 'onOpen', 'onClosed', 'onOpened', 'onClickOverlay'];
var Popover = /*#__PURE__*/forwardRef(function (_ref, ref) {
  var children = _ref.children,
      className = _ref.className,
      props = _objectWithoutPropertiesLoose(_ref, _excluded);

  var _useContext = useContext(ConfigProviderContext),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('popover', prefixCls),
      bem = _createNamespace[0];

  var _useState = useState(false),
      visible = _useState[0],
      updateShow = _useState[1];

  var popper = useRef(null);
  var wrapperRef = useRef();
  var popoverRef = useRef();

  var createPopperInstance = function createPopperInstance() {
    return createPopper(wrapperRef.current, popoverRef.current.popupRef.current, {
      placement: props.placement,
      modifiers: [{
        name: 'computeStyles',
        options: {
          adaptive: false,
          gpuAcceleration: false
        }
      }, extend({}, offsetModifier, {
        options: {
          offset: props.offset
        }
      })]
    });
  };

  var updateLocation = function updateLocation() {
    if (!visible) {
      return;
    }

    if (!popper.current) {
      popper.current = createPopperInstance();
    } else {
      var _popper$current;

      (_popper$current = popper.current) == null ? void 0 : _popper$current.setOptions({
        placement: props.placement
      });
    }
  };

  var onClickWrapper = function onClickWrapper() {
    if (props.trigger === 'click') {
      updateShow(!visible);
    }
  };

  var onClickAction = function onClickAction(action, index) {
    if (action.disabled) {
      return;
    }

    props.onSelect == null ? void 0 : props.onSelect(action, index);

    if (props.closeOnClickAction) {
      updateShow(false);
    }
  };

  var onClickAway = function onClickAway() {
    if (props.closeOnClickOutside && (!props.overlay || props.closeOnClickOverlay)) {
      updateShow(false);
    }
  };

  var renderAction = function renderAction(action, index) {
    var icon = action.icon,
        text = action.text,
        color = action.color,
        disabled = action.disabled,
        actionClassname = action.className;
    return /*#__PURE__*/React.createElement("div", {
      // role="menuitem"
      key: index,
      className: cls(bem('action', {
        disabled: disabled,
        'with-icon': icon
      }), actionClassname),
      style: {
        color: color
      },
      onClick: function onClick() {
        return onClickAction(action, index);
      }
    }, icon ? /*#__PURE__*/React.cloneElement(icon, {
      className: cls(bem('action-icon'))
    }) : null, /*#__PURE__*/React.createElement("div", {
      className: cls(bem('action-text'), BORDER_BOTTOM)
    }, text));
  };

  useEffect(function () {
    return function () {
      if (popper.current) {
        var _popper$current2;

        (_popper$current2 = popper.current) == null ? void 0 : _popper$current2.destroy();
        popper.current = null;
      }
    };
  }, []);
  useEffect(function () {
    updateLocation();
  }, [visible, props.placement]);
  useEffect(function () {
    var popupTarget;

    var prevent = function prevent(e) {
      return e.stopPropagation();
    };

    if (popoverRef.current && popoverRef.current.popupRef.current) {
      popupTarget = popoverRef.current.popupRef.current;
      popupTarget.addEventListener('touchstart', prevent);
    }

    return function () {
      if (popupTarget) popupTarget.removeEventListener('touchstart', prevent);
    };
  }, [popoverRef.current]);
  useImperativeHandle(ref, function () {
    return {
      show: function show() {
        if (visible) {
          updateShow(false);
          setTimeout(function () {
            return updateShow(true);
          }, 0);
          return;
        }

        updateShow(true);
      },
      hide: function hide() {
        return updateShow(false);
      }
    };
  });
  useClickAway(wrapperRef, onClickAway, 'touchstart');
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
    ref: wrapperRef,
    className: cls(bem('wrapper')),
    onClick: onClickWrapper
  }, props.reference), /*#__PURE__*/React.createElement(Popup, _extends({
    ref: popoverRef,
    visible: visible,
    className: cls(bem([props.theme])),
    position: "",
    transition: "rv-zoom",
    lockScroll: false
  }, pick(props, popupProps)), /*#__PURE__*/React.createElement("div", {
    className: cls(bem('arrow'))
  }), /*#__PURE__*/React.createElement("div", {
    role: "menu",
    className: cls(bem('content'))
  }, children || props.actions.map(renderAction))));
});
Popover.defaultProps = {
  overlay: false,
  duration: 300,
  closeOnClickAction: true,
  closeOnClickOverlay: true,
  closeOnClickOutside: true,
  offset: [0, 8],
  theme: 'light',
  trigger: 'click',
  actions: [],
  placement: 'bottom'
};
export default Popover;