var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/checkout/components/PaymentResultToast/PaymentResultToastProvider.tsx
var PaymentResultToastProvider_exports = {};
__export(PaymentResultToastProvider_exports, {
  PaymentResultToastProvider: () => PaymentResultToastProvider,
  clearAllPaymentResultToasts: () => clearAllPaymentResultToasts,
  closePaymentResultToast: () => closePaymentResultToast,
  getPaymentResultToastCount: () => getPaymentResultToastCount,
  globalToastManager: () => globalToastManager,
  setTillButton: () => setTillButton,
  showPaymentResultToast: () => showPaymentResultToast,
  showPaymentResultToastFailed: () => showPaymentResultToastFailed,
  showPaymentResultToastPartiallyPaid: () => showPaymentResultToastPartiallyPaid,
  showPaymentResultToastSuccess: () => showPaymentResultToastSuccess,
  showPaymentResultToastWalletPassFailed: () => showPaymentResultToastWalletPassFailed,
  usePaymentResultToast: () => usePaymentResultToast
});
module.exports = __toCommonJS(PaymentResultToastProvider_exports);
var import_react = __toESM(require("react"));
var import_react_dom = require("react-dom");
var import_index = __toESM(require("./index"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var PaymentResultToastContext = (0, import_react.createContext)(null);
var globalPaymentResultToastContext = null;
var DEFAULT_TOAST_CONFIG = {
  width: 680,
  mask: false,
  maskClosable: false,
  closable: true
  // 移除强制的zIndex设置，让Toast使用默认层级或由外部控制
};
var PaymentResultToastProvider = ({ children }) => {
  var _a, _b, _c;
  const [contextToastIds, setContextToastIds] = (0, import_react.useState)([]);
  const context = (0, import_useEngineContext.default)();
  const { interaction } = ((_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) || {};
  (_c = (_b = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _b.asyncDataManager) == null ? void 0 : _c.call(_b, {
    module: "get",
    key: "till_button"
  }).then((res) => {
    globalToastManager.setTillButton(res);
  }).catch((err) => {
    console.error("Failed to get till_button from asyncDataManager:", err);
  });
  const closeToast = (0, import_react.useCallback)(() => {
    contextToastIds.forEach((id) => {
      globalToastManager.removeToast(id);
    });
    setContextToastIds([]);
  }, [contextToastIds]);
  const showToast = (0, import_react.useCallback)((config) => {
    const toastId = globalToastManager.addToast({
      ...config,
      onClose: () => {
        var _a2;
        (_a2 = config.onClose) == null ? void 0 : _a2.call(config);
        setContextToastIds((prev) => prev.filter((id) => id !== toastId));
      }
    });
    setContextToastIds((prev) => [...prev, toastId]);
    return toastId;
  }, []);
  const showSuccess = (0, import_react.useCallback)((config) => {
    return showToast({ ...config, statusClassName: "success" });
  }, [showToast]);
  const showFailed = (0, import_react.useCallback)((config) => {
    return showToast({ ...config, statusClassName: "failed" });
  }, [showToast]);
  const showWalletPassFailed = (0, import_react.useCallback)((config) => {
    return showToast({ ...config, statusClassName: "wallet-pass-failed" });
  }, [showToast]);
  const showPartiallyPaid = (0, import_react.useCallback)((config) => {
    return showToast({ ...config, statusClassName: "partially-paid" });
  }, [showToast]);
  const isVisible = contextToastIds.length > 0;
  const contextValue = {
    showSuccess,
    showFailed,
    showWalletPassFailed,
    showPartiallyPaid,
    showToast,
    closeToast,
    isVisible
  };
  (0, import_react.useEffect)(() => {
    globalPaymentResultToastContext = contextValue;
    return () => {
      globalPaymentResultToastContext = null;
    };
  }, [contextValue]);
  return /* @__PURE__ */ import_react.default.createElement(PaymentResultToastContext.Provider, { value: contextValue }, children);
};
var usePaymentResultToast = () => {
  const context = (0, import_react.useContext)(PaymentResultToastContext);
  if (!context) {
    throw new Error("usePaymentResultToast must be used within a PaymentResultToastProvider");
  }
  return context;
};
var GlobalToastManager = class {
  instances = /* @__PURE__ */ new Map();
  nextId = 1;
  TOAST_HEIGHT = 160;
  // 单个Toast的高度（估算：内容约128px + padding 32px）
  TOAST_MARGIN = 8;
  // Toast之间的间距
  BOTTOM_OFFSET = 110;
  // 距离底部的距离
  LEFT_OFFSET = 96;
  // 距离左边的距离
  cachedBottomOffset = null;
  // 缓存计算的bottom位置
  cachedCenterOffset = null;
  // 缓存计算的center位置
  tillButton = null;
  // 缓存的tillButton数据
  setTillButton(tillButton) {
    this.tillButton = tillButton;
  }
  // 生成唯一ID
  generateId() {
    return `toast-${this.nextId++}`;
  }
  // 计算并缓存 .ticket-booking-left-panel-content 组件的 bottom 位置
  calculateAndCacheBottomOffset() {
    var _a;
    if (this.cachedBottomOffset !== null) {
      return this.cachedBottomOffset;
    }
    if ((_a = this.tillButton) == null ? void 0 : _a.y) {
      console.log("使用钱箱按钮位置", this.tillButton);
      this.cachedBottomOffset = window.innerHeight - this.tillButton.y + 8 + this.tillButton.size;
      console.log("计算钱箱按钮位置得到的bottom位置", this.cachedBottomOffset);
      return this.cachedBottomOffset;
    }
    const bodyElement = document.querySelector("body");
    if (bodyElement) {
      const rect = bodyElement.getBoundingClientRect();
      const windowHeight = window.innerHeight;
      this.cachedBottomOffset = windowHeight - rect.bottom + 16;
    } else {
      this.cachedBottomOffset = this.BOTTOM_OFFSET;
    }
    return this.cachedBottomOffset;
  }
  calculateAndCacheCenterOffset() {
    if (this.cachedCenterOffset !== null) {
      return this.cachedCenterOffset;
    }
    const ticketBookingElement = document.querySelector(".ticket-booking-left-panel-content");
    if (ticketBookingElement) {
      const rect = ticketBookingElement.getBoundingClientRect();
      this.cachedCenterOffset = {
        x: rect.width / 2,
        y: rect.height / 2
      };
    } else {
      this.cachedCenterOffset = { x: 0, y: 0 };
    }
    return this.cachedCenterOffset;
  }
  // 重置缓存的 bottom 位置（当窗口大小变化或组件位置变化时调用）
  resetBottomOffsetCache() {
    this.cachedBottomOffset = null;
  }
  // 计算Toast的bottom位置
  // 新逻辑：最新的Toast在最底部，旧Toast向上位移
  calculateBottomPosition(offsetIndex, totalCount) {
    const reversedIndex = totalCount - 1 - offsetIndex;
    const dynamicBottomOffset = this.calculateAndCacheBottomOffset();
    return dynamicBottomOffset + (this.TOAST_HEIGHT + this.TOAST_MARGIN) * reversedIndex;
  }
  // 更新所有Toast的位置（新Toast在底部，旧Toast平滑向上位移）
  updatePositions() {
    const instances = Array.from(this.instances.values());
    const totalCount = instances.length;
    instances.forEach((instance, index) => {
      instance.offsetIndex = index;
      const bottomPosition = this.calculateBottomPosition(index, totalCount);
      if (instance.container) {
        const hasMask = instance.container.getAttribute("data-mask") === "true";
        if (hasMask) {
          return;
        }
        instance.container.classList.add("toast-moving");
        instance.container.style.position = "fixed";
        instance.container.style.left = `${this.LEFT_OFFSET}px`;
        instance.container.style.bottom = `${bottomPosition}px`;
        instance.container.style.top = "auto";
        instance.container.style.right = "auto";
        instance.container.style.transition = "all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94)";
        instance.container.style.pointerEvents = "none";
        instance.container.style.width = "auto";
        instance.container.style.height = "auto";
        instance.container.style.transform = "none";
        instance.container.style.margin = "0";
        setTimeout(() => {
          if (instance.container) {
            instance.container.classList.remove("toast-moving");
          }
        }, 400);
      }
    });
  }
  // 添加新的Toast实例
  addToast(config) {
    const id = this.generateId();
    this.resetBottomOffsetCache();
    const finalConfig = {
      ...DEFAULT_TOAST_CONFIG,
      visible: true,
      statusClassName: config.statusClassName,
      title: config.title,
      subtitle: config.subtitle,
      changeDueText: config.changeDueText,
      actionButtons: config.actionButtons || [],
      autoClose: config.autoClose,
      autoCloseDelay: config.autoCloseDelay || 30,
      showCountdownProgress: config.showCountdownProgress,
      clickOutsideToClose: config.clickOutsideToClose,
      onCountdownComplete: config.onCountdownComplete,
      onClose: () => {
        var _a;
        (_a = config.onClose) == null ? void 0 : _a.call(config);
        this.removeToast(id);
      },
      closable: config.closable !== void 0 ? config.closable : DEFAULT_TOAST_CONFIG.closable,
      mask: config.mask || false
    };
    const container = document.createElement("div");
    container.setAttribute("data-toast-id", id);
    if (config.mask) {
      container.setAttribute("data-mask", "true");
    }
    const dynamicBottomOffset = this.calculateAndCacheBottomOffset();
    container.style.position = "fixed";
    if (config.mask) {
      container.style.left = "50%";
      container.style.top = "50%";
      container.style.transform = "translate(-50%, -50%)";
      container.style.bottom = "auto";
      container.style.right = "auto";
    } else {
      container.style.left = `${this.LEFT_OFFSET}px`;
      container.style.bottom = `${dynamicBottomOffset}px`;
      container.style.top = "auto";
      container.style.right = "auto";
      container.style.transform = "none";
    }
    const modalMaskElement = document.querySelector(".payment-modal-wrapper");
    if (modalMaskElement) {
      container.style.zIndex = `${Number(modalMaskElement.style.zIndex || 1e3) + 1}`;
    }
    container.style.pointerEvents = "none";
    container.style.width = "auto";
    container.style.height = "auto";
    container.style.margin = "0";
    document.body.appendChild(container);
    const instance = {
      id,
      container,
      props: finalConfig,
      offsetIndex: this.instances.size
    };
    this.instances.set(id, instance);
    (0, import_react_dom.render)(/* @__PURE__ */ import_react.default.createElement(import_index.default, { ...finalConfig }), container);
    return id;
  }
  // 移除Toast实例（带动画效果）
  removeToast(id) {
    const instance = this.instances.get(id);
    if (instance) {
      if (instance.container) {
        instance.container.classList.add("toast-exiting");
        setTimeout(() => {
          if (instance.container) {
            (0, import_react_dom.unmountComponentAtNode)(instance.container);
            if (document.body.contains(instance.container)) {
              document.body.removeChild(instance.container);
            }
          }
          this.instances.delete(id);
          this.updatePositions();
        }, 300);
      } else {
        this.instances.delete(id);
        this.updatePositions();
      }
    }
  }
  // 清理所有Toast
  clearAll() {
    this.instances.forEach((instance) => {
      if (instance.container) {
        (0, import_react_dom.unmountComponentAtNode)(instance.container);
        if (document.body.contains(instance.container)) {
          document.body.removeChild(instance.container);
        }
      }
    });
    this.instances.clear();
  }
  // 获取当前Toast数量
  getCount() {
    return this.instances.size;
  }
  // 初始化窗口大小变化监听器
  initializeResizeListener() {
    const handleResize = () => {
      this.resetBottomOffsetCache();
      this.updatePositions();
    };
    window.addEventListener("resize", handleResize);
    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }
};
var globalToastManager = new GlobalToastManager();
if (typeof window !== "undefined") {
  globalToastManager.initializeResizeListener();
}
var renderGlobalToast = (config) => {
  return globalToastManager.addToast(config);
};
var showPaymentResultToastSuccess = async (config) => {
  return renderGlobalToast({ ...config, statusClassName: "success" });
};
var showPaymentResultToastFailed = async (config) => {
  return renderGlobalToast({ ...config, statusClassName: "failed" });
};
var showPaymentResultToastWalletPassFailed = async (config) => {
  return renderGlobalToast({ ...config, statusClassName: "wallet-pass-failed" });
};
var showPaymentResultToastPartiallyPaid = async (config) => {
  return renderGlobalToast({ ...config, statusClassName: "partially-paid" });
};
var showPaymentResultToast = async (config) => {
  return renderGlobalToast(config);
};
var closePaymentResultToast = (id) => {
  if (id) {
    globalToastManager.removeToast(id);
  } else {
    globalToastManager.clearAll();
  }
};
var clearAllPaymentResultToasts = () => {
  globalToastManager.clearAll();
};
var getPaymentResultToastCount = () => {
  return globalToastManager.getCount();
};
var setTillButton = (tillButton) => {
  globalToastManager.setTillButton(tillButton);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PaymentResultToastProvider,
  clearAllPaymentResultToasts,
  closePaymentResultToast,
  getPaymentResultToastCount,
  globalToastManager,
  setTillButton,
  showPaymentResultToast,
  showPaymentResultToastFailed,
  showPaymentResultToastPartiallyPaid,
  showPaymentResultToastSuccess,
  showPaymentResultToastWalletPassFailed,
  usePaymentResultToast
});
