const require_runtime = require("../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../hooks/useEngineContext.js");
const require_hooks = require("./hooks.js");
const require_utils = require("./utils.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
//#region src/components/venueBooking/context.tsx
/**
* venueBooking 全局状态管理
* 集中管理步骤、场地选择、PisellOS venueBooking 模块数据等状态
*/
const VenueBookingContext = (0, react.createContext)(void 0);
/** 初始视图模型：所有数据从 OS 模块获取，初始为空 */
const INITIAL_VIEW_MODEL = {
	dateSummary: [],
	timeSlotGrid: null,
	cartItems: [],
	summary: {},
	note: "",
	contactsInfo: [],
	venueProducts: [],
	addonProductList: []
};
/**
* 宿主 engineContext.appHelper.utils 缺失时的稳定兜底对象。
* 必须为模块级常量，避免在 Provider 内用 `|| {}` 字面量导致每次 render 产生新引用，
* 进而让依赖它的 useCallback / useEffect 反复失效，拖入重渲染循环。
*/
const EMPTY_UTILS = {};
/**
* 计算 anchorDate 所在周的起止日期
*/
function getWeekRange(anchor) {
	const days = require_utils.getWeekDays(anchor);
	return {
		startDate: require_utils.formatDateKey(days[0]),
		endDate: require_utils.formatDateKey(days[days.length - 1])
	};
}
/**
* 把 startDate 夹紧到今天：避免把已过去的日期传给 OS。
* 若整段范围都已过去（endDate < 今天），返回 null 表示该段不需要请求。
*/
function clampRangeToToday(startDate, endDate) {
	const todayKey = require_utils.formatDateKey((0, dayjs.default)());
	if (endDate < todayKey) return null;
	return {
		startDate: startDate < todayKey ? todayKey : startDate,
		endDate
	};
}
/**
* 从 submitOrder 异常中提取可读错误文案（优先规则校验提示）
*/
function getSubmitOrderErrorMessage(error) {
	const firstFailure = Array.isArray(error === null || error === void 0 ? void 0 : error.failures) ? error.failures[0] : null;
	const failureTips = String((firstFailure === null || firstFailure === void 0 ? void 0 : firstFailure.validationMessage) || "").trim();
	if (failureTips) return failureTips;
	const message = String((error === null || error === void 0 ? void 0 : error.message) || "").trim();
	if (message) return message;
	return String(_pisell_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 || item === void 0 ? void 0 : item.status) === "available" || (item === null || item === void 0 ? void 0 : item.status) === "few_left").map((item) => (0, dayjs.default)(String((item === null || item === void 0 ? 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];
}
/**
* VenueBookingProvider -- 场地预订全局 Context
* 管理步骤导航、场地选择状态、OS 模块集成
*/
function VenueBookingProvider({ entryContext, children }) {
	var _viewModel$addonProdu2, _engineContext$appHel, _viewModel$summary2;
	const pisellOS = require_useEngineContext.usePisellOS();
	const venueBookingModule = require_hooks.useVenueBookingModule();
	const [currentStep, setCurrentStep] = (0, react.useState)("select-venue");
	/**
	* 步骤状态是否已完成首屏 hydrate：
	*   - 首次 venueBookingModule 就绪时，从 OS UI 缓存里读取 pendingStep / step
	*   - 只做一次，避免 module 引用更新时重复覆盖用户真实的步骤操作
	*/
	const hydratedRef = (0, react.useRef)(false);
	/**
	* 附加商品列表是否已至少 resolve 过一次。
	* bootstrap 里对 getProductList() 是非阻塞预拉取，`addonProductList` 一开始是空数组，
	* stepList 也因此先呈现为 2 步。若直接用 stepList 校验 hydrated step，会把缓存里
	* 合法的 'addons' 误判为非法。所以 stepList 校验必须等到本标记翻转之后。
	* 用 state 而非 ref：保证翻转时触发 effect 重跑（即便 stepList 没变化）
	*/
	const [addonsResolved, setAddonsResolved] = (0, react.useState)(false);
	const [viewModel, setViewModel] = (0, react.useState)(INITIAL_VIEW_MODEL);
	/**
	* 步骤列表：当 addonProductList 为空时跳过 addons 步骤。
	* - 有附加商品：select-venue → addons → checkout（3 步）
	* - 无附加商品：select-venue → checkout（2 步）
	*/
	const stepList = (0, react.useMemo)(() => {
		var _viewModel$addonProdu;
		return (((_viewModel$addonProdu = viewModel.addonProductList) === null || _viewModel$addonProdu === void 0 ? void 0 : _viewModel$addonProdu.length) || 0) > 0 ? [
			"select-venue",
			"addons",
			"checkout"
		] : ["select-venue", "checkout"];
	}, [(_viewModel$addonProdu2 = viewModel.addonProductList) === null || _viewModel$addonProdu2 === void 0 ? void 0 : _viewModel$addonProdu2.length]);
	const [isLoading, setIsLoading] = (0, react.useState)(true);
	/** 周视图加载中：fetchWeekData / goToNearestAvailableDate 期间为 true */
	const [isWeekLoading, setIsWeekLoading] = (0, react.useState)(true);
	/** 时段网格加载中：包含周加载 + 日期切换的短暂过渡 */
	const [isGridTransition, setIsGridTransition] = (0, react.useState)(true);
	const isGridLoading = isWeekLoading || isGridTransition;
	const [anchorDate, setAnchorDate] = (0, react.useState)((0, dayjs.default)());
	const [filter, setFilter] = (0, react.useState)("ALL");
	const [search, setSearch] = (0, react.useState)("");
	const [limitMessage, setLimitMessage] = (0, react.useState)("");
	const [mobileCartOpen, setMobileCartOpen] = (0, react.useState)(false);
	const [monthPickerOpen, setMonthPickerOpen] = (0, react.useState)(false);
	const [monthCursor, setMonthCursor] = (0, react.useState)((0, dayjs.default)().startOf("month"));
	const { isLogin, openLoginModal } = require_hooks.useVenueBookingLogin();
	const engineContext = require_useEngineContext.default();
	const utils = (engineContext === null || engineContext === void 0 || (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.utils) || EMPTY_UTILS;
	const [discountList, setDiscountList] = (0, react.useState)([]);
	const [isAgreeDepositPolicy, setIsAgreeDepositPolicy] = (0, react.useState)(false);
	const [cartValidation, setCartValidation] = (0, react.useState)({
		passed: null,
		failures: []
	});
	const [footerActionText, setFooterActionText] = (0, react.useState)(String(_pisell_utils.locales.getText("pisell2.venue.action.next.addons") || ""));
	const [isSubmittingOrder, setIsSubmittingOrder] = (0, react.useState)(false);
	const anchorDateRef = (0, react.useRef)(anchorDate);
	anchorDateRef.current = anchorDate;
	/**
	* bootstrap 只跑一次：避免宿主 Provider 重渲染导致的依赖身份抖动
	* （例如 utils 引用变化 → syncCustomerLoginToModule 重建 → effect 重跑 → 骨架屏闪烁）。
	* 只在首次 venueBookingModule 就绪时执行，和步骤 hydrate 的 hydratedRef 同语义。
	*/
	const bootstrappedRef = (0, react.useRef)(false);
	/** 是否有已选时段（用于判断能否进入下一步） */
	const canNext = (0, react.useMemo)(() => {
		const allSelected = require_hooks.getAllSelectedSlots(venueBookingModule);
		if (Array.isArray(allSelected) && allSelected.length > 0) return true;
		return viewModel.cartItems.length > 0;
	}, [venueBookingModule, viewModel]);
	(0, react.useEffect)(() => {
		if (!limitMessage) return void 0;
		const timer = window.setTimeout(() => setLimitMessage(""), 3800);
		return () => window.clearTimeout(timer);
	}, [limitMessage]);
	/**
	* 步骤缓存 hydrate：首次 module 就绪时读取 OS UI 缓存
	*   - 优先级：pendingStep（用户点过 next 的意图，可能经过登录重定向）→ step（普通刷新场景）
	*   - pendingStep 命中即消费（delete），避免下次刷新还被拉到 checkout
	*   - 基于 cacheId 分桶，无 cacheId 时 OS 层降级为 no-op，getUIState 返回 undefined
	*/
	(0, react.useEffect)(() => {
		var _venueBookingModule$g, _venueBookingModule$g2;
		if (hydratedRef.current || !venueBookingModule) return;
		hydratedRef.current = true;
		const pending = (_venueBookingModule$g = venueBookingModule.getUIState) === null || _venueBookingModule$g === void 0 ? void 0 : _venueBookingModule$g.call(venueBookingModule, "pendingStep");
		if (pending) {
			var _venueBookingModule$d;
			(_venueBookingModule$d = venueBookingModule.deleteUIState) === null || _venueBookingModule$d === void 0 || _venueBookingModule$d.call(venueBookingModule, "pendingStep");
			setCurrentStep(pending);
			return;
		}
		const cached = (_venueBookingModule$g2 = venueBookingModule.getUIState) === null || _venueBookingModule$g2 === void 0 ? void 0 : _venueBookingModule$g2.call(venueBookingModule, "step");
		if (cached) setCurrentStep(cached);
	}, [venueBookingModule]);
	/**
	* 步骤变化写回 OS UI 缓存，hydrate 完成后才写，避免用默认值覆盖已有缓存
	*/
	(0, react.useEffect)(() => {
		var _venueBookingModule$s;
		if (!hydratedRef.current || !venueBookingModule) return;
		(_venueBookingModule$s = venueBookingModule.setUIState) === null || _venueBookingModule$s === void 0 || _venueBookingModule$s.call(venueBookingModule, "step", currentStep);
	}, [currentStep, venueBookingModule]);
	/**
	* 步骤列表是动态的（无 addons 时只 2 步），若缓存 step 落在当前 stepList 之外则回退。
	* 例：缓存为 'addons' 但本次 addonProductList 确实为空，stepList 里没有 'addons'。
	* 必须等 addonsResolvedRef 置位（getProductList 至少 resolve 过一次）才能校验，
	* 否则会被首屏 2 步的过渡态误杀掉合法的 'addons' 缓存。
	*/
	(0, react.useEffect)(() => {
		if (!hydratedRef.current || !addonsResolved) return;
		if (!stepList.includes(currentStep)) setCurrentStep(stepList[0]);
	}, [
		stepList,
		currentStep,
		addonsResolved
	]);
	/**
	* 刷新购物车视图模型（cartItems / summary / note）
	* 可选传入 extraFields 合并到 viewModel（如 addonProductList）
	*/
	const refreshViewModel = (0, react.useCallback)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (extraFields) {
			if (venueBookingModule && typeof venueBookingModule.getSummary === "function") try {
				yield venueBookingModule.getSummary();
			} catch (error) {
				console.warn("[venueBooking] getSummary failed during refreshViewModel", error);
			}
			const moduleData = require_hooks.createVenueBookingViewModel(venueBookingModule);
			setViewModel((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), moduleData), extraFields || {}));
			if (venueBookingModule && typeof venueBookingModule.getDiscountList === "function") setDiscountList(venueBookingModule.getDiscountList() || []);
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), [venueBookingModule]);
	/**
	* 刷新当前日期的 timeSlotGrid（纯计算，不发网络请求）
	*/
	const refreshTimeSlotGrid = (0, react.useCallback)((date) => {
		if (!venueBookingModule) return;
		const grid = require_hooks.getTimeSlotGrid(venueBookingModule, date || require_utils.formatDateKey(anchorDateRef.current));
		setViewModel((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, { timeSlotGrid: grid }));
	}, [venueBookingModule]);
	/**
	* 拉取指定周的资源可用性数据 + 刷新 dateSummary + timeSlotGrid
	*/
	const fetchWeekData = (0, react.useCallback)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (startDate, endDate) {
			if (!venueBookingModule) return;
			setIsWeekLoading(true);
			try {
				const clamped = clampRangeToToday(startDate, endDate);
				let summary = [];
				if (clamped) {
					yield require_hooks.fetchResourceAvailability(venueBookingModule, clamped.startDate, clamped.endDate);
					const raw = require_hooks.getDateRangeSummary(venueBookingModule, clamped.startDate, clamped.endDate);
					summary = Array.isArray(raw) ? raw : [];
				}
				const grid = require_hooks.getTimeSlotGrid(venueBookingModule, require_utils.formatDateKey(anchorDateRef.current));
				setViewModel((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, {
					dateSummary: summary,
					timeSlotGrid: grid
				}));
			} finally {
				setIsWeekLoading(false);
			}
		});
		return function(_x2, _x3) {
			return _ref2.apply(this, arguments);
		};
	}(), [venueBookingModule]);
	/**
	* 从指定日期开始，自动定位最近可用日期：
	* 1) 优先当前周内最近可用；
	* 2) 若当前周全不可用，则向后滚动周继续查找。
	*/
	const goToNearestAvailableDate = (0, react.useCallback)(function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (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;
					yield require_hooks.fetchResourceAvailability(venueBookingModule, clamped.startDate, clamped.endDate);
					const weekSummary = require_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 = require_hooks.getTimeSlotGrid(venueBookingModule, require_utils.formatDateKey(candidateDate));
					setViewModel((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, {
						dateSummary: Array.isArray(weekSummary) ? weekSummary : [],
						timeSlotGrid: grid
					}));
					return;
				}
				const fallbackGrid = require_hooks.getTimeSlotGrid(venueBookingModule, require_utils.formatDateKey(fromDate));
				setAnchorDate(fromDate);
				setMonthCursor(fromDate.startOf("month"));
				setViewModel((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, {
					dateSummary: fallbackSummary,
					timeSlotGrid: fallbackGrid
				}));
			} finally {
				setIsWeekLoading(false);
			}
		});
		return function(_x4) {
			return _ref3.apply(this, arguments);
		};
	}(), [venueBookingModule]);
	/**
	* 切换选中/取消某个时段
	* 调用 OS venueBooking.toggleSlot 后刷新 grid + 购物车
	*/
	const toggleSlot = (0, react.useCallback)(function() {
		var _ref4 = require_asyncToGenerator._asyncToGenerator(function* (resourceId, productId, slot) {
			if (!venueBookingModule || !slot.price) return;
			try {
				yield require_hooks.toggleSlotAction(venueBookingModule, {
					resourceId,
					productId,
					startTime: slot.startTime,
					endTime: slot.endTime,
					price: slot.price
				});
				refreshTimeSlotGrid();
				yield refreshViewModel();
			} catch (error) {
				console.warn("[venueBooking] toggleSlot failed", error);
			}
		});
		return function(_x5, _x6, _x7) {
			return _ref4.apply(this, arguments);
		};
	}(), [
		venueBookingModule,
		refreshTimeSlotGrid,
		refreshViewModel
	]);
	/** 更新订单备注到 OS 模块 */
	const updateOrderNote = (0, react.useCallback)(function() {
		var _ref5 = require_asyncToGenerator._asyncToGenerator(function* (note) {
			yield require_hooks.safeRunModuleAction(venueBookingModule, "updateTempOrderNote", note);
			yield refreshViewModel();
		});
		return function(_x8) {
			return _ref5.apply(this, arguments);
		};
	}(), [venueBookingModule, refreshViewModel]);
	/** 安全调用 OS 模块方法的快捷入口 */
	const runModuleAction = (0, react.useCallback)(function() {
		var _ref6 = require_asyncToGenerator._asyncToGenerator(function* (actionName, ...args) {
			return require_hooks.safeRunModuleAction(venueBookingModule, actionName, ...args);
		});
		return function(_x9) {
			return _ref6.apply(this, arguments);
		};
	}(), [venueBookingModule]);
	/**
	* 将当前登录客户同步到 OS venueBooking 模块
	* - 已登录且拿到 customerId 时调用 onCustomerLogin
	* - 缺失 customerId / 解析异常时静默降级，不阻断流程
	*/
	const syncCustomerLoginToModule = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		try {
			var _utils$token, _utils$token$get, _utils$storage, _utils$storage$get;
			if (!!!(utils === null || utils === void 0 || (_utils$token = utils.token) === null || _utils$token === void 0 || (_utils$token$get = _utils$token.get) === null || _utils$token$get === void 0 ? void 0 : _utils$token$get.call(_utils$token))) return;
			const rawCustomer = utils === null || utils === void 0 || (_utils$storage = utils.storage) === null || _utils$storage === void 0 || (_utils$storage$get = _utils$storage.get) === null || _utils$storage$get === void 0 ? void 0 : _utils$storage$get.call(_utils$storage, "customer");
			const customer = typeof rawCustomer === "string" ? JSON.parse(rawCustomer || "{}") : rawCustomer || {};
			const customerId = customer === null || customer === void 0 ? void 0 : customer.id;
			if (!customerId) return;
			yield runModuleAction("onCustomerLogin", { customerId });
		} catch (error) {
			console.warn("[venueBooking] syncCustomerLoginToModule failed", error);
		}
	}), [utils, runModuleAction]);
	const goToStep = (0, react.useCallback)((step) => {
		if (!stepList.includes(step)) return;
		setCurrentStep(step);
	}, [stepList]);
	const nextStep = (0, 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, react.useCallback)(() => {
		setCurrentStep((prev) => {
			const idx = stepList.findIndex((s) => s === prev);
			if (idx <= 0) return prev;
			return stepList[idx - 1];
		});
	}, [stepList]);
	/**
	* 登录成功后调用 OS onCustomerLogin 加载折扣配置并刷新数据
	*/
	const handleLoginSuccess = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		try {
			var _venueBookingModule$g3;
			yield syncCustomerLoginToModule();
			setDiscountList((venueBookingModule === null || venueBookingModule === void 0 || (_venueBookingModule$g3 = venueBookingModule.getDiscountList) === null || _venueBookingModule$g3 === void 0 ? void 0 : _venueBookingModule$g3.call(venueBookingModule)) || []);
			yield refreshViewModel();
		} catch (error) {
			console.warn("[venueBooking] handleLoginSuccess failed", error);
		}
	}), [
		syncCustomerLoginToModule,
		venueBookingModule,
		refreshViewModel
	]);
	/**
	* 以 ref 持有最新的 callback，供仅需稳定调用、不希望因 callback 身份变动而重跑的 effect 使用
	* - bootstrap useEffect：只关心 venueBookingModule 首次就绪，不应被 utils/callback 身份抖动连带重跑
	* - pubsub 订阅 useEffect：只订阅一次，真正回调取最新实现
	*/
	const syncCustomerLoginRef = (0, react.useRef)(syncCustomerLoginToModule);
	syncCustomerLoginRef.current = syncCustomerLoginToModule;
	const goToNearestAvailableDateRef = (0, react.useRef)(goToNearestAvailableDate);
	goToNearestAvailableDateRef.current = goToNearestAvailableDate;
	const handleLoginSuccessRef = (0, react.useRef)(handleLoginSuccess);
	handleLoginSuccessRef.current = handleLoginSuccess;
	/** 结账步骤提交订单（调用 OS venueBooking.submitOrder） */
	const submitOrder = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (isSubmittingOrder) return;
		try {
			var _result$data, _viewModel$summary;
			setIsSubmittingOrder(true);
			const result = yield require_hooks.safeRunModuleAction(venueBookingModule, "submitOrder");
			yield refreshViewModel();
			const orderId = (result === null || result === void 0 || (_result$data = result.data) === null || _result$data === void 0 ? void 0 : _result$data.order_id) || (result === null || result === void 0 ? void 0 : result.order_id) || "";
			const totalAmount = viewModel === null || viewModel === void 0 || (_viewModel$summary = viewModel.summary) === null || _viewModel$summary === void 0 ? void 0 : _viewModel$summary.total_amount;
			antd.message.success({
				content: String(_pisell_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 = require_hooks.getOtherParams(venueBookingModule);
			if (typeof (utils === null || utils === void 0 ? void 0 : utils.action) === "function" && (otherParams === null || otherParams === void 0 ? void 0 : otherParams.openData["sale.require_payment_on_submit"])) {
				var _otherParams$openData;
				if (totalAmount === 0 || (otherParams === null || otherParams === void 0 || (_otherParams$openData = otherParams.openData["checkout.checkout_options"]) === null || _otherParams$openData === void 0 ? void 0 : _otherParams$openData.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) {
			antd.message.error({
				content: getSubmitOrderErrorMessage(error),
				duration: 2
			});
			console.warn("[venueBooking] submitOrder failed", error);
		} finally {
			setIsSubmittingOrder(false);
		}
	}), [
		isSubmittingOrder,
		venueBookingModule,
		refreshViewModel,
		utils,
		viewModel === null || viewModel === void 0 || (_viewModel$summary2 = viewModel.summary) === null || _viewModel$summary2 === void 0 ? void 0 : _viewModel$summary2.total_amount
	]);
	/** 带登录门禁的提交订单入口 */
	const handleSubmitOrder = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		var _venueBookingModule$s2;
		if (isLogin) {
			yield submitOrder();
			return;
		}
		venueBookingModule === null || venueBookingModule === void 0 || (_venueBookingModule$s2 = venueBookingModule.setUIState) === null || _venueBookingModule$s2 === void 0 || _venueBookingModule$s2.call(venueBookingModule, "pendingStep", "checkout");
		openLoginModal({ callback: (status) => {
			var _venueBookingModule$d2;
			if (status !== "success") return;
			venueBookingModule === null || venueBookingModule === void 0 || (_venueBookingModule$d2 = venueBookingModule.deleteUIState) === null || _venueBookingModule$d2 === void 0 || _venueBookingModule$d2.call(venueBookingModule, "pendingStep");
			handleLoginSuccess().then(() => {
				submitOrder();
			});
		} });
	}), [
		isLogin,
		openLoginModal,
		handleLoginSuccess,
		submitOrder,
		venueBookingModule
	]);
	/** 跳转到 checkout，并在未登录时插入登录门禁（参照 scanOrder gotoCheckOrder） */
	const proceedToCheckout = (0, react.useCallback)(() => {
		if (!isLogin) {
			var _venueBookingModule$s3;
			venueBookingModule === null || venueBookingModule === void 0 || (_venueBookingModule$s3 = venueBookingModule.setUIState) === null || _venueBookingModule$s3 === void 0 || _venueBookingModule$s3.call(venueBookingModule, "pendingStep", "checkout");
			openLoginModal({ callback: (status) => {
				if (status === "success") {
					var _venueBookingModule$d3;
					venueBookingModule === null || venueBookingModule === void 0 || (_venueBookingModule$d3 = venueBookingModule.deleteUIState) === null || _venueBookingModule$d3 === void 0 || _venueBookingModule$d3.call(venueBookingModule, "pendingStep");
					handleLoginSuccess().then(() => goToStep("checkout"));
				}
			} });
			return;
		}
		goToStep("checkout");
	}, [
		isLogin,
		openLoginModal,
		handleLoginSuccess,
		goToStep,
		venueBookingModule
	]);
	/** 主操作按钮行为（含登录门禁，自适应 2/3 步流程） */
	const handlePrimaryAction = (0, react.useCallback)(() => {
		var _viewModel$summary3, _deposit$deposit_poli;
		if (currentStep === "select-venue") {
			if (!canNext) {
				antd.message.warning({
					content: String(_pisell_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 = (_viewModel$summary3 = viewModel.summary) === null || _viewModel$summary3 === void 0 ? void 0 : _viewModel$summary3.deposit;
		if ((deposit === null || deposit === void 0 ? void 0 : deposit.hasDeposit) && (deposit === null || deposit === void 0 || (_deposit$deposit_poli = deposit.deposit_policy_data) === null || _deposit$deposit_poli === void 0 ? void 0 : _deposit$deposit_poli.length) > 0 && !isAgreeDepositPolicy) {
			antd.message.warning(String(_pisell_utils.locales.getText("pisell2.appointment.deposit.agree.policy") || "请先同意定金协议"));
			return;
		}
		handleSubmitOrder();
	}, [
		currentStep,
		canNext,
		isAgreeDepositPolicy,
		viewModel.summary,
		stepList,
		proceedToCheckout,
		goToStep,
		handleSubmitOrder
	]);
	(0, react.useEffect)(() => {
		var _pubsub$subscribe;
		const pubsub = utils === null || utils === void 0 ? void 0 : utils.pubsub;
		if (!pubsub) return;
		const onGlobalLoginSuccess = function() {
			var _ref7 = require_asyncToGenerator._asyncToGenerator(function* (res) {
				if (res === "success" || (res === null || res === void 0 ? void 0 : res.status) === "success") yield handleLoginSuccessRef.current();
			});
			return function onGlobalLoginSuccess(_x10) {
				return _ref7.apply(this, arguments);
			};
		}();
		(_pubsub$subscribe = pubsub.subscribe) === null || _pubsub$subscribe === void 0 || _pubsub$subscribe.call(pubsub, "pisell1.login.success", onGlobalLoginSuccess);
		return () => {
			var _pubsub$unsubscribe;
			(_pubsub$unsubscribe = pubsub.unsubscribe) === null || _pubsub$unsubscribe === void 0 || _pubsub$unsubscribe.call(pubsub, "pisell1.login.success", onGlobalLoginSuccess);
		};
	}, [utils === null || utils === void 0 ? void 0 : utils.pubsub]);
	(0, react.useEffect)(() => {
		if (!venueBookingModule) return;
		setIsGridTransition(true);
		refreshTimeSlotGrid(require_utils.formatDateKey(anchorDate));
		const timer = window.setTimeout(() => setIsGridTransition(false), 220);
		return () => window.clearTimeout(timer);
	}, [
		anchorDate,
		venueBookingModule,
		refreshTimeSlotGrid
	]);
	(0, react.useEffect)(() => {
		var _pisellOS$effects, _pisellOS$effects$on;
		if (!venueBookingModule) return;
		let cancelled = false;
		const syncCartValidation = function() {
			var _ref8 = require_asyncToGenerator._asyncToGenerator(function* () {
				try {
					const value = yield require_hooks.safeRunModuleAction(venueBookingModule, "getCartValidation");
					if (!cancelled) setCartValidation({
						passed: typeof (value === null || value === void 0 ? void 0 : value.passed) === "boolean" || (value === null || value === void 0 ? void 0 : value.passed) === null ? value.passed : null,
						failures: Array.isArray(value === null || value === void 0 ? void 0 : value.failures) ? value.failures : []
					});
				} catch (_unused) {
					if (!cancelled) setCartValidation({
						passed: null,
						failures: []
					});
				}
			});
			return function syncCartValidation() {
				return _ref8.apply(this, arguments);
			};
		}();
		const onCartValidationChanged = (payload) => {
			const nextValue = payload === null || payload === void 0 ? void 0 : payload.cartValidation;
			setCartValidation({
				passed: typeof (nextValue === null || nextValue === void 0 ? void 0 : nextValue.passed) === "boolean" || (nextValue === null || nextValue === void 0 ? void 0 : nextValue.passed) === null ? nextValue.passed : typeof (payload === null || payload === void 0 ? void 0 : payload.cartValidationPassed) === "boolean" ? payload.cartValidationPassed : null,
				failures: Array.isArray(nextValue === null || nextValue === void 0 ? void 0 : nextValue.failures) ? nextValue.failures : []
			});
		};
		syncCartValidation();
		pisellOS === null || pisellOS === void 0 || (_pisellOS$effects = pisellOS.effects) === null || _pisellOS$effects === void 0 || (_pisellOS$effects$on = _pisellOS$effects.on) === null || _pisellOS$effects$on === void 0 || _pisellOS$effects$on.call(_pisellOS$effects, "venueBooking:onCartValidationChanged", onCartValidationChanged);
		return () => {
			var _pisellOS$effects2, _pisellOS$effects2$of;
			cancelled = true;
			pisellOS === null || pisellOS === void 0 || (_pisellOS$effects2 = pisellOS.effects) === null || _pisellOS$effects2 === void 0 || (_pisellOS$effects2$of = _pisellOS$effects2.off) === null || _pisellOS$effects2$of === void 0 || _pisellOS$effects2$of.call(_pisellOS$effects2, "venueBooking:onCartValidationChanged", onCartValidationChanged);
		};
	}, [pisellOS, venueBookingModule]);
	(0, react.useEffect)(() => {
		if (bootstrappedRef.current || !venueBookingModule) return;
		bootstrappedRef.current = true;
		let unmounted = false;
		(function() {
			var _ref9 = require_asyncToGenerator._asyncToGenerator(function* () {
				try {
					setIsLoading(true);
					yield syncCustomerLoginRef.current();
					yield require_hooks.loadVenueProducts(venueBookingModule, require_hooks.VENUE_PRODUCT_IDS);
					const venueProducts = typeof (venueBookingModule === null || venueBookingModule === void 0 ? void 0 : venueBookingModule.getVenueProducts) === "function" ? venueBookingModule.getVenueProducts() : [];
					yield goToNearestAvailableDateRef.current(anchorDateRef.current);
					const moduleData = require_hooks.createVenueBookingViewModel(venueBookingModule);
					if (!unmounted) {
						setViewModel((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, 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 || venueBookingModule === void 0 ? void 0 : venueBookingModule.getProductList) === "function") venueBookingModule.getProductList().then((res) => {
							if (!unmounted && Array.isArray(res)) setViewModel((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, 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);
				}
			});
			return function bootstrap() {
				return _ref9.apply(this, arguments);
			};
		})()();
		return () => {
			unmounted = true;
		};
	}, [venueBookingModule]);
	const value = (0, 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__ */ react.default.createElement(VenueBookingContext.Provider, { value }, children);
}
/** 消费 venueBooking Context 的 hook */
function useVenueBookingContext() {
	const context = (0, react.useContext)(VenueBookingContext);
	if (context) return context;
	throw new Error("useVenueBookingContext must be used within VenueBookingProvider");
}
//#endregion
exports.VenueBookingProvider = VenueBookingProvider;
exports.useVenueBookingContext = useVenueBookingContext;
