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); }

/* eslint-disable no-plusplus */
import React, { useMemo, useState, useEffect, useRef, forwardRef, useImperativeHandle, useContext } from 'react';
import clsx from 'clsx';
import { CSSTransition } from 'react-transition-group';
import { Cross } from '@react-vant/icons';
import Overlay from '../overlay';
import useEventListener from '../hooks/use-event-listener';
import { isDef } from '../utils';
import { callInterceptor } from '../utils/interceptor';
import { renderToContainer } from '../utils/dom/renderToContainer';
import useSsrCompat from '../hooks/use-ssr-compat';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
import PopupContext from './PopupContext';
export var sharedPopupProps = ['round', 'zIndex', 'closeable', 'overlay', 'overlayClass', 'overlayStyle', 'destroyOnClose', 'forceRender', 'lockScroll', 'duration', 'transition', 'closeOnClickOverlay', 'closeOnPopstate', 'onClickOverlay', 'safeAreaInsetBottom', 'onOpen', 'onClose', 'onOpened', 'onClosed', 'beforeClose'];
var globalZIndex = 2000;
var Popup = /*#__PURE__*/forwardRef(function (props, ref) {
  var _props$zIndex;

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

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

  var round = props.round,
      visible = props.visible,
      closeable = props.closeable,
      title = props.title,
      descrition = props.descrition,
      children = props.children,
      duration = props.duration,
      closeIcon = props.closeIcon,
      position = props.position;
  var opened = useRef(false);
  var zIndex = useRef((_props$zIndex = props.zIndex) != null ? _props$zIndex : globalZIndex);
  var popupRef = useRef();

  var _useState = useState(visible),
      animatedVisible = _useState[0],
      setAnimatedVisible = _useState[1];

  var _useSsrCompat = useSsrCompat(),
      ssrCompatRender = _useSsrCompat[0],
      rendered = _useSsrCompat[1];

  var style = useMemo(function () {
    var initStyle = _extends({
      zIndex: zIndex.current
    }, props.style);

    if (isDef(props.duration)) {
      var key = props.position === 'center' ? 'animationDuration' : 'transitionDuration';
      initStyle[key] = props.duration + "ms";
    }

    return initStyle;
  }, [zIndex.current, props.style, props.duration]);

  var open = function open() {
    if (props.zIndex !== undefined) {
      zIndex.current = +props.zIndex;
    } else {
      zIndex.current = globalZIndex++;
    }

    opened.current = true;
    props.onOpen == null ? void 0 : props.onOpen();
  };

  var close = function close() {
    if (opened.current) {
      callInterceptor({
        interceptor: props.beforeClose,
        args: ['close'],
        done: function done() {
          opened.current = false;
          props.onClose == null ? void 0 : props.onClose();
        }
      });
    }
  };

  var onClickOverlay = function onClickOverlay(event) {
    props.onClickOverlay == null ? void 0 : props.onClickOverlay(event);

    if (props.closeOnClickOverlay) {
      close();
    }
  };

  var renderOverlay = function renderOverlay() {
    if (props.overlay) {
      return /*#__PURE__*/React.createElement(Overlay, {
        visible: visible && rendered,
        lockScroll: props.lockScroll,
        className: props.overlayClass,
        customStyle: props.overlayStyle,
        zIndex: zIndex.current,
        duration: duration,
        onClick: onClickOverlay
      });
    }

    return null;
  };

  var onClickCloseIcon = function onClickCloseIcon(e) {
    if (props.onClickCloseIcon) {
      props.onClickCloseIcon(e);
    }

    close();
  };

  var renderCloseIcon = function renderCloseIcon() {
    if (closeable) {
      var closeIconPosition = props.closeIconPosition;

      if (closeIcon) {
        return /*#__PURE__*/React.createElement("div", {
          className: clsx(bem('close-icon', closeIconPosition)),
          onClick: onClickCloseIcon
        }, closeIcon);
      }

      return null;
    }

    return null;
  };

  var renderTitle = function renderTitle() {
    if (title) {
      return /*#__PURE__*/React.createElement("div", {
        className: clsx(bem('title'))
      }, title);
    }

    return null;
  };

  var renderDescrition = function renderDescrition() {
    if (descrition) {
      return /*#__PURE__*/React.createElement("div", {
        className: clsx(bem('descrition'))
      }, descrition);
    }

    return null;
  };

  var renderPopup = function renderPopup() {
    var _bem;

    var safeAreaInsetBottom = props.safeAreaInsetBottom;
    return /*#__PURE__*/React.createElement("div", {
      ref: popupRef,
      style: _extends({}, style, {
        display: !visible && !animatedVisible ? 'none' : undefined
      }),
      className: clsx(bem((_bem = {
        round: round
      }, _bem[position] = position, _bem)), {
        'rv-safe-area-bottom': safeAreaInsetBottom
      }, props.className),
      onClick: props.onClick
    }, renderTitle(), renderDescrition(), children, renderCloseIcon());
  };

  var renderTransition = function renderTransition() {
    var transition = props.transition,
        destroyOnClose = props.destroyOnClose,
        forceRender = props.forceRender;
    var name = position === 'center' ? prefixCls + "-fade" : prefixCls + "-popup-slide-" + position;
    return /*#__PURE__*/React.createElement(CSSTransition, {
      in: visible && rendered
      /**
       * https://github.com/reactjs/react-transition-group/pull/559
       */
      ,
      nodeRef: popupRef,
      timeout: duration,
      classNames: transition || name,
      mountOnEnter: !forceRender,
      unmountOnExit: destroyOnClose,
      onEnter: open,
      onEntered: props.onOpened,
      onExited: function onExited() {
        setAnimatedVisible(false);
        props.onClosed == null ? void 0 : props.onClosed();
      }
    }, renderPopup());
  };

  useEventListener('popstate', function () {
    if (props.closeOnPopstate) {
      close();
    }
  });
  useEffect(function () {
    if (!rendered) return;

    if (visible) {
      setAnimatedVisible(true);
    }
  }, [visible, rendered]);
  useImperativeHandle(ref, function () {
    return {
      popupRef: popupRef
    };
  });
  return ssrCompatRender(function () {
    return renderToContainer(props.teleport, /*#__PURE__*/React.createElement(PopupContext.Provider, {
      value: {
        visible: visible
      }
    }, renderOverlay(), renderTransition()));
  });
});
Popup.defaultProps = {
  duration: 300,
  overlay: true,
  lockScroll: true,
  position: 'center',
  closeIcon: /*#__PURE__*/React.createElement(Cross, null),
  closeIconPosition: 'top-right',
  closeOnClickOverlay: true,
  teleport: function teleport() {
    return document.body;
  }
};
export default Popup;