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/plus/pisellSaleSummaryDetail/index.tsx
var pisellSaleSummaryDetail_exports = {};
__export(pisellSaleSummaryDetail_exports, {
  PisellSaleSummaryDetail: () => PisellSaleSummaryDetail,
  default: () => pisellSaleSummaryDetail_default
});
module.exports = __toCommonJS(pisellSaleSummaryDetail_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_decimal = __toESM(require("decimal.js"));
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_useInitLocalesOnce = __toESM(require("../../hooks/useInitLocalesOnce"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_usePaymentMethodNameMap = require("../pisellSalesManagement/hooks/usePaymentMethodNameMap");
var import_locales = __toESM(require("./locales"));
var import_index = require("./index.less");
var PREFIX = "pisell-sale-summary-detail";
var SECTION_ROW_CLASS = `${PREFIX}__section-row`;
var STANDALONE_ROW_CLASS = `${PREFIX}__standalone-row`;
var DIVIDER_ROW_CLASS = `${PREFIX}__divider-row`;
var PAYMENT_SURCHARGE_ROW_CLASS = `${PREFIX}__payment-surcharge-row`;
var SUMMARY_DETAIL_LEVEL_CONFIG = {
  1: {
    rowStyle: { padding: "0 0 12px" },
    labelTextStyle: {
      color: "#a9b8ee",
      fontSize: 13,
      fontWeight: 900,
      lineHeight: "18px"
    },
    valueTextStyle: {
      color: "#f5f8ff",
      fontSize: 13,
      fontWeight: 900,
      lineHeight: "18px"
    },
    expandIconStyle: { size: 14, color: "#e7eeff" }
  },
  2: {
    rowStyle: { padding: "0" },
    labelTextStyle: {
      color: "#f5f8ff",
      fontSize: 13,
      fontWeight: 800,
      lineHeight: "19px"
    },
    valueTextStyle: {
      color: "#f5f8ff",
      fontSize: 13,
      fontWeight: 900,
      lineHeight: "19px"
    },
    expandIconStyle: { size: 14, color: "#e7eeff" }
  },
  3: {
    rowStyle: { padding: "0" },
    labelTextStyle: {
      color: "#a9b8ee",
      fontSize: 13,
      fontWeight: 700,
      lineHeight: "19px"
    },
    valueTextStyle: {
      color: "#a9b8ee",
      fontSize: 13,
      fontWeight: 800,
      lineHeight: "19px"
    },
    expandIconStyle: { size: 14, color: "#e7eeff" }
  }
};
function normalizeVisibleDetailChildren(children) {
  return (children == null ? void 0 : children.filter((child) => !child.hidden)) ?? [];
}
function collectDefaultExpandedDetailKeys(items, level = 1) {
  const keys = [];
  items.filter((item) => !item.hidden).forEach((item) => {
    const children = normalizeVisibleDetailChildren(item.children);
    const canDefaultExpand = item.key !== void 0 && children.length > 0;
    if (canDefaultExpand && level <= 2) {
      keys.push(item.key);
    }
    if (children.length > 0 && level < 2) {
      keys.push(...collectDefaultExpandedDetailKeys(children, level + 1));
    }
  });
  return keys;
}
function uppercaseSectionLabel(label, locale) {
  return typeof label === "string" ? label.toLocaleUpperCase(locale) : label;
}
function toDecimal(value) {
  try {
    if (value instanceof import_decimal.default) return value;
    if (value === void 0 || value === null || value === "") {
      return new import_decimal.default(0);
    }
    return new import_decimal.default(value);
  } catch {
    return new import_decimal.default(0);
  }
}
function isNonZeroAmount(value) {
  return !toDecimal(value).isZero();
}
function formatMoney(value, symbol) {
  return (0, import_utils.formatAmount)(toDecimal(value).toString(), 2, symbol);
}
function formatNegativeMoney(value, symbol) {
  return formatMoney(toDecimal(value).abs().negated(), symbol);
}
function asRecords(value) {
  return Array.isArray(value) ? value.filter(
    (item) => !!item && typeof item === "object"
  ) : [];
}
function firstDefined(record, keys) {
  if (!record) return void 0;
  for (const key of keys) {
    const value = record[key];
    if (value !== void 0 && value !== null && value !== "") {
      return value;
    }
  }
  return void 0;
}
function getPaymentAmount(record) {
  return firstDefined(record, ["origin_amount", "amount"]);
}
function getPaymentSurchargeAmount(record) {
  return record.service_fee;
}
function isVoucherPaymentRecord(record) {
  return !!record.voucher_id;
}
function isRefundPaymentRecord(record) {
  const rawType = String(record.type || record.status || "").toLowerCase();
  return rawType.includes("refund") || toDecimal(getPaymentAmount(record)).lt(0);
}
function createDetailRow(key, label, value, options) {
  return {
    key,
    label,
    value,
    hidden: options == null ? void 0 : options.hidden,
    children: options == null ? void 0 : options.children,
    rowClassName: options == null ? void 0 : options.rowClassName
  };
}
function filterDetailItemsByKeys(items, visibleKeys) {
  if (!(visibleKeys == null ? void 0 : visibleKeys.size)) return items;
  return items.map((item) => {
    const itemKey = item.key === void 0 ? void 0 : String(item.key);
    const isDirectlyVisible = itemKey !== void 0 && visibleKeys.has(itemKey);
    if (isDirectlyVisible) {
      return item;
    }
    const children = item.children ? filterDetailItemsByKeys(item.children, visibleKeys) : void 0;
    const hasVisibleChildren = normalizeVisibleDetailChildren(children).length > 0;
    if (!hasVisibleChildren) {
      return {
        ...item,
        hidden: true,
        children
      };
    }
    return {
      ...item,
      children
    };
  }).filter((item) => !item.hidden);
}
function getSummaryAmount(summary, keys, fallback = 0) {
  return firstDefined(summary, keys) ?? fallback;
}
function getRefundTaxAmount(summary) {
  return getSummaryAmount(summary, [
    "refund_tax_fee",
    "tax_refund_amount",
    "gst_refund_amount",
    "refund_gst_amount"
  ]);
}
function getRefundNetAmount(summary) {
  const explicit = firstDefined(summary, [
    "net_refund_amount",
    "refund_net_amount"
  ]);
  if (explicit !== void 0) return explicit;
  return toDecimal(summary.total_refund_amount).minus(toDecimal(getRefundTaxAmount(summary))).toString();
}
function getBalanceDueAmount(summary, paymentStatus) {
  return String(paymentStatus ?? "").toLowerCase() === "payment_processing" ? summary.expect_amount : summary.amount_gap;
}
function getPaidExclPaymentSurchargeLabel(paymentSurchargeText) {
  const formatLabel = import_utils.locales.getText("pisell2.sale-detail.paid-excl-payment-sc");
  if (typeof formatLabel === "function") {
    return formatLabel(paymentSurchargeText);
  }
  return `${import_utils.locales.getText("pisell2.sale-detail.pay.paid")} (${paymentSurchargeText})`;
}
function buildPaymentRows(payments, paymentMethodNameMap, symbol, options) {
  return payments.filter((payment) => !isVoucherPaymentRecord(payment)).map((payment, index) => {
    const amount = getPaymentAmount(payment);
    const isRefund = isRefundPaymentRecord(payment);
    const serviceFee = getPaymentSurchargeAmount(payment);
    const lastDigits = String(
      firstDefined(payment, [
        "card_last_four",
        "card_last4",
        "last4",
        "last_digits"
      ]) ?? ""
    ).trim();
    const title = [
      options == null ? void 0 : options.labelPrefix,
      (0, import_usePaymentMethodNameMap.resolvePaymentMethodName)(payment, paymentMethodNameMap),
      lastDigits
    ].filter(Boolean).join(" ");
    return createDetailRow(
      `payment-${payment.order_payment_id || payment.id || index}`,
      title,
      formatMoney(
        isRefund ? toDecimal(amount).abs().negated() : amount,
        symbol
      ),
      {
        children: [
          createDetailRow(
            `payment-${index}-surcharge`,
            import_utils.locales.getText("pisell2.sale-detail.payment-surcharge"),
            formatMoney(serviceFee, symbol),
            {
              hidden: !isNonZeroAmount(serviceFee),
              rowClassName: PAYMENT_SURCHARGE_ROW_CLASS
            }
          )
        ]
      }
    );
  });
}
function buildDetailItems(options) {
  var _a;
  const {
    dataSource,
    detailOptions,
    fallbackPaymentMethodNameMap,
    fallbackSymbol,
    fallbackTranslationOriginal,
    locale
  } = options;
  const summary = dataSource.summary;
  if (!summary) return [];
  const symbol = dataSource.currencySymbol || fallbackSymbol;
  const translationOriginal = dataSource.translationOriginal ?? fallbackTranslationOriginal;
  const payments = asRecords(dataSource.payments);
  const paymentMethodNameMap = dataSource.paymentMethodNameMap ?? fallbackPaymentMethodNameMap;
  const surcharges = summary.surcharges ? summary.surcharges : [];
  const surchargeList = surcharges.filter((surcharge) => surcharge.name).map((surcharge) => ({
    key: `custom_surcharge_${surcharge.surcharge_id}`,
    value: firstDefined(surcharge, ["amount", "value"]),
    label: (translationOriginal == null ? void 0 : translationOriginal(surcharge.name)) || String(surcharge.name)
  }));
  const paymentRows = buildPaymentRows(
    payments.filter((payment) => !isRefundPaymentRecord(payment)),
    paymentMethodNameMap,
    symbol
  );
  const refundRows = buildPaymentRows(
    payments.filter(isRefundPaymentRecord),
    paymentMethodNameMap,
    symbol,
    { labelPrefix: import_utils.locales.getText("pisell2.sale-detail.refund-payment-prefix") }
  );
  const additionsSubtotal = surchargeList.reduce(
    (total, surcharge) => total.plus(toDecimal(surcharge.value)),
    new import_decimal.default(0)
  ).plus(toDecimal(summary.rounding_amount)).plus(toDecimal(summary.tax_fee));
  const balanceDueAmount = getBalanceDueAmount(
    summary,
    dataSource.paymentStatus
  );
  const paymentSurchargeAmount = summary.pay_service_charge_amount;
  const customerTotalPaid = toDecimal(summary.order_paid_amount).plus(
    toDecimal(paymentSurchargeAmount)
  );
  const totalRefundAmount = toDecimal(summary.total_refund_amount).abs();
  const paymentStatusPaidMode = (detailOptions == null ? void 0 : detailOptions.paymentStatusPaidMode) ?? "split";
  const visibleKeys = ((_a = detailOptions == null ? void 0 : detailOptions.visibleItemKeys) == null ? void 0 : _a.length) ? new Set(detailOptions.visibleItemKeys.map(String)) : void 0;
  const paymentStatusPaidRows = paymentStatusPaidMode === "combined" ? [
    createDetailRow(
      "payment-status-paid",
      getPaidExclPaymentSurchargeLabel(
        formatMoney(paymentSurchargeAmount, symbol)
      ),
      formatMoney(summary.order_paid_amount, symbol)
    )
  ] : [
    createDetailRow(
      "payment-status-paid",
      import_utils.locales.getText("pisell2.sale-detail.payment-applied"),
      formatMoney(summary.order_paid_amount, symbol)
    ),
    createDetailRow(
      "payment-status-surcharge",
      import_utils.locales.getText("pisell2.sale-detail.payment-surcharge"),
      formatMoney(paymentSurchargeAmount, symbol)
    )
  ];
  const items = [
    {
      key: "paymentStatus",
      rowClassName: SECTION_ROW_CLASS,
      label: uppercaseSectionLabel(
        import_utils.locales.getText("pisell2.sale-detail.payment-status"),
        locale
      ),
      children: [
        createDetailRow(
          "payment-status-total",
          import_utils.locales.getText("pisell2.sale-detail.total-amount"),
          formatMoney(summary.expect_amount, symbol)
        ),
        ...paymentStatusPaidRows,
        createDetailRow(
          "payment-status-refunded",
          import_utils.locales.getText("pisell2.sale-detail.refunded"),
          formatNegativeMoney(summary.total_refund_amount, symbol)
        ),
        createDetailRow(
          "payment-status-balance",
          import_utils.locales.getText("pisell2.sale-detail.balance-due"),
          formatMoney(balanceDueAmount, symbol)
        )
      ]
    },
    {
      key: "paymentAdditions",
      rowClassName: SECTION_ROW_CLASS,
      label: uppercaseSectionLabel(
        import_utils.locales.getText("pisell2.sale-detail.payment-additions"),
        locale
      ),
      children: [
        ...surchargeList.map(
          (surcharge) => createDetailRow(
            surcharge.key,
            surcharge.label,
            formatMoney(surcharge.value, symbol),
            { hidden: !isNonZeroAmount(surcharge.value) }
          )
        ),
        createDetailRow(
          "addition-rounding",
          import_utils.locales.getText("pisell2.sale-detail.rounding"),
          formatMoney(summary.rounding_amount, symbol)
        ),
        createDetailRow(
          "addition-tax",
          dataSource.taxTitle || summary.tax_title || import_utils.locales.getText("pisell2.sale-detail.tax"),
          formatMoney(summary.tax_fee, symbol)
        ),
        createDetailRow(
          "addition-subtotal",
          import_utils.locales.getText("pisell2.sale-detail.subtotal"),
          formatMoney(additionsSubtotal, symbol)
        )
      ]
    },
    createDetailRow(
      "payments-total-amount",
      uppercaseSectionLabel(
        import_utils.locales.getText("pisell2.sale-detail.total-amount"),
        locale
      ),
      formatMoney(summary.expect_amount, symbol),
      { rowClassName: SECTION_ROW_CLASS }
    ),
    {
      key: "payments",
      rowClassName: SECTION_ROW_CLASS,
      label: uppercaseSectionLabel(
        import_utils.locales.getText("pisell2.sale-detail.payments"),
        locale
      ),
      children: [
        ...paymentRows,
        createDetailRow(
          "payments-divider",
          "",
          "",
          { rowClassName: DIVIDER_ROW_CLASS }
        ),
        createDetailRow(
          "payments-applied-subtotal",
          import_utils.locales.getText("pisell2.sale-detail.total-payment-applied"),
          formatMoney(summary.order_paid_amount, symbol)
        ),
        createDetailRow(
          "payments-total-surcharge",
          import_utils.locales.getText("pisell2.sale-detail.total-payment-surcharge"),
          formatMoney(paymentSurchargeAmount, symbol)
        ),
        createDetailRow(
          "payments-customer-paid",
          import_utils.locales.getText("pisell2.sale-detail.customer-total-paid"),
          formatMoney(customerTotalPaid, symbol)
        )
      ]
    },
    {
      key: "refunds",
      rowClassName: SECTION_ROW_CLASS,
      label: uppercaseSectionLabel(
        import_utils.locales.getText("pisell2.sale-detail.refunds"),
        locale
      ),
      hidden: !refundRows.length && totalRefundAmount.isZero(),
      children: [
        ...refundRows,
        createDetailRow(
          "refund-net",
          import_utils.locales.getText("pisell2.sale-detail.net-refund"),
          formatNegativeMoney(getRefundNetAmount(summary), symbol)
        ),
        createDetailRow(
          "refund-tax",
          import_utils.locales.getText("pisell2.sale-detail.gst-refund-included"),
          formatNegativeMoney(getRefundTaxAmount(summary), symbol),
          { hidden: true }
        ),
        createDetailRow(
          "refund-subtotal",
          import_utils.locales.getText("pisell2.sale-detail.refund-subtotal"),
          formatNegativeMoney(summary.total_refund_amount, symbol)
        )
      ]
    },
    createDetailRow(
      "detail-balance-due",
      import_utils.locales.getText("pisell2.sale-detail.balance-due"),
      formatMoney(balanceDueAmount, symbol),
      { rowClassName: STANDALONE_ROW_CLASS }
    )
  ];
  return filterDetailItemsByKeys(items, visibleKeys);
}
var PisellSaleSummaryDetail = import_react.default.memo(({ dataSource, className, options }) => {
  var _a, _b, _c, _d, _e;
  (0, import_useInitLocalesOnce.default)(import_locales.default);
  const engineContext = (0, import_useEngineContext.default)();
  const paymentMethodNameMap = (0, import_usePaymentMethodNameMap.usePaymentMethodNameMap)();
  const [collapsedDefaultKeys, setCollapsedDefaultKeys] = (0, import_react.useState)([]);
  const [manualExpandedKeys, setManualExpandedKeys] = (0, import_react.useState)(
    []
  );
  const currentLocale = import_utils.locales.getLocale();
  const fallbackSymbol = ((_c = (_b = (_a = engineContext.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.getSymbolic) == null ? void 0 : _c.call(_b)) ?? "";
  const fallbackTranslationOriginal = (_e = (_d = engineContext.appHelper) == null ? void 0 : _d.utils) == null ? void 0 : _e.translationOriginal;
  const items = (0, import_react.useMemo)(
    () => buildDetailItems({
      dataSource: dataSource ?? {},
      detailOptions: options,
      fallbackPaymentMethodNameMap: paymentMethodNameMap,
      fallbackSymbol,
      fallbackTranslationOriginal,
      locale: currentLocale
    }),
    [
      currentLocale,
      dataSource,
      fallbackSymbol,
      fallbackTranslationOriginal,
      options,
      paymentMethodNameMap
    ]
  );
  const defaultExpandedKeys = (0, import_react.useMemo)(
    () => collectDefaultExpandedDetailKeys(items),
    [items]
  );
  const expandedKeys = (0, import_react.useMemo)(() => {
    const collapsedSet = new Set(collapsedDefaultKeys);
    const defaultSet = new Set(defaultExpandedKeys);
    const nextKeys = defaultExpandedKeys.filter(
      (key) => !collapsedSet.has(key)
    );
    manualExpandedKeys.forEach((key) => {
      if (!defaultSet.has(key)) {
        nextKeys.push(key);
      }
    });
    return nextKeys;
  }, [collapsedDefaultKeys, defaultExpandedKeys, manualExpandedKeys]);
  const handleExpandedKeysChange = (0, import_react.useCallback)(
    (keys) => {
      const expandedSet = new Set(keys);
      const defaultSet = new Set(defaultExpandedKeys);
      setCollapsedDefaultKeys(
        defaultExpandedKeys.filter((key) => !expandedSet.has(key))
      );
      setManualExpandedKeys(keys.filter((key) => !defaultSet.has(key)));
    },
    [defaultExpandedKeys]
  );
  return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(PREFIX, className) }, /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellHierarchicalSummaryList,
    {
      className: `${PREFIX}__list`,
      items: [
        {
          key: "summary-detail-root",
          label: "",
          children: items
        }
      ],
      expandedKeys,
      onExpandedKeysChange: handleExpandedKeysChange,
      indent: 26,
      rowGap: 4,
      padding: 0,
      levelConfig: SUMMARY_DETAIL_LEVEL_CONFIG,
      gaps: { row: 8, rowLeft: 6, rowRight: 6 }
    }
  ));
});
PisellSaleSummaryDetail.displayName = "PisellSaleSummaryDetail";
var pisellSaleSummaryDetail_default = PisellSaleSummaryDetail;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PisellSaleSummaryDetail
});
