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/plus/salesSdk/context/SalesSdkProvider.tsx
var SalesSdkProvider_exports = {};
__export(SalesSdkProvider_exports, {
  SalesSdkPrepareOrderSwitchContext: () => SalesSdkPrepareOrderSwitchContext,
  SalesSdkProvider: () => SalesSdkProvider,
  SalesSdkRootRefreshContext: () => SalesSdkRootRefreshContext
});
module.exports = __toCommonJS(SalesSdkProvider_exports);
var import_react = __toESM(require("react"));
var import_ahooks = require("ahooks");
var import_dayjs = __toESM(require("dayjs"));
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_utils = require("../../../components/ticketBooking/utils");
var import_SalesSdkContext = require("./SalesSdkContext");
var import_SalesSdkProductContext = require("./SalesSdkProductContext");
var import_SalesSdkCartContext = require("./SalesSdkCartContext");
var import_SalesSdkCustomerContext = require("./SalesSdkCustomerContext");
var import_SalesSdkHolderContext = require("./SalesSdkHolderContext");
var import_SalesSdkSummaryContext = require("./SalesSdkSummaryContext");
var import_SalesSdkUIHostsContext = require("./SalesSdkUIHostsContext");
var import_SalesSdkHostBridgesContext = require("./SalesSdkHostBridgesContext");
var import_BookingEditHostRenderer = require("../hosts/BookingEditHostRenderer");
var import_MultiDayHostRenderer = require("../hosts/MultiDayHostRenderer");
var import_HolderHostRenderer = require("../hosts/HolderHostRenderer");
var import_ConfirmHolderHostRenderer = require("../hosts/ConfirmHolderHostRenderer");
var import_ensureHoldersBeforeSubmit = require("../utils/ensureHoldersBeforeSubmit");
var import_createHolderConfirmBridge = require("../holderConfirm/createHolderConfirmBridge");
var import_NormalProductDetailHostRenderer = require("../normalProductDetail/NormalProductDetailHostRenderer");
var import_useSalesSdkTempOrderSync = require("../hooks/useSalesSdkTempOrderSync");
var import_createOpenBookingEditHost = require("../hosts/createOpenBookingEditHost");
var import_createOpenMultiDaySelectHost = require("../hosts/createOpenMultiDaySelectHost");
var import_createOpenHolderSelectHost = require("../hosts/createOpenHolderSelectHost");
var import_createCompositeOpenProductDetailHost = require("../hosts/createCompositeOpenProductDetailHost");
var import_createOpenNormalProductDetailHost = require("../normalProductDetail/createOpenNormalProductDetailHost");
var import_createOpenGiftSelectHost = require("../giftSelect/createOpenGiftSelectHost");
var import_GiftSelectHostRenderer = require("../giftSelect/GiftSelectHostRenderer");
var import_payment_modal_utils = require("../../../components/checkout/payment-modal-utils");
var import_buildDefaultLoadProductsParams = require("../utils/buildDefaultLoadProductsParams");
var import_ensureSalesSdkHttpRequest = require("../utils/ensureSalesSdkHttpRequest");
var import_useSalesSdkCart = require("../hooks/useSalesSdkCart");
var import_SalesSdkGlobalScanSubscriber = require("../components/SalesSdkGlobalScanSubscriber");
var EMPTY_ROOT_SNAPSHOT = {
  tempOrder: null,
  salesDetail: null
};
var EMPTY_DISCOUNT_LIST = [];
function cloneArray(value, fallback) {
  return Array.isArray(value) ? [...value] : fallback;
}
function cloneTempOrder(tempOrder) {
  if (!tempOrder) return null;
  return {
    ...tempOrder,
    products: cloneArray(tempOrder.products, []),
    bookings: cloneArray(tempOrder.bookings, []),
    payments: cloneArray(tempOrder.payments, []),
    surcharges: cloneArray(tempOrder.surcharges, []),
    discount_list: cloneArray(tempOrder.discount_list, []),
    relation_forms: cloneArray(tempOrder.relation_forms, []),
    contacts: cloneArray(tempOrder.contacts, []),
    contacts_info: tempOrder.contacts_info,
    summary: tempOrder.summary ? { ...tempOrder.summary } : tempOrder.summary
  };
}
function readRootSnapshot(bookingTicket) {
  var _a, _b;
  if (!bookingTicket) return EMPTY_ROOT_SNAPSHOT;
  try {
    return {
      tempOrder: cloneTempOrder(((_a = bookingTicket.getTempOrder) == null ? void 0 : _a.call(bookingTicket)) ?? null),
      salesDetail: ((_b = bookingTicket.getSalesOrder) == null ? void 0 : _b.call(bookingTicket)) ?? null
    };
  } catch (e) {
    console.warn("[SalesSdk] readRootSnapshot 失败", e);
    return EMPTY_ROOT_SNAPSHOT;
  }
}
var SalesSdkRootRefreshContext = (0, import_react.createContext)(null);
SalesSdkRootRefreshContext.displayName = "SalesSdkRootRefreshContext";
var SalesSdkPrepareOrderSwitchContext = (0, import_react.createContext)(null);
SalesSdkPrepareOrderSwitchContext.displayName = "SalesSdkPrepareOrderSwitchContext";
function SalesSdkBootstrap({
  autoRestoreOnInit,
  autoBootstrap,
  autoInitBookingContext,
  orderId,
  initBookingContext
}) {
  const sales = (0, import_react.useContext)(import_SalesSdkContext.SalesSdkContext);
  const cart = (0, import_useSalesSdkCart.useSalesSdkCart)();
  (0, import_react.useEffect)(() => {
    if (!(sales == null ? void 0 : sales.bookingTicket)) return;
    let cancelled = false;
    (async () => {
      var _a, _b;
      try {
        if (autoRestoreOnInit) {
          await sales.restore();
          if (cancelled) return;
          await cart.recalcSummary();
        }
        if (autoBootstrap && orderId) {
          if (cancelled) return;
          await sales.loadDetail(orderId);
        }
        if (cancelled || !autoInitBookingContext) return;
        const bookingIds = (0, import_buildDefaultLoadProductsParams.collectBookingIdsFromTempOrder)(
          ((_b = (_a = sales.bookingTicket) == null ? void 0 : _a.getTempOrder) == null ? void 0 : _b.call(_a)) ?? null
        );
        await initBookingContext(bookingIds.length ? bookingIds : void 0);
      } catch (e) {
        if (!cancelled) {
          console.warn("[SalesSdk] bootstrap 失败", e);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [
    sales == null ? void 0 : sales.bookingTicket,
    sales == null ? void 0 : sales.osKey,
    sales == null ? void 0 : sales.restore,
    sales == null ? void 0 : sales.loadDetail,
    cart.recalcSummary,
    autoRestoreOnInit,
    autoBootstrap,
    autoInitBookingContext,
    orderId,
    initBookingContext
  ]);
  return null;
}
var SalesSdkProvider = ({
  osKey,
  businessCode,
  bookingConfigParams,
  autoInitBookingContext = true,
  otherParams,
  rulesHooks,
  orderId,
  autoBootstrap = true,
  autoRestoreOnInit = true,
  restoreOrderAfterPaidCheckout = true,
  uiHosts,
  legacyOpenProductDetail,
  enableTempOrderSync = false,
  enableTempOrderPersist = false,
  isActive = true,
  enableGlobalScanListener = false,
  defaultProductLoadParams,
  children
}) => {
  var _a;
  const context = (0, import_useEngineContext.default)();
  const utils = ((_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) || {};
  const { pisellos, pisellosAllModule, businessUtils, action } = utils;
  (0, import_react.useEffect)(() => {
    (0, import_ensureSalesSdkHttpRequest.ensureSalesSdkHttpRequest)(utils == null ? void 0 : utils.request);
  }, [utils == null ? void 0 : utils.request]);
  const { BookingTicket } = pisellosAllModule || {};
  const bookingTicket = (0, import_react.useMemo)(() => {
    var _a2;
    if (!pisellos || !BookingTicket) return null;
    const moduleKey = (0, import_utils.getBookingTicketKey)(osKey);
    let mod = pisellos.getModule(moduleKey);
    if (!mod) {
      mod = new BookingTicket(moduleKey);
      pisellos.registerModule(mod, {
        otherParams: {
          cacheId: moduleKey,
          platform: (otherParams == null ? void 0 : otherParams.platform) || "pos",
          businessCode,
          isFranchisee: (_a2 = businessUtils == null ? void 0 : businessUtils.getAppByModal) == null ? void 0 : _a2.call(businessUtils, "franchisee"),
          rules: rulesHooks ? { hooks: rulesHooks } : void 0,
          ...otherParams || {},
          enableTempOrderPersist
        }
      });
    }
    return mod;
  }, [pisellos, BookingTicket, osKey]);
  const [status, setStatus] = (0, import_react.useState)("idle");
  const [error, setError] = (0, import_react.useState)(null);
  const [rootSnapshot, setRootSnapshot] = (0, import_react.useState)(EMPTY_ROOT_SNAPSHOT);
  const publishTempOrderRef = (0, import_react.useRef)(() => {
  });
  const summaryProviderRef = (0, import_react.useRef)(null);
  const refreshRootSnapshot = (0, import_ahooks.useMemoizedFn)(() => {
    const nextSnapshot = readRootSnapshot(bookingTicket);
    setRootSnapshot(nextSnapshot);
    publishTempOrderRef.current(nextSnapshot.tempOrder);
  });
  const prepareOrderSwitch = (0, import_ahooks.useMemoizedFn)(() => {
    setError(null);
    setRootSnapshot(EMPTY_ROOT_SNAPSHOT);
    publishTempOrderRef.current(null);
  });
  const { publishTempOrder } = (0, import_useSalesSdkTempOrderSync.useSalesSdkTempOrderSync)({
    enabled: enableTempOrderSync,
    isActive,
    osKey,
    bookingTicket,
    refreshRootSnapshot
  });
  publishTempOrderRef.current = publishTempOrder;
  const hostBridgesRef = (0, import_react.useRef)((0, import_SalesSdkHostBridgesContext.createSalesSdkHostBridges)());
  const hostBridges = hostBridgesRef.current;
  const bookingTicketRef = (0, import_react.useRef)(null);
  bookingTicketRef.current = bookingTicket;
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    if (typeof bookingTicket.setPromotionEvaluator === "function") {
      bookingTicket.setPromotionEvaluator((utils == null ? void 0 : utils.promotionEvaluator) ?? null);
    }
    if (typeof bookingTicket.setGiftSelectResolver === "function") {
      const resolver = (0, import_createOpenGiftSelectHost.createOpenGiftSelectHost)(
        hostBridges.giftSelect,
        () => bookingTicketRef.current
      );
      bookingTicket.setGiftSelectResolver(resolver);
    }
    return () => {
      if (typeof bookingTicket.setPromotionEvaluator === "function") {
        bookingTicket.setPromotionEvaluator(null);
      }
      if (typeof bookingTicket.setGiftSelectResolver === "function") {
        bookingTicket.setGiftSelectResolver(null);
      }
    };
  }, [bookingTicket, utils == null ? void 0 : utils.promotionEvaluator, hostBridges.giftSelect]);
  (0, import_react.useEffect)(() => {
    refreshRootSnapshot();
  }, [bookingTicket, refreshRootSnapshot]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket || typeof bookingTicket.setEnableTempOrderPersist !== "function") return;
    bookingTicket.setEnableTempOrderPersist(enableTempOrderPersist);
  }, [bookingTicket, enableTempOrderPersist]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
      refreshRootSnapshot();
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, refreshRootSnapshot]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onOrderCustomerChange", () => {
      refreshRootSnapshot();
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, refreshRootSnapshot]);
  (0, import_react.useEffect)(() => {
    var _a2;
    if (!bookingTicket) return;
    const orderModule = (_a2 = bookingTicket.store) == null ? void 0 : _a2.order;
    if (!orderModule || typeof orderModule.effectsOn !== "function") {
      return;
    }
    const off = orderModule.effectsOn("onPromotionApplied", () => {
      refreshRootSnapshot();
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, refreshRootSnapshot]);
  (0, import_react.useEffect)(() => {
    if (!bookingTicket) return;
    const off = bookingTicket.effectsOn("onTempOrderReplaced", () => {
      refreshRootSnapshot();
    });
    return () => {
      try {
        off();
      } catch {
      }
    };
  }, [bookingTicket, refreshRootSnapshot]);
  const initBookingContext = (0, import_ahooks.useMemoizedFn)(async (bookingIds) => {
    if (!(bookingTicket == null ? void 0 : bookingTicket.initBookingContext)) return;
    await bookingTicket.initBookingContext(
      (0, import_buildDefaultLoadProductsParams.buildInitBookingContextParams)(bookingConfigParams, { bookingIds })
    );
  });
  const ensureBookingConfigForLoad = (0, import_ahooks.useMemoizedFn)(async () => {
    var _a2;
    if (!bookingTicket) return;
    const bookingIds = (0, import_buildDefaultLoadProductsParams.collectBookingIdsFromTempOrder)(((_a2 = bookingTicket.getTempOrder) == null ? void 0 : _a2.call(bookingTicket)) ?? null);
    await (0, import_buildDefaultLoadProductsParams.ensureBookingConfigForLoad)(
      bookingTicket,
      (0, import_buildDefaultLoadProductsParams.buildInitBookingContextParams)(bookingConfigParams, {
        bookingIds: bookingIds.length ? bookingIds : void 0,
        loadResources: false
      })
    );
  });
  const loadDetail = (0, import_ahooks.useMemoizedFn)(async (id) => {
    var _a2;
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    setStatus("loading");
    setError(null);
    try {
      const sales = await bookingTicket.loadSalesDetail(id);
      refreshRootSnapshot();
      if (autoInitBookingContext && bookingTicket.loadBookingResources) {
        const bookingIds = (_a2 = sales == null ? void 0 : sales.bookings) == null ? void 0 : _a2.map((b) => b == null ? void 0 : b.id).filter((bid) => typeof bid === "number" && Number.isFinite(bid));
        await bookingTicket.loadBookingResources({
          date: (0, import_dayjs.default)().format("YYYY-MM-DD"),
          bookingIds: (bookingIds == null ? void 0 : bookingIds.length) ? bookingIds : void 0
        });
      }
      setStatus("ready");
      return sales;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      setStatus("error");
      throw err;
    }
  });
  const loadDetailByRemote = (0, import_ahooks.useMemoizedFn)(async (id) => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    setStatus("loading");
    setError(null);
    try {
      const sales = await bookingTicket.loadSalesDetail({
        orderId: id,
        forceRemote: true
      });
      refreshRootSnapshot();
      setStatus("ready");
      return sales;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      setStatus("error");
      throw err;
    }
  });
  (0, import_react.useEffect)(() => {
    var _a2;
    if (!bookingTicket || !isActive) return;
    (_a2 = bookingTicket.initPeripheralsListener) == null ? void 0 : _a2.call(bookingTicket);
  }, [bookingTicket, isActive]);
  const refreshSalesDetail = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    setError(null);
    try {
      const sales = await bookingTicket.refreshSalesDetail();
      refreshRootSnapshot();
      return sales;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      throw err;
    }
  });
  const createNew = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    try {
      const tempOrder = await bookingTicket.addNewOrder();
      refreshRootSnapshot();
      setStatus("ready");
      setError(null);
      return tempOrder;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      setStatus("error");
      throw err;
    }
  });
  const restore = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    try {
      const tempOrder = await bookingTicket.restoreOrder();
      refreshRootSnapshot();
      setStatus("ready");
      setError(null);
      return tempOrder;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      setStatus("error");
      throw err;
    }
  });
  const clearCartItemsOnly = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    if (typeof bookingTicket.clearOrderCartLines !== "function") {
      throw new Error("[SalesSdk] bookingTicket.clearOrderCartLines 不可用，请升级 pisellos");
    }
    try {
      const tempOrder = await bookingTicket.clearOrderCartLines();
      refreshRootSnapshot();
      setError(null);
      return tempOrder;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      throw err;
    }
  });
  const clearCartAndReset = (0, import_ahooks.useMemoizedFn)(async () => {
    return restore();
  });
  const destroy = (0, import_ahooks.useMemoizedFn)(async () => {
    if (!bookingTicket) return;
    await bookingTicket.destroy();
    setRootSnapshot(EMPTY_ROOT_SNAPSHOT);
    setStatus("idle");
    setError(null);
  });
  const openCheckout = (0, import_ahooks.useMemoizedFn)(async () => {
    var _a2;
    if (typeof action !== "function") {
      throw new Error("[SalesSdk] appHelper.utils.action is not available.");
    }
    if (!bookingTicket) {
      throw new Error("[SalesSdk] bookingTicket 未初始化");
    }
    const canProceed = await (0, import_ensureHoldersBeforeSubmit.ensureHoldersBeforeSubmit)({
      bookingTicket,
      onMutate: refreshRootSnapshot,
      holderConfirmBridge: hostBridges.holderConfirm
    });
    if (!canProceed) {
      throw import_createHolderConfirmBridge.HOLDER_CONFIRM_CANCELLED;
    }
    const tempOrder = (_a2 = bookingTicket.getTempOrder) == null ? void 0 : _a2.call(bookingTicket);
    const orderIdFromTemp = tempOrder == null ? void 0 : tempOrder.order_id;
    return new Promise((resolve) => {
      let settled = false;
      let hasRestoredAfterPaid = false;
      action({
        type: "pisell1.handleOpenPayment",
        data: { order: { id: orderIdFromTemp }, baseSalesModuleName: (0, import_utils.getBookingTicketKey)(osKey) },
        callback: async (res = {}) => {
          var _a3;
          const paymentEvent = (0, import_payment_modal_utils.normalizePaymentModalCallbackEvent)(res);
          if (paymentEvent.type === "toast-close") {
            return;
          }
          const isPaidCheckout = paymentEvent.status === "paid" && paymentEvent.reason === "paid";
          const shouldRestoreAfterCheckout = paymentEvent.type === "modal-close" && (isPaidCheckout || paymentEvent.reason === "save-pay-later");
          if (restoreOrderAfterPaidCheckout && !hasRestoredAfterPaid && shouldRestoreAfterCheckout) {
            hasRestoredAfterPaid = true;
            await restore();
          }
          if (paymentEvent.shouldRefreshOrder || paymentEvent.shouldCloseCaller) {
            (_a3 = summaryProviderRef.current) == null ? void 0 : _a3.refreshSummary();
            refreshRootSnapshot();
          }
          const shouldResolveCheckout = paymentEvent.type === "modal-close" || paymentEvent.type === "error";
          if (!shouldResolveCheckout) return;
          if (settled) return;
          settled = true;
          resolve(paymentEvent);
        }
      });
    });
  });
  const setBookingStatus = (0, import_ahooks.useMemoizedFn)(async (status2) => {
    var _a2;
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    try {
      const data = await bookingTicket.setBookingStatus(status2);
      const tempOrder = (_a2 = bookingTicket.getTempOrder) == null ? void 0 : _a2.call(bookingTicket);
      const orderIdFromTemp = tempOrder == null ? void 0 : tempOrder.order_id;
      action({
        type: "webpos.updateLocalOrderApi",
        data: { order_id: orderIdFromTemp }
      });
      refreshRootSnapshot();
      setError(null);
      return data;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      throw err;
    }
  });
  function runTempOrderMutation(exec) {
    if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
    try {
      const result = exec(bookingTicket);
      refreshRootSnapshot();
      setError(null);
      return result;
    } catch (e) {
      const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
      setError(err);
      throw err;
    }
  }
  const setOrderNote = (0, import_ahooks.useMemoizedFn)(
    (note) => runTempOrderMutation((handle) => handle.updateTempOrderNote(note))
  );
  const setShopDiscount = (0, import_ahooks.useMemoizedFn)(
    (amount) => runTempOrderMutation((handle) => handle.updateTempOrderShopDiscount(amount))
  );
  const setContactsInfo = (0, import_ahooks.useMemoizedFn)(
    (contactsInfo) => runTempOrderMutation((handle) => handle.updateTempOrderContactsInfo(contactsInfo))
  );
  const activateCamera = (0, import_ahooks.useMemoizedFn)((data) => {
    bookingTicket == null ? void 0 : bookingTicket.activateCamera(data);
  });
  const getDiscountList = (0, import_ahooks.useMemoizedFn)(() => {
    var _a2;
    if (!bookingTicket) return [];
    return cloneArray((_a2 = bookingTicket.getDiscountList) == null ? void 0 : _a2.call(bookingTicket), EMPTY_DISCOUNT_LIST);
  });
  const scanPromotionCode = (0, import_ahooks.useMemoizedFn)(
    async (code, customerId) => {
      if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
      try {
        const result = await bookingTicket.scanPromotionCode(code, customerId);
        if (result == null ? void 0 : result.isAvailable) {
          refreshRootSnapshot();
        }
        setError(null);
        return result;
      } catch (e) {
        const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
        setError(err);
        throw err;
      }
    }
  );
  const setDiscountSelected = (0, import_ahooks.useMemoizedFn)(
    async (params) => {
      if (!bookingTicket) throw new Error("[SalesSdk] bookingTicket 未初始化");
      try {
        await bookingTicket.setDiscountSelected(params);
        refreshRootSnapshot();
        setError(null);
      } catch (e) {
        const err = e instanceof Error ? e : new Error(String((e == null ? void 0 : e.message) ?? e));
        setError(err);
        throw err;
      }
    }
  );
  const builtInUiHosts = (0, import_react.useMemo)(() => {
    const normalHost = (0, import_createOpenNormalProductDetailHost.createOpenNormalProductDetailHost)(hostBridges.normalProductDetail);
    const openProductDetail = legacyOpenProductDetail ? (0, import_createCompositeOpenProductDetailHost.createCompositeOpenProductDetailHost)({
      ...legacyOpenProductDetail,
      normalHost
    }) : normalHost;
    return {
      openProductDetail,
      openBookingEdit: (0, import_createOpenBookingEditHost.createOpenBookingEditHost)(hostBridges.bookingEdit),
      openMultiDaySelect: (0, import_createOpenMultiDaySelectHost.createOpenMultiDaySelectHost)(hostBridges.multiDay),
      openHolderSelect: (0, import_createOpenHolderSelectHost.createOpenHolderSelectHost)(hostBridges.holder)
    };
  }, [hostBridges, legacyOpenProductDetail]);
  const uiHostsValue = (0, import_react.useMemo)(
    () => ({
      ...builtInUiHosts,
      ...uiHosts ?? {}
    }),
    [
      builtInUiHosts,
      uiHosts == null ? void 0 : uiHosts.openProductDetail,
      uiHosts == null ? void 0 : uiHosts.openBookingEdit,
      uiHosts == null ? void 0 : uiHosts.openMultiDaySelect,
      uiHosts == null ? void 0 : uiHosts.openHolderSelect
    ]
  );
  const value = (0, import_react.useMemo)(
    () => {
      var _a2;
      return {
        bookingTicket,
        osKey,
        status,
        error,
        isReady: status === "ready",
        shop_full_order_number: ((_a2 = rootSnapshot.tempOrder) == null ? void 0 : _a2.shop_full_order_number) || "",
        tempOrder: rootSnapshot.tempOrder,
        salesDetail: rootSnapshot.salesDetail,
        loadDetail,
        loadDetailByRemote,
        refreshSalesDetail,
        createNew,
        restore,
        clearCartItemsOnly,
        clearCartAndReset,
        destroy,
        setBookingStatus,
        setOrderNote,
        setShopDiscount,
        setContactsInfo,
        activateCamera,
        openCheckout,
        getDiscountList,
        scanPromotionCode,
        setDiscountSelected,
        ensureBookingConfigForLoad,
        defaultProductLoadParams,
        bookingConfigParams
      };
    },
    // actions 引用稳定（useMemoizedFn）；不进 deps 也安全，但显式列出便于阅读
    [
      bookingTicket,
      osKey,
      status,
      error,
      rootSnapshot,
      defaultProductLoadParams,
      bookingConfigParams,
      loadDetail,
      loadDetailByRemote,
      refreshSalesDetail,
      createNew,
      restore,
      clearCartItemsOnly,
      clearCartAndReset,
      destroy,
      setBookingStatus,
      setOrderNote,
      setShopDiscount,
      setContactsInfo,
      activateCamera,
      openCheckout,
      getDiscountList,
      scanPromotionCode,
      setDiscountSelected,
      ensureBookingConfigForLoad
    ]
  );
  return /* @__PURE__ */ import_react.default.createElement(import_SalesSdkContext.SalesSdkContext.Provider, { value }, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkHostBridgesContext.SalesSdkHostBridgesContext.Provider, { value: hostBridges }, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkUIHostsContext.SalesSdkUIHostsContext.Provider, { value: uiHostsValue }, /* @__PURE__ */ import_react.default.createElement(SalesSdkRootRefreshContext.Provider, { value: refreshRootSnapshot }, /* @__PURE__ */ import_react.default.createElement(SalesSdkPrepareOrderSwitchContext.Provider, { value: prepareOrderSwitch }, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkHolderContext.SalesSdkHolderProvider, null, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkProductContext.SalesSdkProductProvider, null, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkSummaryContext.SalesSdkSummaryProvider, { ref: summaryProviderRef }, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkCartContext.SalesSdkCartProvider, null, /* @__PURE__ */ import_react.default.createElement(
    import_SalesSdkGlobalScanSubscriber.SalesSdkGlobalScanSubscriber,
    {
      enabled: enableGlobalScanListener,
      isActive,
      businessCode
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    SalesSdkBootstrap,
    {
      autoRestoreOnInit,
      autoBootstrap,
      autoInitBookingContext,
      orderId,
      initBookingContext
    }
  ), /* @__PURE__ */ import_react.default.createElement(import_SalesSdkCustomerContext.SalesSdkCustomerProvider, null, /* @__PURE__ */ import_react.default.createElement(import_BookingEditHostRenderer.BookingEditHostRenderer, null), /* @__PURE__ */ import_react.default.createElement(import_MultiDayHostRenderer.MultiDayHostRenderer, null), /* @__PURE__ */ import_react.default.createElement(import_HolderHostRenderer.HolderHostRenderer, null), /* @__PURE__ */ import_react.default.createElement(import_ConfirmHolderHostRenderer.ConfirmHolderHostRenderer, null), /* @__PURE__ */ import_react.default.createElement(import_NormalProductDetailHostRenderer.NormalProductDetailHostRenderer, null), /* @__PURE__ */ import_react.default.createElement(import_GiftSelectHostRenderer.GiftSelectHostRenderer, null), children))))))))));
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SalesSdkPrepareOrderSwitchContext,
  SalesSdkProvider,
  SalesSdkRootRefreshContext
});
