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/pisellReservation/components/bookingDetailModal/bookingDetailFromRaw.ts
var bookingDetailFromRaw_exports = {};
__export(bookingDetailFromRaw_exports, {
  bookingDetailFromRaw: () => bookingDetailFromRaw,
  bookingDetailOrderStripFromRaw: () => bookingDetailOrderStripFromRaw,
  isBookingRawOrderPaid: () => isBookingRawOrderPaid
});
module.exports = __toCommonJS(bookingDetailFromRaw_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_mapRowToFloorRoomCardData = require("../../floorRoomCard/mapRowToFloorRoomCardData");
var import_floorRoomCardUtils = require("../../floorRoomCard/floorRoomCardUtils");
function str(v) {
  if (v == null) return "";
  const s = String(v).trim();
  return s;
}
function isBookingRawOrderPaid(raw) {
  const order = raw.order;
  const fromOrder = order == null ? void 0 : order.payment_status;
  const fromTop = raw.payment_status;
  const v = fromOrder != null && String(fromOrder).trim() !== "" ? fromOrder : fromTop;
  return String(v ?? "").trim().toLowerCase() === "paid";
}
function pickTitle(raw, order) {
  const rf = str(raw.relation_form_name);
  if (rf) return rf;
  const on = str(order.name ?? order.title ?? order.order_name);
  if (on) return on;
  const meta = raw.metadata;
  if (meta && typeof meta === "object") {
    const t = str(meta.title ?? meta.product_name);
    if (t) return t;
  }
  return "";
}
function formatMoney(v) {
  if (v == null || v === "") return "";
  if (typeof v === "number" && Number.isFinite(v)) return String(v);
  return str(v);
}
function buildTimeRange(raw, order) {
  const startAt = raw.start_at ?? order.start_at;
  const endAt = raw.end_at ?? order.end_at;
  if (startAt || endAt) {
    const a = startAt ? (0, import_dayjs.default)(String(startAt)) : null;
    const b = endAt ? (0, import_dayjs.default)(String(endAt)) : null;
    if ((a == null ? void 0 : a.isValid()) && (b == null ? void 0 : b.isValid())) {
      if (a.isSame(b, "day")) {
        return `${a.format("HH:mm")} – ${b.format("HH:mm")} · ${a.format(
          "D MMM"
        )}`;
      }
      return `${a.format("HH:mm")} – ${b.format("HH:mm")} · ${a.format(
        "D MMM YYYY"
      )}`;
    }
    if (a == null ? void 0 : a.isValid()) return a.format("YYYY-MM-DD HH:mm");
  }
  const sd = str(raw.start_date);
  const st = str(raw.start_time);
  const ed = str(raw.end_date);
  const et = str(raw.end_time);
  if (sd && st && ed && et) {
    return `${st} – ${et} ${sd}`;
  }
  if (sd && st) return `${sd} ${st}`;
  const sched = str(order.schedule_date);
  if (sched) return sched;
  return "—";
}
function pickStaff(raw, order) {
  var _a, _b;
  const s = str(raw.staff_name) || str(raw.assignee_name) || str(order.staff_name) || str((_a = order.staff) == null ? void 0 : _a.name) || str((_b = raw.staff) == null ? void 0 : _b.name);
  return s || void 0;
}
function pickStatusBadge(raw) {
  const s = str(raw.status);
  if (!s) return void 0;
  const k = s.toLowerCase().replace(/\s+/g, "_");
  const successKeys = /* @__PURE__ */ new Set([
    "started",
    "confirmed",
    "active",
    "checked_in",
    "checkin",
    "in_progress"
  ]);
  const warningKeys = /* @__PURE__ */ new Set([
    "pending",
    "pending_payment",
    "draft",
    "waiting",
    "hold"
  ]);
  const dangerKeys = /* @__PURE__ */ new Set(["cancelled", "canceled", "void", "refunded"]);
  let variant = "neutral";
  if (successKeys.has(k)) variant = "success";
  else if (warningKeys.has(k)) variant = "warning";
  else if (dangerKeys.has(k)) variant = "danger";
  return {
    labelKey: `pisell-reservation.booking-detail.status-enum.${k}`,
    variant
  };
}
function titleCaseStatusWords(s) {
  return s.split(/[_\s\-]+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(" ");
}
function roomTitleFromRow(row) {
  if (!row) return void 0;
  const parts = [row.code, row.main_field].filter((x) => x && String(x).trim());
  return parts.length ? parts.join(" · ") : void 0;
}
function roomCapacityFromRow(row) {
  if (!(row == null ? void 0 : row.capacityLabel)) return void 0;
  const c = String(row.capacityLabel).trim();
  return c || void 0;
}
function floorRoomCardGuestHeadline(holder) {
  var _a;
  if (!holder) return "";
  const n = (_a = holder.name) == null ? void 0 : _a.trim();
  if (n) return n;
  if (holder.phone) {
    const m = (0, import_floorRoomCardUtils.maskPisellReservationPhoneTail)(holder.phone);
    return m || "";
  }
  return "";
}
function parseQuantity(v) {
  if (v == null || v === "") return null;
  if (typeof v === "number" && Number.isFinite(v)) return Math.max(0, Math.round(v));
  const n = Number(String(v).replace(/,/g, "").trim());
  return Number.isFinite(n) ? Math.max(0, Math.round(n)) : null;
}
function orderCurrencySymbol(order) {
  const s = str(order.currency_symbol);
  if (s) return s;
  return "$";
}
function moneyWithSymbol(symbol, amount) {
  const f = formatMoney(amount);
  if (!f) return `${symbol}—`;
  if (f.startsWith(symbol) || f.startsWith("$") || f.startsWith("¥") || f.startsWith("€"))
    return f;
  return `${symbol}${f}`;
}
function buildStripScheduleLine(raw, order) {
  const startAt = raw.start_at ?? order.start_at;
  const endAt = raw.end_at ?? order.end_at;
  if (startAt || endAt) {
    const a = startAt ? (0, import_dayjs.default)(String(startAt)) : null;
    const b = endAt ? (0, import_dayjs.default)(String(endAt)) : null;
    if ((a == null ? void 0 : a.isValid()) && (b == null ? void 0 : b.isValid())) {
      return `${a.format("HH:mm")} ${a.format("D MMM")} ~ ${b.format("HH:mm")} ${b.format("D MMM")}`;
    }
    if (a == null ? void 0 : a.isValid()) return `${a.format("HH:mm")} ${a.format("D MMM")}`;
  }
  const sd = str(raw.start_date);
  const st = str(raw.start_time);
  const ed = str(raw.end_date);
  const et = str(raw.end_time);
  if (sd && st && ed && et) {
    const padTime = (t) => t.length === 5 ? `${t}:00` : t;
    const a = (0, import_dayjs.default)(`${sd}T${padTime(st)}`);
    const b = (0, import_dayjs.default)(`${ed}T${padTime(et)}`);
    if (a.isValid() && b.isValid()) {
      return `${a.format("HH:mm")} ${a.format("D MMM")} ~ ${b.format("HH:mm")} ${b.format("D MMM")}`;
    }
  }
  return buildTimeRange(raw, order);
}
function countTopLevelProductLines(raw) {
  const p = raw.products;
  if (!Array.isArray(p)) return null;
  return p.filter((x) => x && typeof x === "object").length;
}
function bookingDetailOrderStripFromRaw(raw) {
  const order = raw.order ?? {};
  const sum = order.summary;
  const sym = orderCurrencySymbol(order);
  const eyebrow = str(raw.relation_form_name) || pickTitle(raw, order) || str(raw.booking_id) || "—";
  const stripBookingId = (0, import_mapRowToFloorRoomCardData.resolveBookingStripIdForUi)(raw);
  const itemsCount = countTopLevelProductLines(raw) ?? parseQuantity(sum == null ? void 0 : sum.product_quantity);
  const orderTotalWithSymbol = moneyWithSymbol(sym, sum == null ? void 0 : sum.total_amount);
  const payRaw = order.payment_status ?? raw.payment_status;
  const paymentStatusRaw = payRaw != null && String(payRaw).trim() !== "" ? String(payRaw).trim() : void 0;
  const dueBase = (sum == null ? void 0 : sum.expect_amount) ?? (sum == null ? void 0 : sum.total_amount);
  const dueWithSymbol = moneyWithSymbol(sym, dueBase);
  return {
    eyebrow,
    stripBookingId,
    scheduleLine: buildStripScheduleLine(raw, order),
    itemsCount,
    orderTotalWithSymbol,
    paymentStatusRaw,
    dueWithSymbol
  };
}
function bookingDetailFromRaw(raw, roomRow) {
  var _a;
  const order = raw.order ?? {};
  const bid = raw.booking_id ?? raw.id;
  const bookingIdLabel = bid != null && String(bid) !== "" ? String(bid) : "—";
  const title = pickTitle(raw, order) || bookingIdLabel;
  const holderResolved = (0, import_mapRowToFloorRoomCardData.resolveFloorRoomCardHolder)(raw);
  const contactName = ((_a = holderResolved == null ? void 0 : holderResolved.name) == null ? void 0 : _a.trim()) || void 0;
  const contactPhone = holderResolved == null ? void 0 : holderResolved.phone;
  const guestHeadline = floorRoomCardGuestHeadline(holderResolved);
  const payRaw = order.payment_status ?? raw.payment_status;
  const payLower = payRaw != null && String(payRaw).trim() !== "" ? String(payRaw).trim().toLowerCase() : "";
  const displayAmt = (0, import_mapRowToFloorRoomCardData.resolveBookingCardAmount)(raw, order, payLower);
  const totalAmountLabel = displayAmt != null && String(displayAmt) !== "" ? formatMoney(displayAmt) : void 0;
  const paymentStatusRaw = payRaw != null && String(payRaw).trim() !== "" ? String(payRaw).trim() : void 0;
  const bk = (0, import_mapRowToFloorRoomCardData.rawToBooking)(raw, 0);
  const reservedCountdownMinutes = (0, import_floorRoomCardUtils.resolveFloorRoomCardReservedCountdownMinutesForBooking)(bk);
  const progressPercent = (0, import_floorRoomCardUtils.resolveFloorRoomCardProgressPercent)(bk);
  const badge = pickStatusBadge(raw);
  const statusStr = str(raw.status);
  let statusBadgeLabel;
  let statusBadgeVariant;
  if (statusStr && badge) {
    statusBadgeVariant = badge.variant;
    const localized = import_utils.locales.getText(badge.labelKey);
    statusBadgeLabel = localized && localized !== badge.labelKey ? localized : titleCaseStatusWords(statusStr);
  }
  return {
    bookingIdLabel,
    internalId: raw.id,
    statusRaw: statusStr || void 0,
    statusBadgeLabel,
    statusBadgeVariant,
    title,
    contactName: contactName || void 0,
    contactPhone,
    guestHeadline,
    timeRangeLabel: buildTimeRange(raw, order),
    staffLabel: pickStaff(raw, order),
    paymentStatusRaw,
    totalAmountLabel,
    partySize: bk.number,
    startDisplay: `${bk.start_date} ${bk.start_time}`.trim(),
    endDisplay: `${bk.end_date} ${bk.end_time}`.trim(),
    cardAmount: bk.amount,
    lateTimeMinutes: bk.lateTime != null && bk.lateTime > 0 ? bk.lateTime : void 0,
    timeoutTimeMinutes: bk.timeoutTime != null && bk.timeoutTime > 0 ? bk.timeoutTime : void 0,
    reservedCountdownMinutes,
    progressPercent,
    hostBookingStatus: bk.hostBookingStatus,
    roomCapacityLabel: roomCapacityFromRow(roomRow),
    roomTitleLabel: roomTitleFromRow(roomRow)
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  bookingDetailFromRaw,
  bookingDetailOrderStripFromRaw,
  isBookingRawOrderPaid
});
