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/venueBooking/context.tsx
var context_exports = {};
__export(context_exports, {
  VenueBookingProvider: () => VenueBookingProvider,
  useVenueBookingContext: () => useVenueBookingContext
});
module.exports = __toCommonJS(context_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_useEngineContext = require("../../hooks/useEngineContext");
var import_useEngineContext2 = __toESM(require("../../hooks/useEngineContext"));
var import_hooks = require("./hooks");
var import_utils2 = require("./utils");
var import_buildCartHolderParams = require("../../utils/buildCartHolderParams");
var VenueBookingContext = (0, import_react.createContext)(void 0);
var INITIAL_VIEW_MODEL = {
  dateSummary: [],
  timeSlotGrid: null,
  cartItems: [],
  summary: {},
  note: "",
  contactsInfo: [],
  venueProducts: [],
  addonProductList: []
};
var EMPTY_UTILS = {};
function getWeekRange(anchor) {
  const days = (0, import_utils2.getWeekDays)(anchor);
  return {
    startDate: (0, import_utils2.formatDateKey)(days[0]),
    endDate: (0, import_utils2.formatDateKey)(days[days.length - 1])
  };
}
function clampRangeToToday(startDate, endDate) {
  const todayKey = (0, import_utils2.formatDateKey)((0, import_dayjs.default)());
  if (endDate < todayKey) return null;
  return {
    startDate: startDate < todayKey ? todayKey : startDate,
    endDate
  };
}
function getSubmitOrderErrorMessage(error) {
  const firstFailure = Array.isArray(error == null ? void 0 : error.failures) ? error.failures[0] : null;
  const failureTips = String((firstFailure == null ? void 0 : firstFailure.validationMessage) || "").trim();
  if (failureTips) return failureTips;
  const message2 = String((error == null ? void 0 : error.message) || "").trim();
  if (message2) return message2;
  return String(import_utils.locales.getText("pisell2.venue.error.submit.order") || "提交订单失败，请稍后重试。");
}
function findNearestAvailableDate(params) {
  const { summary, preferredDate } = params;
  if (!Array.isArray(summary) || !summary.length) return null;
  const availableDates = summary.filter((item) => (item == null ? void 0 : item.status) === "available" || (item == null ? void 0 : item.status) === "few_left").map((item) => (0, import_dayjs.default)(String((item == null ? void 0 : item.date) || ""))).filter((date) => date.isValid());
  if (!availableDates.length) return null;
  const normalizedPreferred = preferredDate.startOf("day");
  const futureDates = availableDates.filter((date) => !date.isBefore(normalizedPreferred, "day")).sort((a, b) => a.valueOf() - b.valueOf());
  if (futureDates.length) return futureDates[0];
  return availableDates.sort((a, b) => b.valueOf() - a.valueOf())[0];
}
function VenueBookingProvider({ entryContext, children }) {
  var _a, _b, _c;
  const pisellOS = (0, import_useEngineContext.usePisellOS)();
  const venueBookingModule = (0, import_hooks.useVenueBookingModule)();
  const [currentStep, setCurrentStep] = (0, import_react.useState)("select-venue");
  const hydratedRef = (0, import_react.useRef)(false);
  const [addonsResolved, setAddonsResolved] = (0, import_react.useState)(false);
  const [viewModel, setViewModel] = (0, import_react.useState)(INITIAL_VIEW_MODEL);
  const stepList = (0, import_react.useMemo)(() => {
    var _a2;
    const hasAddons = (((_a2 = viewModel.addonProductList) == null ? void 0 : _a2.length) || 0) > 0;
    return hasAddons ? ["select-venue", "addons", "checkout"] : ["select-venue", "checkout"];
  }, [(_a = viewModel.addonProductList) == null ? void 0 : _a.length]);
  const [isLoading, setIsLoading] = (0, import_react.useState)(true);
  const [isWeekLoading, setIsWeekLoading] = (0, import_react.useState)(true);
  const [isGridTransition, setIsGridTransition] = (0, import_react.useState)(true);
  const isGridLoading = isWeekLoading || isGridTransition;
  const [anchorDate, setAnchorDate] = (0, import_react.useState)((0, import_dayjs.default)());
  const [filter, setFilter] = (0, import_react.useState)("ALL");
  const [search, setSearch] = (0, import_react.useState)("");
  const [limitMessage, setLimitMessage] = (0, import_react.useState)("");
  const [mobileCartOpen, setMobileCartOpen] = (0, import_react.useState)(false);
  const [monthPickerOpen, setMonthPickerOpen] = (0, import_react.useState)(false);
  const [monthCursor, setMonthCursor] = (0, import_react.useState)((0, import_dayjs.default)().startOf("month"));
  const { isLogin, openLoginModal } = (0, import_hooks.useVenueBookingLogin)();
  const engineContext = (0, import_useEngineContext2.default)();
  const utils = ((_b = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _b.utils) || EMPTY_UTILS;
  const [discountList, setDiscountList] = (0, import_react.useState)([]);
  const [isAgreeDepositPolicy, setIsAgreeDepositPolicy] = (0, import_react.useState)(false);
  const [cartValidation, setCartValidation] = (0, import_react.useState)({ passed: null, failures: [] });
  const [footerActionText, setFooterActionText] = (0, import_react.useState)(
    String(import_utils.locales.getText("pisell2.venue.action.next.addons") || "")
  );
  const [isSubmittingOrder, setIsSubmittingOrder] = (0, import_react.useState)(false);
  const anchorDateRef = (0, import_react.useRef)(anchorDate);
  anchorDateRef.current = anchorDate;
  const bootstrappedRef = (0, import_react.useRef)(false);
  const canNext = (0, import_react.useMemo)(() => {
    const allSelected = (0, import_hooks.getAllSelectedSlots)(venueBookingModule);
    if (Array.isArray(allSelected) && allSelected.length > 0) return true;
    return viewModel.cartItems.length > 0;
  }, [venueBookingModule, viewModel]);
  (0, import_react.useEffect)(() => {
    if (!limitMessage) return void 0;
    const timer = window.setTimeout(() => setLimitMessage(""), 3800);
    return () => window.clearTimeout(timer);
  }, [limitMessage]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2;
    if (hydratedRef.current || !venueBookingModule) return;
    hydratedRef.current = true;
    const pending = (_a2 = venueBookingModule.getUIState) == null ? void 0 : _a2.call(venueBookingModule, "pendingStep");
    if (pending) {
      (_b2 = venueBookingModule.deleteUIState) == null ? void 0 : _b2.call(venueBookingModule, "pendingStep");
      setCurrentStep(pending);
      return;
    }
    const cached = (_c2 = venueBookingModule.getUIState) == null ? void 0 : _c2.call(venueBookingModule, "step");
    if (cached) setCurrentStep(cached);
  }, [venueBookingModule]);
  (0, import_react.useEffect)(() => {
    var _a2;
    if (!hydratedRef.current || !venueBookingModule) return;
    (_a2 = venueBookingModule.setUIState) == null ? void 0 : _a2.call(venueBookingModule, "step", currentStep);
  }, [currentStep, venueBookingModule]);
  (0, import_react.useEffect)(() => {
    if (!hydratedRef.current || !addonsResolved) return;
    if (!stepList.includes(currentStep)) setCurrentStep(stepList[0]);
  }, [stepList, currentStep, addonsResolved]);
  const refreshViewModel = (0, import_react.useCallback)(async (extraFields) => {
    if (venueBookingModule && typeof venueBookingModule.getSummary === "function") {
      try {
        await venueBookingModule.getSummary();
      } catch (error) {
        console.warn("[venueBooking] getSummary failed during refreshViewModel", error);
      }
    }
    const moduleData = (0, import_hooks.createVenueBookingViewModel)(venueBookingModule);
    setViewModel((prev) => ({ ...prev, ...moduleData, ...extraFields || {} }));
    if (venueBookingModule && typeof venueBookingModule.getDiscountList === "function") {
      const latestDiscounts = venueBookingModule.getDiscountList() || [];
      setDiscountList(latestDiscounts);
    }
  }, [venueBookingModule]);
  const refreshTimeSlotGrid = (0, import_react.useCallback)((date) => {
    if (!venueBookingModule) return;
    const targetDate = date || (0, import_utils2.formatDateKey)(anchorDateRef.current);
    const grid = (0, import_hooks.getTimeSlotGrid)(venueBookingModule, targetDate);
    setViewModel((prev) => ({ ...prev, timeSlotGrid: grid }));
  }, [venueBookingModule]);
  const fetchWeekData = (0, import_react.useCallback)(async (startDate, endDate) => {
    if (!venueBookingModule) return;
    setIsWeekLoading(true);
    try {
      const clamped = clampRangeToToday(startDate, endDate);
      let summary = [];
      if (clamped) {
        await (0, import_hooks.fetchResourceAvailability)(venueBookingModule, clamped.startDate, clamped.endDate);
        const raw = (0, import_hooks.getDateRangeSummary)(venueBookingModule, clamped.startDate, clamped.endDate);
        summary = Array.isArray(raw) ? raw : [];
      }
      const currentDateKey = (0, import_utils2.formatDateKey)(anchorDateRef.current);
      const grid = (0, import_hooks.getTimeSlotGrid)(venueBookingModule, currentDateKey);
      setViewModel((prev) => ({
        ...prev,
        dateSummary: summary,
        timeSlotGrid: grid
      }));
    } finally {
      setIsWeekLoading(false);
    }
  }, [venueBookingModule]);
  const goToNearestAvailableDate = (0, import_react.useCallback)(async (fromDate) => {
    if (!venueBookingModule) return;
    setIsWeekLoading(true);
    try {
      const MAX_FORWARD_WEEKS = 8;
      let fallbackSummary = [];
      for (let weekOffset = 0; weekOffset <= MAX_FORWARD_WEEKS; weekOffset++) {
        const probeDate = fromDate.add(weekOffset * 7, "day");
        const { startDate, endDate } = getWeekRange(probeDate);
        const clamped = clampRangeToToday(startDate, endDate);
        if (!clamped) continue;
        await (0, import_hooks.fetchResourceAvailability)(venueBookingModule, clamped.startDate, clamped.endDate);
        const weekSummary = (0, import_hooks.getDateRangeSummary)(venueBookingModule, clamped.startDate, clamped.endDate);
        if (weekOffset === 0) fallbackSummary = Array.isArray(weekSummary) ? weekSummary : [];
        const candidateDate = findNearestAvailableDate({
          summary: Array.isArray(weekSummary) ? weekSummary : [],
          preferredDate: weekOffset === 0 ? fromDate : probeDate.startOf("week")
        });
        if (!candidateDate) continue;
        setAnchorDate(candidateDate);
        setMonthCursor(candidateDate.startOf("month"));
        const grid = (0, import_hooks.getTimeSlotGrid)(venueBookingModule, (0, import_utils2.formatDateKey)(candidateDate));
        setViewModel((prev) => ({
          ...prev,
          dateSummary: Array.isArray(weekSummary) ? weekSummary : [],
          timeSlotGrid: grid
        }));
        return;
      }
      const fallbackGrid = (0, import_hooks.getTimeSlotGrid)(venueBookingModule, (0, import_utils2.formatDateKey)(fromDate));
      setAnchorDate(fromDate);
      setMonthCursor(fromDate.startOf("month"));
      setViewModel((prev) => ({
        ...prev,
        dateSummary: fallbackSummary,
        timeSlotGrid: fallbackGrid
      }));
    } finally {
      setIsWeekLoading(false);
    }
  }, [venueBookingModule]);
  const toggleSlot = (0, import_react.useCallback)(async (resourceId, productId, slot) => {
    if (!venueBookingModule || !slot.price) return;
    try {
      await (0, import_hooks.toggleSlotAction)(venueBookingModule, {
        resourceId,
        productId,
        startTime: slot.startTime,
        endTime: slot.endTime,
        price: slot.price
      });
      refreshTimeSlotGrid();
      await refreshViewModel();
    } catch (error) {
      console.warn("[venueBooking] toggleSlot failed", error);
    }
  }, [venueBookingModule, refreshTimeSlotGrid, refreshViewModel]);
  const updateOrderNote = (0, import_react.useCallback)(async (note) => {
    await (0, import_hooks.safeRunModuleAction)(venueBookingModule, "updateTempOrderNote", note);
    await refreshViewModel();
  }, [venueBookingModule, refreshViewModel]);
  const runModuleAction = (0, import_react.useCallback)(async (actionName, ...args) => {
    return (0, import_hooks.safeRunModuleAction)(venueBookingModule, actionName, ...args);
  }, [venueBookingModule]);
  const syncCustomerLoginToModule = (0, import_react.useCallback)(async () => {
    var _a2, _b2, _c2, _d;
    try {
      const hasToken = !!((_b2 = (_a2 = utils == null ? void 0 : utils.token) == null ? void 0 : _a2.get) == null ? void 0 : _b2.call(_a2));
      if (!hasToken) return;
      const rawCustomer = (_d = (_c2 = utils == null ? void 0 : utils.storage) == null ? void 0 : _c2.get) == null ? void 0 : _d.call(_c2, "customer");
      const customer = typeof rawCustomer === "string" ? JSON.parse(rawCustomer || "{}") : rawCustomer || {};
      const customerId = customer == null ? void 0 : customer.id;
      if (!customerId) return;
      await runModuleAction("onCustomerLogin", { customerId });
    } catch (error) {
      console.warn("[venueBooking] syncCustomerLoginToModule failed", error);
    }
  }, [utils, runModuleAction]);
  const goToStep = (0, import_react.useCallback)((step) => {
    if (!stepList.includes(step)) return;
    setCurrentStep(step);
  }, [stepList]);
  const nextStep = (0, import_react.useCallback)(() => {
    setCurrentStep((prev) => {
      const idx = stepList.findIndex((s) => s === prev);
      if (idx < 0 || idx >= stepList.length - 1) return prev;
      return stepList[idx + 1];
    });
  }, [stepList]);
  const prevStep = (0, import_react.useCallback)(() => {
    setCurrentStep((prev) => {
      const idx = stepList.findIndex((s) => s === prev);
      if (idx <= 0) return prev;
      return stepList[idx - 1];
    });
  }, [stepList]);
  const handleLoginSuccess = (0, import_react.useCallback)(async () => {
    var _a2;
    try {
      await syncCustomerLoginToModule();
      const list = ((_a2 = venueBookingModule == null ? void 0 : venueBookingModule.getDiscountList) == null ? void 0 : _a2.call(venueBookingModule)) || [];
      setDiscountList(list);
      await refreshViewModel();
    } catch (error) {
      console.warn("[venueBooking] handleLoginSuccess failed", error);
    }
  }, [syncCustomerLoginToModule, venueBookingModule, refreshViewModel]);
  const syncCustomerLoginRef = (0, import_react.useRef)(syncCustomerLoginToModule);
  syncCustomerLoginRef.current = syncCustomerLoginToModule;
  const goToNearestAvailableDateRef = (0, import_react.useRef)(goToNearestAvailableDate);
  goToNearestAvailableDateRef.current = goToNearestAvailableDate;
  const handleLoginSuccessRef = (0, import_react.useRef)(handleLoginSuccess);
  handleLoginSuccessRef.current = handleLoginSuccess;
  const submitOrder = (0, import_react.useCallback)(async () => {
    var _a2, _b2, _c2;
    if (isSubmittingOrder) return;
    try {
      setIsSubmittingOrder(true);
      const result = await (0, import_hooks.safeRunModuleAction)(venueBookingModule, "submitOrder");
      await refreshViewModel();
      const orderId = ((_a2 = result == null ? void 0 : result.data) == null ? void 0 : _a2.order_id) || (result == null ? void 0 : result.order_id) || "";
      const totalAmount = (_b2 = viewModel == null ? void 0 : viewModel.summary) == null ? void 0 : _b2.total_amount;
      import_antd.message.success({
        content: String(import_utils.locales.getText("pisell2.venue.order.submit.success") || "订单已提交"),
        duration: 2
      });
      if (!orderId) {
        console.warn("[venueBooking] submitOrder succeeded but order_id is missing", result);
        return;
      }
      const otherParams = (0, import_hooks.getOtherParams)(venueBookingModule);
      if (typeof (utils == null ? void 0 : utils.action) === "function" && (otherParams == null ? void 0 : otherParams.openData["sale.require_payment_on_submit"])) {
        if (totalAmount === 0 || ((_c2 = otherParams == null ? void 0 : otherParams.openData["checkout.checkout_options"]) == null ? void 0 : _c2.length) === 0) {
          return location.replace(`/payment-finish/success?amount=${totalAmount}&order_id=${orderId}`);
        }
        utils.action({
          type: "pisell1.payment",
          data: {
            order_id: orderId,
            total_amount: totalAmount
          },
          callback: (e) => {
          }
        });
      } else {
        location.replace(`/order/details?id=${orderId}`);
      }
    } catch (error) {
      import_antd.message.error({
        content: getSubmitOrderErrorMessage(error),
        duration: 2
      });
      console.warn("[venueBooking] submitOrder failed", error);
    } finally {
      setIsSubmittingOrder(false);
    }
  }, [isSubmittingOrder, venueBookingModule, refreshViewModel, utils, (_c = viewModel == null ? void 0 : viewModel.summary) == null ? void 0 : _c.total_amount]);
  const handleSubmitOrder = (0, import_react.useCallback)(async () => {
    var _a2;
    if (isLogin) {
      await submitOrder();
      return;
    }
    (_a2 = venueBookingModule == null ? void 0 : venueBookingModule.setUIState) == null ? void 0 : _a2.call(venueBookingModule, "pendingStep", "checkout");
    openLoginModal({
      callback: (status) => {
        var _a3;
        if (status !== "success") return;
        (_a3 = venueBookingModule == null ? void 0 : venueBookingModule.deleteUIState) == null ? void 0 : _a3.call(venueBookingModule, "pendingStep");
        handleLoginSuccess().then(() => {
          void submitOrder();
        });
      }
    });
  }, [isLogin, openLoginModal, handleLoginSuccess, submitOrder, venueBookingModule]);
  const proceedToCheckout = (0, import_react.useCallback)(() => {
    var _a2;
    if (!isLogin) {
      (_a2 = venueBookingModule == null ? void 0 : venueBookingModule.setUIState) == null ? void 0 : _a2.call(venueBookingModule, "pendingStep", "checkout");
      openLoginModal({
        callback: (status) => {
          var _a3;
          if (status === "success") {
            (_a3 = venueBookingModule == null ? void 0 : venueBookingModule.deleteUIState) == null ? void 0 : _a3.call(venueBookingModule, "pendingStep");
            handleLoginSuccess().then(() => goToStep("checkout"));
          }
        }
      });
      return;
    }
    if (currentStep === "addons") {
      const { hasError } = (0, import_buildCartHolderParams.validateRequiredCartHolders)({
        items: viewModel.cartItems,
        getHolderConfig: import_buildCartHolderParams.getVenueCartHolderConfig
      });
      if (hasError) {
        return;
      }
    }
    goToStep("checkout");
  }, [isLogin, openLoginModal, handleLoginSuccess, goToStep, venueBookingModule, currentStep, viewModel.cartItems, import_buildCartHolderParams.getVenueCartHolderConfig]);
  const handlePrimaryAction = (0, import_react.useCallback)(() => {
    var _a2, _b2;
    if (currentStep === "select-venue") {
      if (!canNext) {
        import_antd.message.warning({
          content: String(import_utils.locales.getText("pisell2.venue.cart.choose.first") || "请先选择场地。"),
          duration: 2
        });
        return;
      }
      if (stepList[1] === "checkout") {
        proceedToCheckout();
        return;
      }
      goToStep("addons");
      return;
    }
    if (currentStep === "addons") {
      proceedToCheckout();
      return;
    }
    const deposit = (_a2 = viewModel.summary) == null ? void 0 : _a2.deposit;
    if ((deposit == null ? void 0 : deposit.hasDeposit) && ((_b2 = deposit == null ? void 0 : deposit.deposit_policy_data) == null ? void 0 : _b2.length) > 0 && !isAgreeDepositPolicy) {
      import_antd.message.warning(String(import_utils.locales.getText("pisell2.appointment.deposit.agree.policy") || "请先同意定金协议"));
      return;
    }
    void handleSubmitOrder();
  }, [currentStep, canNext, isAgreeDepositPolicy, viewModel.summary, stepList, goToStep, handleSubmitOrder, proceedToCheckout]);
  (0, import_react.useEffect)(() => {
    var _a2;
    const pubsub = utils == null ? void 0 : utils.pubsub;
    if (!pubsub) return;
    const onGlobalLoginSuccess = async (res) => {
      if (res === "success" || (res == null ? void 0 : res.status) === "success") {
        await handleLoginSuccessRef.current();
      }
    };
    (_a2 = pubsub.subscribe) == null ? void 0 : _a2.call(pubsub, "pisell1.login.success", onGlobalLoginSuccess);
    return () => {
      var _a3;
      (_a3 = pubsub.unsubscribe) == null ? void 0 : _a3.call(pubsub, "pisell1.login.success", onGlobalLoginSuccess);
    };
  }, [utils == null ? void 0 : utils.pubsub]);
  (0, import_react.useEffect)(() => {
    if (!venueBookingModule) return;
    setIsGridTransition(true);
    refreshTimeSlotGrid((0, import_utils2.formatDateKey)(anchorDate));
    const timer = window.setTimeout(() => setIsGridTransition(false), 220);
    return () => window.clearTimeout(timer);
  }, [anchorDate, venueBookingModule, refreshTimeSlotGrid]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2;
    if (!venueBookingModule) return;
    let cancelled = false;
    const syncCartValidation = async () => {
      try {
        const value2 = await (0, import_hooks.safeRunModuleAction)(venueBookingModule, "getCartValidation");
        if (!cancelled) {
          setCartValidation({
            passed: typeof (value2 == null ? void 0 : value2.passed) === "boolean" || (value2 == null ? void 0 : value2.passed) === null ? value2.passed : null,
            failures: Array.isArray(value2 == null ? void 0 : value2.failures) ? value2.failures : []
          });
        }
      } catch {
        if (!cancelled) setCartValidation({ passed: null, failures: [] });
      }
    };
    const onCartValidationChanged = (payload) => {
      const nextValue = payload == null ? void 0 : payload.cartValidation;
      setCartValidation({
        passed: typeof (nextValue == null ? void 0 : nextValue.passed) === "boolean" || (nextValue == null ? void 0 : nextValue.passed) === null ? nextValue.passed : typeof (payload == null ? void 0 : payload.cartValidationPassed) === "boolean" ? payload.cartValidationPassed : null,
        failures: Array.isArray(nextValue == null ? void 0 : nextValue.failures) ? nextValue.failures : []
      });
    };
    void syncCartValidation();
    (_b2 = (_a2 = pisellOS == null ? void 0 : pisellOS.effects) == null ? void 0 : _a2.on) == null ? void 0 : _b2.call(_a2, "venueBooking:onCartValidationChanged", onCartValidationChanged);
    return () => {
      var _a3, _b3;
      cancelled = true;
      (_b3 = (_a3 = pisellOS == null ? void 0 : pisellOS.effects) == null ? void 0 : _a3.off) == null ? void 0 : _b3.call(_a3, "venueBooking:onCartValidationChanged", onCartValidationChanged);
    };
  }, [pisellOS, venueBookingModule]);
  (0, import_react.useEffect)(() => {
    if (bootstrappedRef.current || !venueBookingModule) return;
    bootstrappedRef.current = true;
    let unmounted = false;
    const bootstrap = async () => {
      try {
        setIsLoading(true);
        await syncCustomerLoginRef.current();
        await (0, import_hooks.loadVenueProducts)(venueBookingModule, import_hooks.VENUE_PRODUCT_IDS);
        const venueProducts = typeof (venueBookingModule == null ? void 0 : venueBookingModule.getVenueProducts) === "function" ? venueBookingModule.getVenueProducts() : [];
        await goToNearestAvailableDateRef.current(anchorDateRef.current);
        const moduleData = (0, import_hooks.createVenueBookingViewModel)(venueBookingModule);
        if (!unmounted) {
          setViewModel((prev) => ({
            ...prev,
            cartItems: Array.isArray(moduleData.cartItems) ? moduleData.cartItems : [],
            summary: moduleData.summary || {},
            note: moduleData.note || "",
            contactsInfo: Array.isArray(moduleData.contactsInfo) ? moduleData.contactsInfo : [],
            venueProducts: Array.isArray(venueProducts) ? venueProducts : []
          }));
          setIsLoading(false);
          if (typeof (venueBookingModule == null ? void 0 : venueBookingModule.getProductList) === "function") {
            venueBookingModule.getProductList().then((res) => {
              if (!unmounted && Array.isArray(res)) {
                setViewModel((prev) => ({ ...prev, addonProductList: res }));
              }
            }).catch((err) => {
              console.warn("[venueBooking] prefetch getProductList failed", err);
            }).finally(() => {
              if (!unmounted) setAddonsResolved(true);
            });
          } else {
            setAddonsResolved(true);
          }
        }
      } catch (error) {
        console.warn("[venueBooking] bootstrap failed", error);
        if (!unmounted) setIsLoading(false);
      }
    };
    bootstrap();
    return () => {
      unmounted = true;
    };
  }, [venueBookingModule]);
  const value = (0, import_react.useMemo)(() => ({
    venueBookingModule,
    currentStep,
    stepList,
    viewModel,
    anchorDate,
    filter,
    search,
    isLoading,
    isWeekLoading,
    isGridLoading,
    limitMessage,
    mobileCartOpen,
    monthPickerOpen,
    monthCursor,
    canNext,
    cartValidation,
    footerActionText,
    isSubmittingOrder,
    isLogin,
    openLoginModal,
    discountList,
    isAgreeDepositPolicy,
    setIsAgreeDepositPolicy,
    goToStep,
    nextStep,
    prevStep,
    setAnchorDate,
    setFilter,
    setSearch,
    setLimitMessage,
    setMobileCartOpen,
    setMonthPickerOpen,
    setMonthCursor,
    setFooterActionText,
    toggleSlot,
    refreshViewModel,
    fetchWeekData,
    goToNearestAvailableDate,
    refreshTimeSlotGrid,
    runModuleAction,
    updateOrderNote,
    handlePrimaryAction,
    handleSubmitOrder
  }), [
    venueBookingModule,
    currentStep,
    viewModel,
    anchorDate,
    filter,
    search,
    isLoading,
    isWeekLoading,
    isGridLoading,
    limitMessage,
    mobileCartOpen,
    monthPickerOpen,
    monthCursor,
    canNext,
    cartValidation,
    footerActionText,
    isSubmittingOrder,
    isLogin,
    openLoginModal,
    discountList,
    toggleSlot,
    refreshViewModel,
    fetchWeekData,
    goToNearestAvailableDate,
    refreshTimeSlotGrid,
    runModuleAction,
    updateOrderNote,
    handlePrimaryAction,
    handleSubmitOrder,
    goToStep,
    nextStep,
    prevStep
  ]);
  return /* @__PURE__ */ import_react.default.createElement(VenueBookingContext.Provider, { value }, children);
}
function useVenueBookingContext() {
  const context = (0, import_react.useContext)(VenueBookingContext);
  if (context) return context;
  throw new Error("useVenueBookingContext must be used within VenueBookingProvider");
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  VenueBookingProvider,
  useVenueBookingContext
});
