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_serve = require("../booking/info/service/serve.js");
const require_utils = require("../booking/utils.js");
const require_useEngineContext = require("../../hooks/useEngineContext.js");
const require_index = require("../../plus/skuOptionsSelection/index.js");
const require_locales = require("./locales.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let decimal_js = require("decimal.js");
decimal_js = require_runtime.__toESM(decimal_js);
let _pisell_materials = require("@pisell/materials");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
require("./index.less");
//#region src/components/kioskSkuDetail/index.tsx
/**
* @description Kiosk 商品详情（参考 Figma: Kiosk / Launchpad screen）
* - 默认从 URL query 读取商品 id（productId / product_id / id），内部通过 getProductDetail 拉取详情
* - 中间区域用 SKUOptionsSelection 做 SKU 选择
* - 底部用 PisellNumberSelector 做数量编辑
*/
function KioskSkuDetail(props) {
	var _ref, _context$appHelper, _context$engine, _context$appHelper2, _store$getState, _store$getState2, _store$getState3;
	const { className, style, onAddToCart } = props;
	/**
	* @description 从 URL 中读取 productId（兼容 search / hash query）
	* - 支持 key: productId / product_id / id
	*/
	const productIdFromUrl = (0, react.useMemo)(() => {
		return getQueryFirstMatch({ keys: [
			"productId",
			"product_id",
			"id"
		] });
	}, []);
	const initialProductId = (_ref = productIdFromUrl !== null && productIdFromUrl !== void 0 ? productIdFromUrl : props.productId) !== null && _ref !== void 0 ? _ref : null;
	/**
	* @description 目前 scheduleDate 暂时固定成“当天”
	* - 按本地时区格式化为 YYYY-MM-DD
	*/
	const scheduleDate = (0, react.useMemo)(() => (0, dayjs.default)().format("YYYY-MM-DD"), []);
	const stageScale = useDesignStageScale({
		designWidth: 1080,
		designHeight: 1800
	});
	const context = require_useEngineContext.default();
	const { interaction } = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	_pisell_utils.locales.init(require_locales.default, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || "en");
	require_utils.request.setRequest(context.appHelper.utils.request);
	const { store, getData, Toast } = ((_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.utils) || {};
	store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || _store$getState.call(store);
	const symbol = (store === null || store === void 0 || (_store$getState2 = store.getState) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.call(store)) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.global) === null || _store$getState2 === void 0 ? void 0 : _store$getState2.symbol) || "$";
	const currency_code = (store === null || store === void 0 || (_store$getState3 = store.getState) === null || _store$getState3 === void 0 || (_store$getState3 = _store$getState3.call(store)) === null || _store$getState3 === void 0 || (_store$getState3 = _store$getState3.global) === null || _store$getState3 === void 0 ? void 0 : _store$getState3.currency_code) || "AUD";
	const [isLoading, setIsLoading] = (0, react.useState)(false);
	const [errorText, setErrorText] = (0, react.useState)(null);
	const [productData, setProductData] = (0, react.useState)(null);
	const [quantity, setQuantity] = (0, react.useState)(1);
	const [skuValue, setSkuValue] = (0, react.useState)({
		product_id: 0,
		product_variant_id: 0,
		bundle: [],
		option: []
	});
	const [skuDefaultValue, setSkuDefaultValue] = (0, react.useState)({
		product_id: 0,
		product_variant_id: 0,
		bundle: [],
		option: []
	});
	const [isEdit, setIsEdit] = (0, react.useState)(false);
	const skuOptionsSelectionRef = (0, react.useRef)(null);
	const [nativeInitData, setNativeInitData] = (0, react.useState)(null);
	/**
	* @description 防止“原生多次初始化/快速切换”导致请求乱序覆盖
	*/
	const requestSeqRef = (0, react.useRef)(0);
	const resetForInit = (0, react.useCallback)(() => {
		setProductData(null);
		setErrorText(null);
		setQuantity(1);
		setSkuValue({
			product_id: 0,
			product_variant_id: 0,
			bundle: [],
			option: []
		});
		setSkuDefaultValue({
			product_id: 0,
			product_variant_id: 0,
			bundle: [],
			option: []
		});
		setNativeInitData(null);
	}, []);
	const loadByProductId = (0, react.useCallback)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (productId, options = {}) {
			console.log("准备 load", productId);
			if (productId === null || typeof productId === "undefined" || productId === "") return;
			const reqId = ++requestSeqRef.current;
			setIsLoading(true);
			setErrorText(null);
			try {
				var _context$engine2;
				const params = {
					open_deposit: (getData === null || getData === void 0 ? void 0 : getData("bookingv2_deposit")) || 0,
					"translate-locale": (context === null || context === void 0 || (_context$engine2 = context.engine) === null || _context$engine2 === void 0 || (_context$engine2 = _context$engine2.props) === null || _context$engine2 === void 0 ? void 0 : _context$engine2.locale) || "en"
				};
				params.schedule_date = scheduleDate;
				const res = yield require_serve.getProductDetail(String(productId), params);
				console.log("详情接口");
				console.log(JSON.stringify(res));
				const apiData = ((res === null || res === void 0 ? void 0 : res.id) ? res : res === null || res === void 0 ? void 0 : res.data) || {};
				if (reqId !== requestSeqRef.current) return;
				setProductData(apiData);
				console.log("已设置 productData");
				const normalizedProductId = Number((apiData === null || apiData === void 0 ? void 0 : apiData.product_id) || (apiData === null || apiData === void 0 ? void 0 : apiData.id) || productId || 0);
				const minNumUnit = Number((apiData === null || apiData === void 0 ? void 0 : apiData.min_num_unit) || 1);
				if (options.shouldInitQuantity !== false) setQuantity(minNumUnit > 0 ? minNumUnit : 1);
				const initialSkuValue = {
					product_id: normalizedProductId,
					product_variant_id: (() => {
						var _apiData$variant;
						const firstVariantId = Array.isArray(apiData === null || apiData === void 0 ? void 0 : apiData.variant) ? Number((apiData === null || apiData === void 0 || (_apiData$variant = apiData.variant) === null || _apiData$variant === void 0 || (_apiData$variant = _apiData$variant[0]) === null || _apiData$variant === void 0 ? void 0 : _apiData$variant.id) || 0) : 0;
						return Number.isFinite(firstVariantId) ? firstVariantId : 0;
					})(),
					bundle: [],
					option: []
				};
				if (options.shouldInitSku !== false) {
					setSkuValue(initialSkuValue);
					setSkuDefaultValue(initialSkuValue);
					setTimeout(() => {
						if (initialSkuValue.product_variant_id) {
							var _skuOptionsSelectionR;
							(_skuOptionsSelectionR = skuOptionsSelectionRef.current) === null || _skuOptionsSelectionR === void 0 || _skuOptionsSelectionR.validate();
						}
					}, 0);
				}
			} catch (error) {
				console.error(error);
				setErrorText("Failed to load product detail");
			} finally {
				if (reqId !== requestSeqRef.current) return;
				setIsLoading(false);
			}
		});
		return function(_x) {
			return _ref2.apply(this, arguments);
		};
	}(), [getData, scheduleDate]);
	const loadRef = (0, react.useRef)(loadByProductId);
	loadRef.current = loadByProductId;
	(0, react.useEffect)(() => {
		var _interaction$utils, _interaction$utils$po, _interaction$utils2, _interaction$utils2$m, _interaction$utils3, _interaction$utils3$m, _interaction$utils4, _interaction$utils4$m;
		interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$po = _interaction$utils.postMessageToApp) === null || _interaction$utils$po === void 0 || _interaction$utils$po.call(_interaction$utils, {
			module: "wallet_pass",
			key: "page_load"
		});
		interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 || (_interaction$utils2$m = _interaction$utils2.mountFunction) === null || _interaction$utils2$m === void 0 || _interaction$utils2$m.call(_interaction$utils2, "wallet_pass", "restore_buy_wallet_pass", (id) => {
			console.log("重置状态", id);
			console.log("宽", window.innerWidth);
			console.log("高", window.innerHeight);
			console.log("设备像素比", window.devicePixelRatio);
			resetForInit();
			if (id || id === 0) loadRef.current(id);
			setIsEdit(false);
		});
		interaction === null || interaction === void 0 || (_interaction$utils3 = interaction.utils) === null || _interaction$utils3 === void 0 || (_interaction$utils3$m = _interaction$utils3.mountFunction) === null || _interaction$utils3$m === void 0 || _interaction$utils3$m.call(_interaction$utils3, "wallet_pass", "restore_recharge_wallet_pass", (_data) => {
			const data = JSON.parse(_data || "{}");
			console.log("重置状态", data === null || data === void 0 ? void 0 : data.productId);
			console.log("宽", window.innerWidth);
			console.log("高", window.innerHeight);
			console.log("设备像素比", window.devicePixelRatio);
			resetForInit();
			if ((data === null || data === void 0 ? void 0 : data.productId) || (data === null || data === void 0 ? void 0 : data.productId) === 0) loadRef.current(data === null || data === void 0 ? void 0 : data.productId);
			setIsEdit(false);
			setNativeInitData(data);
		});
		interaction === null || interaction === void 0 || (_interaction$utils4 = interaction.utils) === null || _interaction$utils4 === void 0 || (_interaction$utils4$m = _interaction$utils4.mountFunction) === null || _interaction$utils4$m === void 0 || _interaction$utils4$m.call(_interaction$utils4, "wallet_pass", "edit_buy_wallet_pass", (data) => {
			console.log("编辑状态", data);
			const productData = JSON.parse(data);
			/**
			* @description 编辑态原生只会触发 edit_buy_wallet_pass
			* - 这里需要主动 load 一次拿到最新详情（尤其是 variant 列表/价格）
			* - 但不能覆盖原生传入的 variantId / quantity
			*/
			loadRef.current(productData.productId, {
				shouldInitSku: false,
				shouldInitQuantity: false
			});
			setSkuValue({
				product_id: productData.productId,
				product_variant_id: Number(productData.variantId),
				bundle: [],
				option: []
			});
			setSkuDefaultValue({
				product_id: productData.productId,
				product_variant_id: Number(productData.variantId),
				bundle: [],
				option: []
			});
			setIsEdit(true);
			setNativeInitData(productData);
		});
		if (initialProductId || initialProductId === 0) loadRef.current(initialProductId);
	}, []);
	const coverUrl = (0, react.useMemo)(() => {
		return (productData === null || productData === void 0 ? void 0 : productData.cover) || (productData === null || productData === void 0 ? void 0 : productData.image) || "";
	}, [productData]);
	const titleText = (0, react.useMemo)(() => {
		var _productData$_extend;
		return (productData === null || productData === void 0 ? void 0 : productData.title) || (productData === null || productData === void 0 || (_productData$_extend = productData._extend) === null || _productData$_extend === void 0 ? void 0 : _productData$_extend.product_name) || (productData === null || productData === void 0 ? void 0 : productData.product_name) || "";
	}, [productData]);
	const descriptionText = (0, react.useMemo)(() => {
		var _productData$_extend2;
		return (productData === null || productData === void 0 ? void 0 : productData.description) || (productData === null || productData === void 0 ? void 0 : productData.sub_title) || (productData === null || productData === void 0 || (_productData$_extend2 = productData._extend) === null || _productData$_extend2 === void 0 ? void 0 : _productData$_extend2.sub_title) || "";
	}, [productData]);
	const unitPrice = (0, react.useMemo)(() => {
		const selectedVariantId = Number((skuValue === null || skuValue === void 0 ? void 0 : skuValue.product_variant_id) || 0);
		if (selectedVariantId && Array.isArray(productData === null || productData === void 0 ? void 0 : productData.variant)) {
			const matched = productData.variant.find((item) => Number(item === null || item === void 0 ? void 0 : item.id) === selectedVariantId);
			const vPrice = Number((matched === null || matched === void 0 ? void 0 : matched.price) || 0);
			if (!Number.isNaN(vPrice) && vPrice !== 0) return vPrice;
		}
		return Number((productData === null || productData === void 0 ? void 0 : productData.price) || 0);
	}, [productData, skuValue === null || skuValue === void 0 ? void 0 : skuValue.product_variant_id]);
	const priceRangeText = (0, react.useMemo)(() => {
		const variantPrices = Array.isArray(productData === null || productData === void 0 ? void 0 : productData.variant) ? productData.variant.map((v) => Number((v === null || v === void 0 ? void 0 : v.price) || 0)).filter((n) => !Number.isNaN(n) && n > 0) : [];
		const base = Number((productData === null || productData === void 0 ? void 0 : productData.price) || 0);
		const all = [...variantPrices, ...base > 0 ? [base] : []];
		if (all.length === 0) return "";
		const min = Math.min(...all);
		const max = Math.max(...all);
		if (min === max) return `${symbol}${min.toFixed(2)}`;
		return `${symbol}${min.toFixed(2)}-${symbol}${max.toFixed(2)}`;
	}, [productData, symbol]);
	const itemTotal = (0, react.useMemo)(() => {
		const deUnit = new decimal_js.default(unitPrice || 0);
		const deQty = new decimal_js.default(quantity || 0);
		return deUnit.mul(deQty).toNumber();
	}, [quantity, unitPrice]);
	/**
	* @description 用于展示的总价文案（参考 SkuDetailModal 的 totalText 逻辑）
	* - 统一处理负数符号
	* - 统一保留两位小数
	*/
	const itemTotalText = (0, react.useMemo)(() => {
		const deTotal = new decimal_js.default(itemTotal || 0);
		return `${deTotal.toNumber() < 0 ? "-" : ""}${symbol}${deTotal.abs().toNumber().toFixed(2)}`;
	}, [itemTotal, symbol]);
	const handleAddToCart = () => {
		var _skuOptionsSelectionR2;
		if (!productData) return;
		(_skuOptionsSelectionR2 = skuOptionsSelectionRef.current) === null || _skuOptionsSelectionR2 === void 0 || _skuOptionsSelectionR2.validate();
		if (!skuValue.product_variant_id) {
			Toast.info(_pisell_utils.locales.getText("pisell2.text.kiosk.sku.detail.toast.select.variant"));
			return;
		}
		const obj = {
			productDetail: productData,
			quantity,
			variantId: skuValue.product_variant_id,
			pricePerUnit: unitPrice,
			isWebBuyWalletPass: true,
			balance: nativeInitData === null || nativeInitData === void 0 ? void 0 : nativeInitData.balance,
			walletCodeId: nativeInitData === null || nativeInitData === void 0 ? void 0 : nativeInitData.walletCodeId,
			walletPassCodeId: nativeInitData === null || nativeInitData === void 0 ? void 0 : nativeInitData.walletPassCodeId
		};
		interaction.utils.postMessageToApp({
			module: "wallet_pass",
			key: "buy_wallet_pass",
			data: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, nativeInitData || {}), {}, {
				productData: obj,
				isEdit
			})
		});
	};
	const onBack = () => {
		interaction.utils.postMessageToApp({
			module: "wallet_pass",
			key: "back"
		});
	};
	const stageStyle = (0, react.useMemo)(() => {
		return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, style || {}), {}, {
			width: 1080,
			height: 1800,
			transform: `translateX(-50%) scale(${stageScale})`,
			transformOrigin: "top center"
		});
	}, [stageScale, style]);
	return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail-viewport" }, /* @__PURE__ */ react.default.createElement("div", {
		className: (0, classnames.default)("pisell-kiosk-sku-detail", className),
		style: stageStyle
	}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__content" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__hero" }, coverUrl ? /* @__PURE__ */ react.default.createElement("img", {
		className: "pisell-kiosk-sku-detail__hero-img",
		src: coverUrl,
		alt: titleText || "product"
	}) : /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__hero-placeholder" })), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__header" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__title" }, titleText || (isLoading ? "Loading…" : "")), !!descriptionText && /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__desc" }, /* @__PURE__ */ react.default.createElement("div", { dangerouslySetInnerHTML: { __html: descriptionText } })), (nativeInitData === null || nativeInitData === void 0 ? void 0 : nativeInitData.balance) ? /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__price-range" }, _pisell_utils.locales.getText("pisell2.text.kiosk.sku.detail.balance"), ": ", symbol, nativeInitData === null || nativeInitData === void 0 ? void 0 : nativeInitData.balance) : !!priceRangeText && /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__price-range" }, priceRangeText, " ", currency_code), !!errorText && /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__error" }, errorText)), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__options-card" }, productData && Array.isArray(productData === null || productData === void 0 ? void 0 : productData.variant) && productData.variant.length > 0 ? /* @__PURE__ */ react.default.createElement(require_index.default, {
		ref: skuOptionsSelectionRef,
		dataSource: productData,
		value: skuDefaultValue,
		skuCardConfig: {
			price: { visible: true },
			variantPriceVisible: true
		},
		onChange: (v) => {
			setSkuValue(v);
		},
		customScrollParent: ".pisell-kiosk-sku-detail"
	}) : /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__options-loading" }, isLoading ? _pisell_utils.locales.getText("pisell2.text.kiosk.sku.detail.loading.options") : ""))), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__footer" }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
		className: "pisell-kiosk-sku-detail__back-btn",
		size: "large",
		onClick: onBack
	}, _pisell_utils.locales.getText("pisell2.text.kiosk.sku.detail.btn.back")), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__footer-center" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-kiosk-sku-detail__item-total" }, _pisell_utils.locales.getText("pisell2.text.kiosk.sku.detail.item.total"), ":", " ", itemTotalText)), /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
		type: "primary",
		className: "pisell-kiosk-sku-detail__add-btn",
		size: "large",
		onClick: handleAddToCart,
		disabled: !productData || isLoading
	}, _pisell_utils.locales.getText(isEdit ? "pisell2.text.kiosk.sku.detail.btn.update" : "pisell2.text.kiosk.sku.detail.btn.add.to.cart")))));
}
/**
* @description 从当前页面 URL 中读取 query 参数（兼容 hash router）
* - search: ?a=b
* - hash: #/path?a=b
*/
function getQueryFirstMatch(params) {
	var _params$keys;
	if (typeof window === "undefined") return null;
	if (!(params === null || params === void 0 || (_params$keys = params.keys) === null || _params$keys === void 0 ? void 0 : _params$keys.length)) return null;
	const keys = params.keys;
	const tryRead = (raw) => {
		if (!raw) return null;
		const normalized = raw.startsWith("?") ? raw.slice(1) : raw;
		const searchParams = new URLSearchParams(normalized);
		for (const key of keys) {
			const value = searchParams.get(key);
			if (value) return value;
		}
		return null;
	};
	const fromSearch = tryRead(window.location.search || "");
	if (fromSearch) return fromSearch;
	const hash = window.location.hash || "";
	const queryIndex = hash.indexOf("?");
	if (queryIndex === -1) return null;
	return tryRead(hash.slice(queryIndex + 1));
}
/**
* @description 按设计稿基准尺寸（默认 1080x1800）计算页面缩放比例
* - scale = min(viewportW/designW, viewportH/designH, 1)
*/
function useDesignStageScale(params) {
	const designWidth = params.designWidth;
	const designHeight = params.designHeight;
	const [scale, setScale] = (0, react.useState)(1);
	(0, react.useEffect)(() => {
		const update = () => {
			const viewportWidth = window.innerWidth || designWidth;
			const viewportHeight = window.innerHeight || designHeight;
			setScale(Math.min(viewportWidth / designWidth, viewportHeight / designHeight, 1));
		};
		update();
		window.addEventListener("resize", update);
		return () => window.removeEventListener("resize", update);
	}, [designHeight, designWidth]);
	return scale;
}
//#endregion
exports.default = KioskSkuDetail;
