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/kioskSkuDetail/index.tsx
var kioskSkuDetail_exports = {};
__export(kioskSkuDetail_exports, {
  default: () => kioskSkuDetail_default
});
module.exports = __toCommonJS(kioskSkuDetail_exports);
var import_react = __toESM(require("react"));
var import_decimal = __toESM(require("decimal.js"));
var import_classnames = __toESM(require("classnames"));
var import_materials = require("@pisell/materials");
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_skuOptionsSelection = __toESM(require("../../plus/skuOptionsSelection"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_serve = require("../booking/info/service/serve");
var import_locales = __toESM(require("./locales"));
var import_index = require("./index.less");
var import_utils2 = require("../booking/utils");
function KioskSkuDetail(props) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
  const { className, style, onAddToCart } = props;
  const productIdFromUrl = (0, import_react.useMemo)(() => {
    return getQueryFirstMatch({ keys: ["productId", "product_id", "id"] });
  }, []);
  const initialProductId = productIdFromUrl ?? props.productId ?? null;
  const scheduleDate = (0, import_react.useMemo)(() => (0, import_dayjs.default)().format("YYYY-MM-DD"), []);
  const stageScale = useDesignStageScale({ designWidth: 1080, designHeight: 1800 });
  const context = (0, import_useEngineContext.default)();
  const { interaction } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  import_utils.locales.init(import_locales.default, ((_c = (_b = context == null ? void 0 : context.engine) == null ? void 0 : _b.props) == null ? void 0 : _c.locale) || "en");
  import_utils2.request.setRequest(context.appHelper.utils.request);
  const { store, getData, Toast } = ((_d = context.appHelper) == null ? void 0 : _d.utils) || {};
  const state = (_e = store == null ? void 0 : store.getState) == null ? void 0 : _e.call(store);
  const symbol = ((_h = (_g = (_f = store == null ? void 0 : store.getState) == null ? void 0 : _f.call(store)) == null ? void 0 : _g.global) == null ? void 0 : _h.symbol) || "$";
  const currency_code = ((_k = (_j = (_i = store == null ? void 0 : store.getState) == null ? void 0 : _i.call(store)) == null ? void 0 : _j.global) == null ? void 0 : _k.currency_code) || "AUD";
  const [isLoading, setIsLoading] = (0, import_react.useState)(false);
  const [errorText, setErrorText] = (0, import_react.useState)(null);
  const [productData, setProductData] = (0, import_react.useState)(null);
  const [quantity, setQuantity] = (0, import_react.useState)(1);
  const [skuValue, setSkuValue] = (0, import_react.useState)({
    product_id: 0,
    product_variant_id: 0,
    bundle: [],
    option: []
  });
  const [skuDefaultValue, setSkuDefaultValue] = (0, import_react.useState)({
    product_id: 0,
    product_variant_id: 0,
    bundle: [],
    option: []
  });
  const [isEdit, setIsEdit] = (0, import_react.useState)(false);
  const skuOptionsSelectionRef = (0, import_react.useRef)(null);
  const [nativeInitData, setNativeInitData] = (0, import_react.useState)(null);
  const requestSeqRef = (0, import_react.useRef)(0);
  const resetForInit = (0, import_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, import_react.useCallback)(async (productId, options = {}) => {
    var _a2, _b2;
    console.log("准备 load", productId);
    if (productId === null || typeof productId === "undefined" || productId === "") return;
    const reqId = ++requestSeqRef.current;
    setIsLoading(true);
    setErrorText(null);
    try {
      const open_deposit = (getData == null ? void 0 : getData("bookingv2_deposit")) || 0;
      const params = { open_deposit, "translate-locale": ((_b2 = (_a2 = context == null ? void 0 : context.engine) == null ? void 0 : _a2.props) == null ? void 0 : _b2.locale) || "en" };
      params.schedule_date = scheduleDate;
      const res = await (0, import_serve.getProductDetail)(String(productId), params);
      console.log("详情接口");
      console.log(JSON.stringify(res));
      const apiData = ((res == null ? void 0 : res.id) ? res : res == null ? void 0 : res.data) || {};
      if (reqId !== requestSeqRef.current) return;
      setProductData(apiData);
      console.log("已设置 productData");
      const normalizedProductId = Number(
        (apiData == null ? void 0 : apiData.product_id) || (apiData == null ? void 0 : apiData.id) || productId || 0
      );
      const minNumUnit = Number((apiData == null ? void 0 : apiData.min_num_unit) || 1);
      if (options.shouldInitQuantity !== false) {
        setQuantity(minNumUnit > 0 ? minNumUnit : 1);
      }
      const defaultVariantId = (() => {
        var _a3, _b3;
        const firstVariantId = Array.isArray(apiData == null ? void 0 : apiData.variant) ? Number(((_b3 = (_a3 = apiData == null ? void 0 : apiData.variant) == null ? void 0 : _a3[0]) == null ? void 0 : _b3.id) || 0) : 0;
        return Number.isFinite(firstVariantId) ? firstVariantId : 0;
      })();
      const initialSkuValue = {
        product_id: normalizedProductId,
        product_variant_id: defaultVariantId,
        bundle: [],
        option: []
      };
      if (options.shouldInitSku !== false) {
        setSkuValue(initialSkuValue);
        setSkuDefaultValue(initialSkuValue);
        setTimeout(() => {
          var _a3;
          if (initialSkuValue.product_variant_id) {
            (_a3 = skuOptionsSelectionRef.current) == null ? void 0 : _a3.validate();
          }
        }, 0);
      }
    } catch (error) {
      console.error(error);
      setErrorText("Failed to load product detail");
    } finally {
      if (reqId !== requestSeqRef.current) return;
      setIsLoading(false);
    }
  }, [getData, scheduleDate]);
  const loadRef = (0, import_react.useRef)(loadByProductId);
  loadRef.current = loadByProductId;
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
    (_b2 = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b2.call(_a2, {
      module: "wallet_pass",
      key: "page_load"
    });
    (_d2 = (_c2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _c2.mountFunction) == null ? void 0 : _d2.call(
      _c2,
      "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);
      }
    );
    (_f2 = (_e2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _e2.mountFunction) == null ? void 0 : _f2.call(
      _e2,
      "wallet_pass",
      "restore_recharge_wallet_pass",
      (_data) => {
        const data = JSON.parse(_data || "{}");
        console.log("重置状态", data == null ? void 0 : data.productId);
        console.log("宽", window.innerWidth);
        console.log("高", window.innerHeight);
        console.log("设备像素比", window.devicePixelRatio);
        resetForInit();
        if ((data == null ? void 0 : data.productId) || (data == null ? void 0 : data.productId) === 0) loadRef.current(data == null ? void 0 : data.productId);
        setIsEdit(false);
        setNativeInitData(data);
      }
    );
    (_h2 = (_g2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _g2.mountFunction) == null ? void 0 : _h2.call(
      _g2,
      "wallet_pass",
      "edit_buy_wallet_pass",
      (data) => {
        console.log("编辑状态", data);
        const productData2 = JSON.parse(data);
        loadRef.current(productData2.productId, {
          shouldInitSku: false,
          shouldInitQuantity: false
        });
        setSkuValue({
          product_id: productData2.productId,
          product_variant_id: Number(productData2.variantId),
          bundle: [],
          option: []
        });
        setSkuDefaultValue({
          product_id: productData2.productId,
          product_variant_id: Number(productData2.variantId),
          bundle: [],
          option: []
        });
        setIsEdit(true);
        setNativeInitData(productData2);
      }
    );
    if (initialProductId || initialProductId === 0) loadRef.current(initialProductId);
  }, []);
  const coverUrl = (0, import_react.useMemo)(() => {
    return (productData == null ? void 0 : productData.cover) || (productData == null ? void 0 : productData.image) || "";
  }, [productData]);
  const titleText = (0, import_react.useMemo)(() => {
    var _a2;
    return (productData == null ? void 0 : productData.title) || ((_a2 = productData == null ? void 0 : productData._extend) == null ? void 0 : _a2.product_name) || (productData == null ? void 0 : productData.product_name) || "";
  }, [productData]);
  const descriptionText = (0, import_react.useMemo)(() => {
    var _a2;
    return (productData == null ? void 0 : productData.description) || (productData == null ? void 0 : productData.sub_title) || ((_a2 = productData == null ? void 0 : productData._extend) == null ? void 0 : _a2.sub_title) || "";
  }, [productData]);
  const unitPrice = (0, import_react.useMemo)(() => {
    const selectedVariantId = Number((skuValue == null ? void 0 : skuValue.product_variant_id) || 0);
    if (selectedVariantId && Array.isArray(productData == null ? void 0 : productData.variant)) {
      const matched = productData.variant.find(
        (item) => Number(item == null ? void 0 : item.id) === selectedVariantId
      );
      const vPrice = Number((matched == null ? void 0 : matched.price) || 0);
      if (!Number.isNaN(vPrice) && vPrice !== 0) return vPrice;
    }
    return Number((productData == null ? void 0 : productData.price) || 0);
  }, [productData, skuValue == null ? void 0 : skuValue.product_variant_id]);
  const priceRangeText = (0, import_react.useMemo)(() => {
    const variantPrices = Array.isArray(productData == null ? void 0 : productData.variant) ? productData.variant.map((v) => Number((v == null ? void 0 : v.price) || 0)).filter((n) => !Number.isNaN(n) && n > 0) : [];
    const base = Number((productData == null ? 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, import_react.useMemo)(() => {
    const deUnit = new import_decimal.default(unitPrice || 0);
    const deQty = new import_decimal.default(quantity || 0);
    return deUnit.mul(deQty).toNumber();
  }, [quantity, unitPrice]);
  const itemTotalText = (0, import_react.useMemo)(() => {
    const deTotal = new import_decimal.default(itemTotal || 0);
    const priceSign = deTotal.toNumber() < 0 ? "-" : "";
    return `${priceSign}${symbol}${deTotal.abs().toNumber().toFixed(2)}`;
  }, [itemTotal, symbol]);
  const handleAddToCart = () => {
    var _a2;
    if (!productData) return;
    (_a2 = skuOptionsSelectionRef.current) == null ? void 0 : _a2.validate();
    if (!skuValue.product_variant_id) {
      Toast.info(import_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 ? void 0 : nativeInitData.balance,
      walletCodeId: nativeInitData == null ? void 0 : nativeInitData.walletCodeId,
      walletPassCodeId: nativeInitData == null ? void 0 : nativeInitData.walletPassCodeId
    };
    interaction.utils.postMessageToApp({
      module: "wallet_pass",
      key: "buy_wallet_pass",
      data: {
        ...nativeInitData || {},
        // 把洗好的数据放这里
        productData: obj,
        isEdit
      }
    });
  };
  const onBack = () => {
    interaction.utils.postMessageToApp({
      module: "wallet_pass",
      key: "back"
    });
  };
  const stageStyle = (0, import_react.useMemo)(() => {
    return {
      ...style || {},
      width: 1080,
      height: 1800,
      transform: `translateX(-50%) scale(${stageScale})`,
      transformOrigin: "top center"
    };
  }, [stageScale, style]);
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail-viewport" }, /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)("pisell-kiosk-sku-detail", className),
      style: stageStyle
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__hero" }, coverUrl ? /* @__PURE__ */ import_react.default.createElement(
      "img",
      {
        className: "pisell-kiosk-sku-detail__hero-img",
        src: coverUrl,
        alt: titleText || "product"
      }
    ) : /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__hero-placeholder" })), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__header" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__title" }, titleText || (isLoading ? "Loading…" : "")), !!descriptionText && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__desc" }, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        dangerouslySetInnerHTML: {
          __html: descriptionText
        }
      }
    )), (nativeInitData == null ? void 0 : nativeInitData.balance) ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__price-range" }, import_utils.locales.getText("pisell2.text.kiosk.sku.detail.balance"), ": ", symbol, nativeInitData == null ? void 0 : nativeInitData.balance) : !!priceRangeText && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__price-range" }, priceRangeText, " ", currency_code), !!errorText && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__error" }, errorText)), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__options-card" }, productData && Array.isArray(productData == null ? void 0 : productData.variant) && productData.variant.length > 0 ? /* @__PURE__ */ import_react.default.createElement(
      import_skuOptionsSelection.default,
      {
        ref: skuOptionsSelectionRef,
        dataSource: productData,
        value: skuDefaultValue,
        skuCardConfig: {
          price: {
            visible: true
          },
          variantPriceVisible: true
        },
        onChange: (v) => {
          setSkuValue(v);
        },
        customScrollParent: ".pisell-kiosk-sku-detail"
      }
    ) : /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__options-loading" }, isLoading ? import_utils.locales.getText(
      "pisell2.text.kiosk.sku.detail.loading.options"
    ) : ""))),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__footer" }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        className: "pisell-kiosk-sku-detail__back-btn",
        size: "large",
        onClick: onBack
      },
      import_utils.locales.getText("pisell2.text.kiosk.sku.detail.btn.back")
    ), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__footer-center" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-kiosk-sku-detail__item-total" }, import_utils.locales.getText("pisell2.text.kiosk.sku.detail.item.total"), ":", " ", itemTotalText)), /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        type: "primary",
        className: "pisell-kiosk-sku-detail__add-btn",
        size: "large",
        onClick: handleAddToCart,
        disabled: !productData || isLoading
      },
      import_utils.locales.getText(
        isEdit ? "pisell2.text.kiosk.sku.detail.btn.update" : "pisell2.text.kiosk.sku.detail.btn.add.to.cart"
      )
    ))
  ));
}
var kioskSkuDetail_default = KioskSkuDetail;
function getQueryFirstMatch(params) {
  var _a;
  if (typeof window === "undefined") return null;
  if (!((_a = params == null ? void 0 : params.keys) == null ? void 0 : _a.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));
}
function useDesignStageScale(params) {
  const designWidth = params.designWidth;
  const designHeight = params.designHeight;
  const [scale, setScale] = (0, import_react.useState)(1);
  (0, import_react.useEffect)(() => {
    const update = () => {
      const viewportWidth = window.innerWidth || designWidth;
      const viewportHeight = window.innerHeight || designHeight;
      const nextScale = Math.min(
        viewportWidth / designWidth,
        viewportHeight / designHeight,
        1
      );
      setScale(nextScale);
    };
    update();
    window.addEventListener("resize", update);
    return () => window.removeEventListener("resize", update);
  }, [designHeight, designWidth]);
  return scale;
}
