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/venueBooking/components/Checkout/index.tsx
var Checkout_exports = {};
__export(Checkout_exports, {
  default: () => Checkout
});
module.exports = __toCommonJS(Checkout_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_hooks = require("../../hooks");
var import_context = require("../../context");
function Checkout() {
  const symbol = (0, import_hooks.useVenueBookingSymbol)();
  const {
    viewModel,
    goToStep,
    updateOrderNote,
    runModuleAction
  } = (0, import_context.useVenueBookingContext)();
  const [contactForm] = import_antd.Form.useForm();
  const [noteValue, setNoteValue] = (0, import_react.useState)(String(viewModel.note || ""));
  const lastContactsSignatureRef = (0, import_react.useRef)("[]");
  const lastNoteRef = (0, import_react.useRef)(String(viewModel.note || ""));
  const bookingSubtotal = (0, import_react.useMemo)(() => {
    var _a;
    return Number(((_a = viewModel.summary) == null ? void 0 : _a.product_amount) ?? 0);
  }, [viewModel.summary]);
  const grandTotal = (0, import_react.useMemo)(() => {
    var _a, _b;
    return Number(
      ((_a = viewModel.summary) == null ? void 0 : _a.total_amount) ?? ((_b = viewModel.summary) == null ? void 0 : _b.expect_amount) ?? 0
    );
  }, [viewModel.summary]);
  const venueCartItems = (0, import_react.useMemo)(() => {
    return (viewModel.cartItems || []).filter((item) => Boolean((item == null ? void 0 : item.start_date) && (item == null ? void 0 : item.end_date)));
  }, [viewModel.cartItems]);
  const addonCartItems = (0, import_react.useMemo)(() => {
    return (viewModel.cartItems || []).filter((item) => !(item == null ? void 0 : item.start_date) || !(item == null ? void 0 : item.end_date));
  }, [viewModel.cartItems]);
  const addonTotal = (0, import_react.useMemo)(() => {
    return addonCartItems.reduce((sum, item) => sum + getItemLineTotal(item), 0);
  }, [addonCartItems]);
  const mergedCourtSessionLines = (0, import_react.useMemo)(() => {
    return venueCartItems.map((item, index) => {
      const resourceName = getVenueResourceName(item);
      const sessionText = getSessionDisplayText(item);
      const courtLabel = String(resourceName || `场地 ${index + 1}`);
      return `${courtLabel} ${sessionText}`;
    });
  }, [venueCartItems]);
  const contactFormConfig = (0, import_react.useMemo)(() => ({
    first_name: {
      visible: true,
      required: false
    },
    last_name: {
      visible: true,
      required: false
    },
    phone: {
      visible: true,
      required: false
    },
    email: {
      visible: false,
      required: false
    }
  }), []);
  const syncContactsInfo = (0, import_react.useCallback)(async () => {
    const formValues = contactForm.getFieldsValue();
    const nextContactsInfo = toContactsInfoPayload(formValues);
    const nextSignature = JSON.stringify(nextContactsInfo);
    if (nextSignature === lastContactsSignatureRef.current) return;
    lastContactsSignatureRef.current = nextSignature;
    await runModuleAction("updateTempOrderContactsInfo", nextContactsInfo);
  }, [contactForm, runModuleAction]);
  const handleContactBlur = (0, import_react.useCallback)(() => {
    void syncContactsInfo();
  }, [syncContactsInfo]);
  const handleNoteBlur = (0, import_react.useCallback)(async () => {
    if (noteValue === lastNoteRef.current) return;
    lastNoteRef.current = noteValue;
    await updateOrderNote(noteValue);
  }, [noteValue, updateOrderNote]);
  (0, import_react.useEffect)(() => {
    const formValues = toContactFormValues(viewModel.contactsInfo);
    contactForm.setFieldsValue(formValues);
    lastContactsSignatureRef.current = JSON.stringify(toContactsInfoPayload(formValues));
  }, [contactForm, viewModel.contactsInfo]);
  (0, import_react.useEffect)(() => {
    const nextNote = String(viewModel.note || "");
    setNoteValue(nextNote);
    lastNoteRef.current = nextNote;
  }, [viewModel.note]);
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "space-y-3 md:space-y-5" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "grid gap-3 md:gap-4" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "rounded-[22px] bg-white p-4 shadow-[0_10px_40px_rgba(20,20,20,0.06)] ring-1 ring-black/6 md:rounded-[28px] md:p-6" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { className: "mt-3 text-[22px] font-extrabold text-zinc-900" }, import_utils.locales.getText("pisell2.venue.checkout.court.summary") || "场地预订摘要"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "rounded-[22px] bg-[#faf7f4] p-4 ring-1 ring-black/6 md:col-span-2" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "text-sm font-semibold text-[#a69183]" }, import_utils.locales.getText("pisell2.venue.checkout.selected.courts") || "已选场地"), /* @__PURE__ */ import_react.default.createElement("div", { className: "mt-3 space-y-2 text-[15px] font-semibold text-zinc-900" }, mergedCourtSessionLines.length ? mergedCourtSessionLines.map((line, idx) => /* @__PURE__ */ import_react.default.createElement("div", { key: `venue-session-line-${idx}` }, line)) : /* @__PURE__ */ import_react.default.createElement("div", null, import_utils.locales.getText("pisell2.venue.checkout.sessions.empty") || "-"))), addonCartItems.length > 0 ? /* @__PURE__ */ import_react.default.createElement("div", { className: "rounded-[22px] bg-[#faf7f4] p-4 ring-1 ring-black/6" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "text-sm font-semibold text-[#a69183]" }, import_utils.locales.getText("pisell2.venue.checkout.addons") || "附加项"), /* @__PURE__ */ import_react.default.createElement("div", { className: "mt-3 text-[15px] font-semibold text-zinc-900" }, addonCartItems.map((item, idx) => /* @__PURE__ */ import_react.default.createElement("div", { key: `addon-${item.id || idx}` }, item.title || item.name || "-")))) : null)), /* @__PURE__ */ import_react.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "rounded-[28px] bg-white p-5 shadow-[0_10px_40px_rgba(20,20,20,0.06)] ring-1 ring-black/6 md:p-6" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "mt-5 rounded-[22px] bg-[#faf7f4] p-4 ring-1 ring-black/6" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "text-lg font-bold text-zinc-900" }, import_utils.locales.getText("pisell2.venue.checkout.notice") || "备注"), /* @__PURE__ */ import_react.default.createElement(
    "textarea",
    {
      className: "mt-4 min-h-[120px] w-full rounded-[20px] border border-black/10 bg-white px-4 py-4 text-sm outline-none placeholder:text-zinc-400",
      value: noteValue,
      onChange: (e) => setNoteValue(e.target.value),
      placeholder: String(import_utils.locales.getText("pisell2.venue.note.placeholder") || "特殊要求..."),
      onBlur: () => {
        void handleNoteBlur();
      }
    }
  ))))));
}
function normalizeCountryCallingCode(code) {
  const value = String(code || "").trim();
  if (!value) return "";
  return value.startsWith("+") ? value : `+${value}`;
}
function toContactFormValues(contactsInfoList) {
  var _a, _b, _c;
  const contactInfo = Array.isArray(contactsInfoList) ? contactsInfoList[0] : null;
  if (!contactInfo || typeof contactInfo !== "object") {
    return {
      first_name: "",
      last_name: "",
      email: "",
      phone: {
        phone: "",
        countryCallingCode: "",
        countryCode: ""
      }
    };
  }
  return {
    first_name: String((contactInfo == null ? void 0 : contactInfo.first_name) || ""),
    last_name: String((contactInfo == null ? void 0 : contactInfo.last_name) || ""),
    email: String((contactInfo == null ? void 0 : contactInfo.email) || ""),
    phone: {
      phone: String(((_a = contactInfo == null ? void 0 : contactInfo.phone) == null ? void 0 : _a.phone) || ""),
      countryCallingCode: normalizeCountryCallingCode((_b = contactInfo == null ? void 0 : contactInfo.phone) == null ? void 0 : _b.country_calling_code),
      countryCode: String(((_c = contactInfo == null ? void 0 : contactInfo.phone) == null ? void 0 : _c.country_code) || "")
    }
  };
}
function toContactsInfoPayload(formValues) {
  var _a, _b, _c;
  const firstName = String((formValues == null ? void 0 : formValues.first_name) || "").trim();
  const lastName = String((formValues == null ? void 0 : formValues.last_name) || "").trim();
  const email = String((formValues == null ? void 0 : formValues.email) || "").trim();
  const phoneValue = String(((_a = formValues == null ? void 0 : formValues.phone) == null ? void 0 : _a.phone) || "").trim();
  const countryCallingCode = String(((_b = formValues == null ? void 0 : formValues.phone) == null ? void 0 : _b.countryCallingCode) || "").trim();
  const countryCode = String(((_c = formValues == null ? void 0 : formValues.phone) == null ? void 0 : _c.countryCode) || "").trim();
  const hasAnyValue = Boolean(firstName || lastName || email || phoneValue || countryCallingCode || countryCode);
  if (!hasAnyValue) return [];
  const displayName = `${firstName} ${lastName}`.trim();
  return [
    {
      first_name: firstName,
      last_name: lastName,
      display_name: displayName,
      email,
      phone: {
        phone: phoneValue,
        country_calling_code: countryCallingCode,
        country_code: countryCode
      }
    }
  ];
}
function applyI18nPlaceholders(template, vars) {
  let result = template;
  for (const [key, value] of Object.entries(vars)) {
    result = result.split(`{${key}}`).join(String(value));
  }
  return result;
}
function formatCheckoutDurationText(totalMinutes) {
  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;
  if (hours > 0 && minutes > 0) {
    const tpl2 = String(
      import_utils.locales.getText("pisell2.venue.checkout.duration.hours_minutes") || "{hours}h {minutes}min"
    );
    return applyI18nPlaceholders(tpl2, { hours, minutes });
  }
  if (hours > 0) {
    const tpl2 = String(
      import_utils.locales.getText("pisell2.venue.checkout.duration.hours") || "{hours}h"
    );
    return applyI18nPlaceholders(tpl2, { hours });
  }
  const tpl = String(
    import_utils.locales.getText("pisell2.venue.checkout.duration.minutes") || "{minutes}min"
  );
  return applyI18nPlaceholders(tpl, { minutes });
}
function getSessionDisplayText(item) {
  const startRaw = String((item == null ? void 0 : item.start_date) || "");
  const endRaw = String((item == null ? void 0 : item.end_date) || "");
  const start = (0, import_dayjs.default)(startRaw);
  const end = (0, import_dayjs.default)(endRaw);
  if (!start.isValid() || !end.isValid())
    return String((item == null ? void 0 : item.description) || (item == null ? void 0 : item.subtitle) || "-");
  const durationMinutes = Math.max(0, end.diff(start, "minute"));
  const durationText = formatCheckoutDurationText(durationMinutes);
  return `${start.format("HH:mm")} ~ ${end.format("HH:mm")} ${start.format("DD/MM/YYYY")} (${durationText})`;
}
function getVenueResourceName(item) {
  var _a, _b;
  const relationFormName = String((item == null ? void 0 : item.relation_form_name) || "").trim();
  if (relationFormName) return relationFormName;
  const resourceMainField = String(((_b = (_a = item == null ? void 0 : item.resources) == null ? void 0 : _a[0]) == null ? void 0 : _b.main_field) || "").trim();
  if (resourceMainField) return resourceMainField;
  const fallbackTitle = String((item == null ? void 0 : item.title) || (item == null ? void 0 : item.name) || "").trim();
  if (fallbackTitle) return fallbackTitle;
  return "";
}
function getItemLineTotal(item) {
  const quantity = Number.isNaN(Number(item == null ? void 0 : item.num)) ? 1 : Math.max(1, Math.floor(Number(item == null ? void 0 : item.num)));
  const price = Number(item == null ? void 0 : item.price);
  if (!Number.isNaN(price)) return price * quantity;
  const total = Number(item == null ? void 0 : item.total);
  if (!Number.isNaN(total)) return total;
  return 0;
}
