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");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
//#region src/components/scanOrder/context.tsx
const ScanOrderContext = (0, react.createContext)(void 0);
const INITIAL_VIEW_MODEL = {
	menuItems: [],
	cartItems: [],
	summary: {},
	note: ""
};
function ScanOrderProvider({ entryContext, children }) {
	const pisellOS = require_useEngineContext.usePisellOS();
	const scanOrderModule = require_hooks.useScanOrderModule();
	const [isLoading, setIsLoading] = (0, react.useState)(true);
	const [errorMessage, setErrorMessage] = (0, react.useState)("");
	const [currentStep, setCurrentStep] = (0, react.useState)("init");
	const [viewModel, setViewModel] = (0, react.useState)(INITIAL_VIEW_MODEL);
	const [cartValidation, setCartValidation] = (0, react.useState)({
		passed: null,
		failures: []
	});
	const [footerActionText, setFooterActionText] = (0, react.useState)(String(_pisell_utils.locales.getText("pisell2.scan.order.action.select.required") || ""));
	const [tableName, setTableName] = (0, react.useState)("");
	const [entryMode, setEntryMode] = (0, react.useState)("default");
	const [submitDisabledTips, setSubmitDisabledTips] = (0, react.useState)("");
	const [discountList, setDiscountList] = (0, react.useState)([]);
	const [isCacheHydrated, setIsCacheHydrated] = (0, react.useState)(false);
	const [resumeStep, setResumeStep] = (0, react.useState)(null);
	const hydratedRef = (0, react.useRef)(false);
	const stepList = [...require_hooks.SCAN_ORDER_STEPS];
	const isGatePassed = (0, react.useCallback)((flag) => {
		var _scanOrderModule$getU;
		const gate = scanOrderModule === null || scanOrderModule === void 0 || (_scanOrderModule$getU = scanOrderModule.getUIState) === null || _scanOrderModule$getU === void 0 ? void 0 : _scanOrderModule$getU.call(scanOrderModule, "gate");
		return Boolean(gate === null || gate === void 0 ? void 0 : gate[flag]);
	}, [scanOrderModule]);
	const markGate = (0, react.useCallback)((flag) => {
		var _scanOrderModule$getU2;
		if (!(scanOrderModule === null || scanOrderModule === void 0 ? void 0 : scanOrderModule.setUIState)) return;
		const prev = ((_scanOrderModule$getU2 = scanOrderModule.getUIState) === null || _scanOrderModule$getU2 === void 0 ? void 0 : _scanOrderModule$getU2.call(scanOrderModule, "gate")) || {};
		scanOrderModule.setUIState("gate", require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, { [flag]: true }));
	}, [scanOrderModule]);
	const clearStepCache = (0, react.useCallback)(() => {
		var _scanOrderModule$clea;
		scanOrderModule === null || scanOrderModule === void 0 || (_scanOrderModule$clea = scanOrderModule.clearUIState) === null || _scanOrderModule$clea === void 0 || _scanOrderModule$clea.call(scanOrderModule);
		setResumeStep(null);
	}, [scanOrderModule]);
	const consumeResumeStep = (0, react.useCallback)(() => {
		setResumeStep(null);
	}, []);
	const refreshViewModel = function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* () {
			if (scanOrderModule && typeof scanOrderModule.getSummary === "function") try {
				yield scanOrderModule.getSummary();
			} catch (error) {
				console.warn("[scanOrder] getSummary failed during refreshViewModel", error);
			}
			setViewModel(require_hooks.createScanOrderViewModel(scanOrderModule));
			if (scanOrderModule && typeof scanOrderModule.getDiscountList === "function") setDiscountList(scanOrderModule.getDiscountList() || []);
		});
		return function refreshViewModel() {
			return _ref.apply(this, arguments);
		};
	}();
	const updateOrderNote = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (note) {
			yield require_hooks.safeRunModuleAction(scanOrderModule, "updateTempOrderNote", note);
			yield refreshViewModel();
		});
		return function updateOrderNote(_x) {
			return _ref2.apply(this, arguments);
		};
	}();
	const goToStep = (step) => {
		if (!stepList.includes(step)) return;
		setCurrentStep(step);
	};
	const nextStep = () => {
		const currentIndex = stepList.findIndex((step) => step === currentStep);
		if (currentIndex < 0) return;
		if (currentIndex >= stepList.length - 1) return;
		setCurrentStep(stepList[currentIndex + 1]);
	};
	const prevStep = () => {
		const currentIndex = stepList.findIndex((step) => step === currentStep);
		if (currentIndex <= 0) return;
		setCurrentStep(stepList[currentIndex - 1]);
	};
	const runModuleAction = function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (actionName, ...args) {
			return require_hooks.safeRunModuleAction(scanOrderModule, actionName, ...args);
		});
		return function runModuleAction(_x2) {
			return _ref3.apply(this, arguments);
		};
	}();
	/**
	* 步骤缓存 hydrate：首次 module 就绪时读取 SDK UI 缓存
	*   - 若缓存里的 entryContext.resourceId 与本次入参不一致，整桶作废（clearUIState）后仅写入新 entryContext
	*   - 一致：按 pendingStep > step 顺序挑恢复目标写入 resumeStep；pendingStep 命中后立即消费
	*   - 注意不直接 setCurrentStep，避免 <Menu>/<Check> 在 checkResourceAvailable 装载
	*     dineInConfig（含 menu_list_ids）之前 mount 发请求
	*   - 基于 cacheId 分桶，无 cacheId 时 SDK 层降级为 no-op
	*/
	(0, react.useEffect)(() => {
		var _entryContext$resourc, _entryContext$biz, _scanOrderModule$getU3, _cachedEntry$resource, _cachedEntry$biz, _scanOrderModule$getU4, _scanOrderModule$getU5;
		if (hydratedRef.current || !scanOrderModule) return;
		hydratedRef.current = true;
		const normalizedResourceId = String((_entryContext$resourc = entryContext === null || entryContext === void 0 ? void 0 : entryContext.resource_id) !== null && _entryContext$resourc !== void 0 ? _entryContext$resourc : "");
		const normalizedBiz = String((_entryContext$biz = entryContext === null || entryContext === void 0 ? void 0 : entryContext.biz) !== null && _entryContext$biz !== void 0 ? _entryContext$biz : "");
		const currentHasOrderId = Boolean(entryContext === null || entryContext === void 0 ? void 0 : entryContext.order_id);
		const cachedEntry = (_scanOrderModule$getU3 = scanOrderModule.getUIState) === null || _scanOrderModule$getU3 === void 0 ? void 0 : _scanOrderModule$getU3.call(scanOrderModule, "entryContext");
		if (!(Boolean(cachedEntry) && String((_cachedEntry$resource = cachedEntry === null || cachedEntry === void 0 ? void 0 : cachedEntry.resourceId) !== null && _cachedEntry$resource !== void 0 ? _cachedEntry$resource : "") === normalizedResourceId && String((_cachedEntry$biz = cachedEntry === null || cachedEntry === void 0 ? void 0 : cachedEntry.biz) !== null && _cachedEntry$biz !== void 0 ? _cachedEntry$biz : "") === normalizedBiz)) {
			var _scanOrderModule$clea2, _scanOrderModule$setU;
			(_scanOrderModule$clea2 = scanOrderModule.clearUIState) === null || _scanOrderModule$clea2 === void 0 || _scanOrderModule$clea2.call(scanOrderModule);
			(_scanOrderModule$setU = scanOrderModule.setUIState) === null || _scanOrderModule$setU === void 0 || _scanOrderModule$setU.call(scanOrderModule, "entryContext", {
				resourceId: normalizedResourceId,
				hasOrderId: currentHasOrderId,
				biz: normalizedBiz
			});
			setIsCacheHydrated(true);
			return;
		}
		const isResumable = (s) => s === "product" || s === "check";
		const pending = (_scanOrderModule$getU4 = scanOrderModule.getUIState) === null || _scanOrderModule$getU4 === void 0 ? void 0 : _scanOrderModule$getU4.call(scanOrderModule, "pendingStep");
		if (isResumable(pending)) {
			var _scanOrderModule$dele;
			(_scanOrderModule$dele = scanOrderModule.deleteUIState) === null || _scanOrderModule$dele === void 0 || _scanOrderModule$dele.call(scanOrderModule, "pendingStep");
			setResumeStep(pending);
			setIsCacheHydrated(true);
			return;
		}
		const cached = (_scanOrderModule$getU5 = scanOrderModule.getUIState) === null || _scanOrderModule$getU5 === void 0 ? void 0 : _scanOrderModule$getU5.call(scanOrderModule, "step");
		if (isResumable(cached)) setResumeStep(cached);
		setIsCacheHydrated(true);
	}, [
		scanOrderModule,
		entryContext === null || entryContext === void 0 ? void 0 : entryContext.resource_id,
		entryContext === null || entryContext === void 0 ? void 0 : entryContext.order_id,
		entryContext === null || entryContext === void 0 ? void 0 : entryContext.biz
	]);
	/**
	* hydrate 完成后写回 step 缓存。
	* 注意跳过 `currentStep === 'init'`：hydrate 刚完成时 currentStep 依然是初始 'init'，
	* 直接写回会覆盖掉 sessionStorage 里真正有用的 'product' / 'check'。
	*/
	(0, react.useEffect)(() => {
		var _scanOrderModule$setU2;
		if (!hydratedRef.current || !isCacheHydrated || !scanOrderModule) return;
		if (currentStep === "init") return;
		(_scanOrderModule$setU2 = scanOrderModule.setUIState) === null || _scanOrderModule$setU2 === void 0 || _scanOrderModule$setU2.call(scanOrderModule, "step", currentStep);
	}, [
		currentStep,
		isCacheHydrated,
		scanOrderModule
	]);
	(0, react.useEffect)(() => {
		var _pisellOS$effects, _pisellOS$effects$on;
		if (!scanOrderModule) return;
		let cancelled = false;
		const syncCartValidation = function() {
			var _ref4 = require_asyncToGenerator._asyncToGenerator(function* () {
				try {
					const value = yield require_hooks.safeRunModuleAction(scanOrderModule, "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 (error) {
					if (!cancelled) setCartValidation({
						passed: null,
						failures: []
					});
				}
			});
			return function syncCartValidation() {
				return _ref4.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, "scanOrder: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, "scanOrder:onCartValidationChanged", onCartValidationChanged);
		};
	}, [pisellOS, scanOrderModule]);
	(0, react.useEffect)(() => {
		let unmounted = false;
		(function() {
			var _ref5 = require_asyncToGenerator._asyncToGenerator(function* () {
				try {
					if (!scanOrderModule) {
						setErrorMessage("scanOrder module not ready");
						setIsLoading(false);
						return;
					}
					if (!(typeof scanOrderModule.checkAccess === "function" ? yield scanOrderModule.checkAccess(entryContext) : true)) throw new Error("scanOrder access denied");
					if (typeof scanOrderModule.getPageConfig === "function") yield scanOrderModule.getPageConfig(entryContext);
					yield refreshViewModel();
					if (!unmounted) {
						setErrorMessage("");
						setIsLoading(false);
					}
				} catch (error) {
					if (!unmounted) {
						setErrorMessage((error === null || error === void 0 ? void 0 : error.message) || "scanOrder load failed");
						setIsLoading(false);
					}
				}
			});
			return function bootstrap() {
				return _ref5.apply(this, arguments);
			};
		})()();
		return () => {
			unmounted = true;
		};
	}, [
		scanOrderModule,
		entryContext === null || entryContext === void 0 ? void 0 : entryContext.biz,
		entryContext === null || entryContext === void 0 ? void 0 : entryContext.resource_id
	]);
	const value = (0, react.useMemo)(() => {
		return {
			entryContext,
			scanOrderModule,
			cartValidation,
			isLoading,
			errorMessage,
			currentStep,
			stepList,
			viewModel,
			footerActionText,
			tableName,
			entryMode,
			submitDisabledTips,
			discountList,
			isReady: !isLoading && !errorMessage,
			setCurrentStep,
			goToStep,
			nextStep,
			prevStep,
			refreshViewModel,
			runModuleAction,
			setFooterActionText,
			setTableName,
			setEntryMode,
			setSubmitDisabledTips,
			updateOrderNote,
			isCacheHydrated,
			markGate,
			isGatePassed,
			clearStepCache,
			resumeStep,
			consumeResumeStep
		};
	}, [
		entryContext,
		scanOrderModule,
		cartValidation,
		isLoading,
		errorMessage,
		currentStep,
		stepList,
		viewModel,
		footerActionText,
		tableName,
		entryMode,
		submitDisabledTips,
		discountList,
		isCacheHydrated,
		markGate,
		isGatePassed,
		clearStepCache,
		resumeStep,
		consumeResumeStep
	]);
	return /* @__PURE__ */ react.default.createElement(ScanOrderContext.Provider, { value }, children);
}
function useScanOrderContext() {
	const context = (0, react.useContext)(ScanOrderContext);
	if (context) return context;
	throw new Error("useScanOrderContext must be used within ScanOrderProvider");
}
//#endregion
exports.ScanOrderProvider = ScanOrderProvider;
exports.useScanOrderContext = useScanOrderContext;
