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/scanOrder/components/Cart/index.tsx
var Cart_exports = {};
__export(Cart_exports, {
  default: () => Cart
});
module.exports = __toCommonJS(Cart_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_shoppingCart = __toESM(require("../../../shoppingCart"));
var import_context = require("../../context");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_subTotal = __toESM(require("../../../subTotal"));
var import_Voucher = __toESM(require("../Voucher"));
var import_index = require("./index.less");
function Cart(props) {
  var _a, _b, _c, _d, _e, _f;
  const {
    open,
    onCancel,
    onNext,
    items,
    summary,
    embedded = false,
    confirmLoading = false,
    extraContent,
    disabled = false
  } = props;
  const { runModuleAction, refreshViewModel, scanOrderModule } = (0, import_context.useScanOrderContext)();
  const engineContext = (0, import_useEngineContext.default)();
  const businessUtils = (_b = (_a = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.businessUtils;
  const locale = ((_d = (_c = engineContext == null ? void 0 : engineContext.engine) == null ? void 0 : _c.props) == null ? void 0 : _d.locale) || "en";
  const hasGoodPassApp = !!((_e = businessUtils == null ? void 0 : businessUtils.getAppByModal) == null ? void 0 : _e.call(businessUtils, "goodpass"));
  const hasDiscountCardApp = !!((_f = businessUtils == null ? void 0 : businessUtils.getAppByModal) == null ? void 0 : _f.call(businessUtils, "discountcard"));
  const showVoucher = hasGoodPassApp || hasDiscountCardApp;
  const isVisible = embedded || open;
  if (!isVisible) return null;
  const [dineInConfig, setDineInConfig] = (0, import_react.useState)(null);
  const getConfig = (0, import_react.useCallback)(async () => {
    const otherParams = await runModuleAction("getOtherParams");
    console.log("otherParams >>>>> ", otherParams);
    const dineInConfig2 = (otherParams == null ? void 0 : otherParams.dineInConfig) ?? {};
    setDineInConfig(dineInConfig2);
  }, [runModuleAction]);
  (0, import_react.useEffect)(() => {
    getConfig();
  }, []);
  const isShowNote = (0, import_react.useMemo)(() => {
    return dineInConfig == null ? void 0 : dineInConfig["sale.allow_item_notes"];
  }, [dineInConfig]);
  const totalDisplayAmount = (0, import_react.useMemo)(() => {
    const rawAmount = (summary == null ? void 0 : summary.total_amount) ?? (summary == null ? void 0 : summary.expect_amount) ?? (summary == null ? void 0 : summary.amount) ?? (summary == null ? void 0 : summary.total) ?? (summary == null ? void 0 : summary.totalAmount) ?? (summary == null ? void 0 : summary.payable_amount) ?? 0;
    const parsed = Number(rawAmount);
    if (Number.isNaN(parsed)) return "0.00";
    return parsed.toFixed(2);
  }, [summary]);
  const confirmOrderText = String(
    import_utils.locales.getText("pisell2.scan.order.action.confirm.order") || import_utils.locales.getText("pisell2.event.confirm") || "Confirm"
  );
  const subTotalList = (0, import_react.useMemo)(() => {
    var _a2;
    const subTotal = Number((summary == null ? void 0 : summary.product_amount) ?? 0);
    const totalTaxFee = Number((summary == null ? void 0 : summary.tax_fee) ?? 0);
    const total = Number((summary == null ? void 0 : summary.total_amount) ?? (summary == null ? void 0 : summary.expect_amount) ?? 0);
    const tempOrder = (_a2 = scanOrderModule == null ? void 0 : scanOrderModule.getTempOrder) == null ? void 0 : _a2.call(scanOrderModule);
    const tempSummary = (tempOrder == null ? void 0 : tempOrder.summary) || {};
    const taxTitle = String(
      (tempSummary == null ? void 0 : tempSummary.tax_title) || (summary == null ? void 0 : summary.tax_title) || "GST/Tax"
    );
    const rawTaxRate = Number((tempSummary == null ? void 0 : tempSummary.tax_rate) ?? (summary == null ? void 0 : summary.tax_rate));
    const normalizedTaxRate = Number.isNaN(rawTaxRate) ? 0 : rawTaxRate > 1 ? rawTaxRate / 100 : rawTaxRate;
    const isPriceIncludeTax = Boolean(
      (tempSummary == null ? void 0 : tempSummary.is_price_include_tax) ?? (tempSummary == null ? void 0 : tempSummary.isPriceIncludeTax) ?? (summary == null ? void 0 : summary.is_price_include_tax)
    );
    const surchargeItems = ((summary == null ? void 0 : summary.surcharges) || []).filter((s) => Number(s == null ? void 0 : s.amount) > 0).map((s) => {
      const labelObj = (s == null ? void 0 : s.label) || (s == null ? void 0 : s.name) || {};
      const label = labelObj[locale] || labelObj.en || labelObj.original || (s == null ? void 0 : s.key) || "";
      return {
        key: (s == null ? void 0 : s.key) || `surcharge_${s == null ? void 0 : s.surcharge_id}`,
        label,
        value: Number(s == null ? void 0 : s.amount)
      };
    });
    return [
      {
        key: "sub_total",
        value: Number.isNaN(subTotal) ? 0 : subTotal
      },
      ...surchargeItems,
      {
        key: "tax",
        value: Number.isNaN(totalTaxFee) ? 0 : totalTaxFee,
        hidden: Number.isNaN(totalTaxFee) ? true : totalTaxFee <= 0,
        tax: {
          title: taxTitle,
          rate: normalizedTaxRate,
          is_price_include_tax: isPriceIncludeTax
        }
      },
      {
        key: "custom_total",
        value: Number.isNaN(total) ? 0 : total,
        label: import_utils.locales.getText("pisell2.event.total"),
        bold: true
      }
    ];
  }, [summary, scanOrderModule, locale]);
  const handleCartChange = async (item, type) => {
    if (type === "note") {
      const productId = (item == null ? void 0 : item.product_id) ?? (item == null ? void 0 : item.id) ?? null;
      const productVariantId = Number((item == null ? void 0 : item.product_variant_id) ?? 0);
      const identityKey = item == null ? void 0 : item.identity_key;
      if (productId === null && Number.isNaN(productVariantId)) return;
      const identity = {
        product_id: productId,
        product_variant_id: Number.isNaN(productVariantId) ? 0 : productVariantId
      };
      if (typeof identityKey === "string" && identityKey.length > 0) {
        identity.identity_key = identityKey;
      }
      try {
        await runModuleAction(
          "setOrderProductLineNote",
          identity,
          String((item == null ? void 0 : item.note) ?? "")
        );
        await refreshViewModel();
      } catch (error) {
        console.error("[scanOrder] setOrderProductLineNote failed", {
          error,
          item
        });
      }
      return;
    } else if (type === "delete") {
      const productId = (item == null ? void 0 : item.product_id) ?? (item == null ? void 0 : item.id) ?? null;
      const productVariantId = Number((item == null ? void 0 : item.product_variant_id) ?? 0);
      const identityKey = item == null ? void 0 : item.identity_key;
      if (productId === null && Number.isNaN(productVariantId)) return;
      if (typeof identityKey !== "string" || identityKey.length === 0) {
        console.error("[scanOrder] removeProductFromOrder skipped: missing identity_key", {
          item
        });
        return;
      }
      try {
        await runModuleAction("removeProductFromOrder", {
          product_id: productId,
          product_variant_id: Number.isNaN(productVariantId) ? 0 : productVariantId,
          identity_key: identityKey
        });
        await refreshViewModel();
      } catch (error) {
        console.error("[scanOrder] removeProductFromOrder failed", {
          error,
          item
        });
      }
    }
  };
  (0, import_react.useEffect)(() => {
    if (!isVisible) return;
    refreshViewModel();
  }, [isVisible]);
  const cartLineItems = /* @__PURE__ */ import_react.default.createElement(
    import_shoppingCart.default,
    {
      productParams: {
        products: items || [],
        hideAddBtn: true,
        disabledEdit: false,
        isShowNote,
        isShowDelete: true,
        isShowPackageNote: false,
        isShowChangeHolder: false,
        isShowHolder: false,
        isShowAddHolderButton: false
      },
      platform: "h5",
      emptyText: import_utils.locales.getText("pisell2.scan.order.empty.product"),
      isOpenGroup: false,
      isHideClearCart: true,
      onChange: handleCartChange
    }
  );
  const cartSubtotalSection = /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, showVoucher ? /* @__PURE__ */ import_react.default.createElement(import_Voucher.default, null) : null, /* @__PURE__ */ import_react.default.createElement(import_subTotal.default, { list: subTotalList, style: { padding: 0 } }), extraContent ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-extra-content" }, extraContent) : null);
  const cartBodyClassName = embedded ? "pisell-scan-order-cart-body pisell-scan-order-cart-body-embedded" : "pisell-scan-order-cart-body";
  const cartBodyContent = /* @__PURE__ */ import_react.default.createElement("div", { className: cartBodyClassName }, cartLineItems, cartSubtotalSection);
  if (embedded) {
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, cartBodyContent, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-embedded-footer" }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        type: "primary",
        block: true,
        onClick: onNext,
        loading: confirmLoading,
        className: disabled ? "pisell-scan-order-cart-embedded-confirm-disabled" : void 0
      },
      confirmOrderText
    )));
  }
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-mask", onClick: onCancel }), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-drawer" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-header" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-sheet-handle-wrap", "aria-hidden": true }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-sheet-handle" }))), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-list-scroll" }, cartLineItems), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-bottom-panel" }, cartSubtotalSection, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-footer" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-footer-total-col" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-footer-total-label" }, import_utils.locales.getText("pisell2.event.total")), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-cart-footer-total-amount" }, "$", totalDisplayAmount)), /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { type: "primary", onClick: onNext, loading: confirmLoading }, import_utils.locales.getText("pisell2.event.continue"))))));
}
