function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(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(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { memo, useCallback, useEffect, useState, useRef } from 'react';
import classnames from 'classnames';
import { Button, ButtonGroupPreview, PisellModal } from '@pisell/materials';
import XClose from '@pisell/icon/es/XClose';
import { getDefaultModalConfig } from "./utils";
import "./index.less";

// 组件样式前缀，用于样式隔离
var COMPONENT_PREFIX = 'payment-result-toast';

// 生成带前缀的类名，实现样式隔离
var getClassName = function getClassName() {
  for (var _len = arguments.length, classNames = new Array(_len), _key = 0; _key < _len; _key++) {
    classNames[_key] = arguments[_key];
  }
  return classnames(classNames.filter(Boolean).map(function (className) {
    return typeof className === 'string' && !className.startsWith(COMPONENT_PREFIX) ? "".concat(COMPONENT_PREFIX, "-").concat(className) : className;
  }));
};

// 生成基础组件类名
var getBaseClassName = function getBaseClassName(extraClassName) {
  return classnames(COMPONENT_PREFIX, extraClassName);
};
var PaymentResultToast = /*#__PURE__*/memo(function (props) {
  var _props$visible = props.visible,
    visible = _props$visible === void 0 ? false : _props$visible,
    onClose = props.onClose,
    className = props.className,
    _props$statusClassNam = props.statusClassName,
    statusClassName = _props$statusClassNam === void 0 ? 'success' : _props$statusClassNam,
    title = props.title,
    subtitle = props.subtitle,
    changeDueText = props.changeDueText,
    _props$actionButtons = props.actionButtons,
    actionButtons = _props$actionButtons === void 0 ? [] : _props$actionButtons,
    _props$autoClose = props.autoClose,
    autoClose = _props$autoClose === void 0 ? false : _props$autoClose,
    _props$autoCloseDelay = props.autoCloseDelay,
    autoCloseDelay = _props$autoCloseDelay === void 0 ? 30 : _props$autoCloseDelay,
    _props$showCountdownP = props.showCountdownProgress,
    showCountdownProgress = _props$showCountdownP === void 0 ? true : _props$showCountdownP,
    onCountdownComplete = props.onCountdownComplete,
    width = props.width,
    height = props.height,
    _props$mask = props.mask,
    mask = _props$mask === void 0 ? false : _props$mask,
    _props$maskClosable = props.maskClosable,
    maskClosable = _props$maskClosable === void 0 ? false : _props$maskClosable,
    _props$closable = props.closable,
    closable = _props$closable === void 0 ? true : _props$closable,
    zIndex = props.zIndex,
    _props$clickOutsideTo = props.clickOutsideToClose,
    clickOutsideToClose = _props$clickOutsideTo === void 0 ? true : _props$clickOutsideTo;

  // 倒计时相关状态
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isAnimating = _useState2[0],
    setIsAnimating = _useState2[1];
  var countdownTimeoutRef = useRef(null);

  // 弹窗内容引用，用于 click outside 检测
  var modalContentRef = useRef(null);
  // Modal 根容器引用
  var modalRef = useRef(null);

  // 使用ref保存回调函数，避免依赖变化导致倒计时重置
  var onCloseRef = useRef(onClose);
  var onCountdownCompleteRef = useRef(onCountdownComplete);

  // 更新ref中的回调函数
  onCloseRef.current = onClose;
  onCountdownCompleteRef.current = onCountdownComplete;

  // 合并默认配置
  var modalConfig = getDefaultModalConfig();

  // 清理倒计时
  var clearCountdown = useCallback(function () {
    if (countdownTimeoutRef.current) {
      clearTimeout(countdownTimeoutRef.current);
      countdownTimeoutRef.current = null;
    }
    setIsAnimating(false);
  }, []);

  // 启动倒计时
  var startCountdown = useCallback(function () {
    if (!autoClose || !visible) return;
    clearCountdown();

    // 立即启动 CSS 动画，不等待
    setIsAnimating(true);

    // 设置定时器，在倒计时结束时自动关闭
    countdownTimeoutRef.current = setTimeout(function () {
      var _onCountdownCompleteR, _onCloseRef$current;
      // 只清理定时器，不重置动画状态
      countdownTimeoutRef.current = null;
      // 倒计时结束，直接关闭弹窗
      (_onCountdownCompleteR = onCountdownCompleteRef.current) === null || _onCountdownCompleteR === void 0 || _onCountdownCompleteR.call(onCountdownCompleteRef);
      (_onCloseRef$current = onCloseRef.current) === null || _onCloseRef$current === void 0 || _onCloseRef$current.call(onCloseRef);
    }, autoCloseDelay * 1000);
  }, [autoClose, autoCloseDelay, visible, clearCountdown]);

  // 监听弹窗可见状态，立即重置状态并控制倒计时
  useEffect(function () {
    if (visible) {
      // 立即重置动画状态
      setIsAnimating(false);
      if (autoClose) {
        // 直接启动倒计时，不等待任何延迟
        // 通过Portal渲染和性能优化，Modal可以立即响应
        startCountdown();
      }
    } else {
      clearCountdown();
    }
    return clearCountdown;
  }, [visible, autoClose, startCountdown, clearCountdown]);

  // 组件卸载时清理倒计时
  useEffect(function () {
    return clearCountdown;
  }, [clearCountdown]);

  // Click outside 检测
  useEffect(function () {
    if (!clickOutsideToClose || !visible) {
      return;
    }
    var handleClickOutside = function handleClickOutside(event) {
      var target = event.target;
      var modalContent = modalContentRef.current;
      if (!modalContent) {
        return;
      }

      // 检查点击的目标元素是否在弹窗内容之外
      if (!modalContent.contains(target)) {
        var _onCloseRef$current2;
        // 点击在弹窗外部，关闭弹窗
        clearCountdown(); // 取消倒计时
        (_onCloseRef$current2 = onCloseRef.current) === null || _onCloseRef$current2 === void 0 || _onCloseRef$current2.call(onCloseRef);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('pointerup', handleClickOutside);
    // 清理函数
    return function () {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('pointerup', handleClickOutside);
    };
  }, [clickOutsideToClose, visible, clearCountdown]);

  // 处理关闭操作（关闭按钮点击时也取消倒计时）
  var handleClose = useCallback(function () {
    var _onCloseRef$current3;
    clearCountdown(); // 取消倒计时
    (_onCloseRef$current3 = onCloseRef.current) === null || _onCloseRef$current3 === void 0 || _onCloseRef$current3.call(onCloseRef);
  }, [clearCountdown]);

  // 渲染标题（合并原副标题内容）
  var renderTitle = function renderTitle() {
    if (!subtitle) {
      return null;
    }
    if (closable) {
      return /*#__PURE__*/React.createElement("div", {
        style: {
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          gap: '16px'
        }
      }, subtitle, /*#__PURE__*/React.createElement(Button, {
        style: {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        },
        type: "text",
        icon: /*#__PURE__*/React.createElement(XClose, {
          style: {
            fontSize: '40px',
            color: 'white'
          }
        }),
        onClick: handleClose
      }));
    }

    // 直接渲染副标题内容作为标题，保持原有的样式和结构
    return subtitle;
  };

  // 渲染找零信息
  var renderChangeDueInfo = function renderChangeDueInfo() {
    if (!changeDueText) {
      return null;
    }
    return /*#__PURE__*/React.createElement("div", {
      className: getClassName('subtitle')
    }, /*#__PURE__*/React.createElement("div", {
      className: getClassName('subtitle-text change-due')
    }, changeDueText));
  };

  // 渲染倒计时进度条
  var renderCountdownProgress = function renderCountdownProgress() {
    if (!autoClose || !showCountdownProgress || !visible) {
      return null;
    }
    var progressBarClassName = classnames(getClassName('countdown-progress-bar'), {
      'animating': isAnimating
    });

    // 动态设置动画持续时间
    var animationStyle = isAnimating ? {
      animationDuration: "".concat(autoCloseDelay, "s")
    } : {};
    return /*#__PURE__*/React.createElement("div", {
      className: getClassName('countdown')
    }, /*#__PURE__*/React.createElement("div", {
      className: getClassName('countdown-text')
    }), /*#__PURE__*/React.createElement("div", {
      className: getClassName('countdown-progress')
    }, /*#__PURE__*/React.createElement("div", {
      className: progressBarClassName,
      style: animationStyle
    })));
  };

  // 处理按钮点击，取消倒计时
  var handleButtonClick = useCallback(function () {
    // 如果存在倒计时，则取消倒计时
    if (autoClose && countdownTimeoutRef.current) {
      clearCountdown();
    }
  }, [autoClose, clearCountdown]);

  // 渲染操作按钮
  var renderActionButtons = function renderActionButtons() {
    if (!actionButtons || actionButtons.length === 0) {
      return null;
    }
    return /*#__PURE__*/React.createElement("div", {
      onClick: handleButtonClick
    }, /*#__PURE__*/React.createElement(ButtonGroupPreview, {
      buttonGroupList: actionButtons
    }));
  };
  return /*#__PURE__*/React.createElement(PisellModal, {
    open: visible,
    onCancel: handleClose,
    footer: null,
    width: width || modalConfig.width,
    mask: mask,
    maskClosable: maskClosable,
    closable: false,
    className: getBaseClassName("".concat(className, " ").concat(statusClassName, " ").concat(mask ? 'payment-result-toast-with-mask' : '')),
    wrapClassName: "toast-modal-wrap ".concat(mask ? 'toast-modal-wrap-with-mask' : ''),
    style: _objectSpread(_objectSpread({}, height ? {
      height: "".concat(height, "px")
    } : {}), {}, {
      // 确保Modal不会被默认定位影响
      position: 'static',
      top: 'auto',
      left: 'auto',
      right: 'auto',
      bottom: 'auto',
      transform: 'none',
      margin: 0,
      padding: 0,
      width: '100%',
      maxWidth: 'none'
    }),
    destroyOnClose: false
    // 优化Modal渲染性能
    ,
    forceRender: true
    // 禁用Modal的默认focus逻辑，减少渲染延迟
    ,
    focusTriggerAfterClose: false
    // 禁用默认动画，使用自定义CSS动画
    ,
    transitionName: "",
    maskTransitionName: ""
    // mask 模式下使用居中定位，非 mask 模式下禁用居中
    ,
    centered: mask
    // mask 模式下渲染到 body，非 mask 模式下渲染到容器内
    ,
    getContainer: mask ? undefined : false
  }, /*#__PURE__*/React.createElement("div", {
    ref: modalContentRef,
    className: getClassName('content', statusClassName),
    style: {
      position: 'relative',
      zIndex: 1
    }
  }, renderTitle(), renderChangeDueInfo(), renderActionButtons(), renderCountdownProgress()));
});
PaymentResultToast.displayName = 'PaymentResultToast';
export default PaymentResultToast;

// 导出Provider相关
export { PaymentResultToastProvider, usePaymentResultToast, showPaymentResultToastSuccess, showPaymentResultToastFailed, showPaymentResultToastWalletPassFailed, showPaymentResultToastPartiallyPaid, showPaymentResultToast, closePaymentResultToast, clearAllPaymentResultToasts, getPaymentResultToastCount, setTillButton, globalToastManager } from "./PaymentResultToastProvider";

// 导出工具函数
export { closeAllPaymentResultToasts, hasActivePaymentResultToasts, getToastCount, debounce, getDefaultModalConfig } from "./utils";

// 全局Provider功能已集成到PaymentResultToastProvider中，无需额外导出

// 导出类型