var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/pisellReservation/hooks/useFloorMapBookingInteraction.ts
var useFloorMapBookingInteraction_exports = {};
__export(useFloorMapBookingInteraction_exports, {
  useFloorMapBookingInteraction: () => useFloorMapBookingInteraction
});
module.exports = __toCommonJS(useFloorMapBookingInteraction_exports);
var import_react = require("react");
var import_materials = require("@pisell/materials");
var import_reservationCards = require("../floorMap/reservationCards");
var import_floorMapHostCheckout = require("../floorMap/floorMapHostCheckout");
var import_calendarAdapter = require("../data/calendarAdapter");
var import_bookingToReservationTables = require("../data/bookingToReservationTables");
var import_mapRowToFloorRoomCardData = require("../floorRoomCard/mapRowToFloorRoomCardData");
var import_reservationTicketBookingHostParams = require("../utils/reservationTicketBookingHostParams");
function bookingOrderFinancialSig(raw) {
  const order = raw.order;
  const sum = order == null ? void 0 : order.summary;
  const products = raw.products;
  const productLineCount = Array.isArray(products) ? products.filter((x) => x && typeof x === "object").length : -1;
  return [
    String((sum == null ? void 0 : sum.total_amount) ?? ""),
    String((sum == null ? void 0 : sum.expect_amount) ?? ""),
    String((sum == null ? void 0 : sum.product_quantity) ?? ""),
    String(productLineCount)
  ].join(":");
}
function bookingPaymentStatusDisplaySig(raw) {
  const order = raw.order;
  const pay = (order == null ? void 0 : order.payment_status) ?? (order == null ? void 0 : order.order_payment_status) ?? raw.payment_status ?? raw.order_payment_status;
  return String(pay ?? "");
}
function bookingContactTiersSig(raw) {
  const tiers = (0, import_mapRowToFloorRoomCardData.resolveFloorRoomCardContactTiers)(raw);
  if (!(tiers == null ? void 0 : tiers.length)) return "";
  return tiers.map((t) => {
    const phone = t.phone != null && String(t.phone).trim() !== "" ? String(t.phone).trim() : "";
    return `${t.source}:${String(t.name ?? "").trim()}:${phone}`;
  }).join(">");
}
function bookingOrderCustomerIdSig(raw) {
  const order = raw.order;
  if (!order) return "";
  const top = order.customer_id;
  if (top != null && String(top).trim() !== "") return String(top);
  const c = order.customer;
  const id = c == null ? void 0 : c.id;
  return id != null && String(id).trim() !== "" ? String(id) : "";
}
function bookingAuxRealtimeSig(raw) {
  const order = raw.order;
  const resourceIds = (0, import_bookingToReservationTables.extractResourceRecordIds)(raw).sort().join(",");
  return [
    bookingContactTiersSig(raw),
    String(raw.number ?? ""),
    String(raw.notes ?? ""),
    String(raw.start_at ?? ""),
    String(raw.end_at ?? ""),
    String((order == null ? void 0 : order.schedule_date) ?? ""),
    bookingOrderCustomerIdSig(raw),
    String(raw.duration ?? ""),
    String(raw.sub_type ?? ""),
    resourceIds,
    String(raw.is_next ?? raw.isNext ?? ""),
    String(raw.lateTime ?? ""),
    String(raw.timeoutTime ?? ""),
    String(raw.remainingReserveTime ?? ""),
    String(raw.progressPercent ?? "")
  ].join("|");
}
function bookingRawRealtimeSig(raw) {
  var _a;
  return [
    String(raw.id ?? ""),
    String(raw.booking_id ?? raw.booking_uid ?? ""),
    String(raw.start_time ?? ""),
    String(raw.end_time ?? ""),
    String(raw.appointment_status ?? ""),
    String(raw.order_payment_status ?? ""),
    String(raw.status ?? ""),
    String(
      ((_a = raw.order) == null ? void 0 : _a.order_payment_status) ?? ""
    ),
    bookingPaymentStatusDisplaySig(raw),
    bookingOrderFinancialSig(raw),
    bookingAuxRealtimeSig(raw)
  ].join("|");
}
var SYNTHETIC_MOUSE_EVENT = {
  stopPropagation: () => {
  },
  preventDefault: () => {
  },
  nativeEvent: { stopImmediatePropagation: () => {
  } }
};
function useFloorMapBookingInteraction(options) {
  const {
    engineCtx,
    onFloorMapBookingClick,
    dataSources,
    mergedTableRows,
    reservationBiz,
    resourceSelectMode,
    associatedMenuListIds,
    reservationRuleProduct
  } = options;
  const [bookingDetailOpen, setBookingDetailOpen] = (0, import_react.useState)(false);
  const [readModeSelectedFloorItemId, setReadModeSelectedFloorItemId] = (0, import_react.useState)(null);
  const [bookingDetailRaw, setBookingDetailRaw] = (0, import_react.useState)(null);
  const [bookingDetailRow, setBookingDetailRow] = (0, import_react.useState)(null);
  const [bookingDetailSceneName, setBookingDetailSceneName] = (0, import_react.useState)(void 0);
  const bookingDetailRawRef = (0, import_react.useRef)(bookingDetailRaw);
  bookingDetailRawRef.current = bookingDetailRaw;
  const lastDetailSyncSigRef = (0, import_react.useRef)("");
  (0, import_react.useEffect)(() => {
    if (!bookingDetailOpen) {
      lastDetailSyncSigRef.current = "";
      setReadModeSelectedFloorItemId(null);
      return;
    }
    const cur = bookingDetailRawRef.current;
    if (!cur) return;
    const row = (0, import_calendarAdapter.findMergedTableRowForBookingRaw)(cur, mergedTableRows);
    if (!row) return;
    const fresh = (0, import_calendarAdapter.extractFloorMapSourceBookingForRow)(cur, row);
    if (!fresh) return;
    const sig = bookingRawRealtimeSig(fresh);
    if (sig === lastDetailSyncSigRef.current) return;
    lastDetailSyncSigRef.current = sig;
    setBookingDetailRaw(fresh);
    setBookingDetailRow(row);
  }, [bookingDetailOpen, mergedTableRows]);
  const closeBookingDetailNow = (0, import_react.useCallback)(() => {
    setBookingDetailOpen(false);
    setBookingDetailRaw(null);
    setBookingDetailRow(null);
    setBookingDetailSceneName(void 0);
  }, []);
  const closeBookingDetailModal = (0, import_react.useCallback)(
    (e) => {
      var _a, _b;
      e == null ? void 0 : e.stopPropagation();
      (_b = (_a = e == null ? void 0 : e.nativeEvent) == null ? void 0 : _a.stopImmediatePropagation) == null ? void 0 : _b.call(_a);
      window.setTimeout(() => {
        closeBookingDetailNow();
      }, 50);
    },
    [closeBookingDetailNow]
  );
  const showBookingDetail = (0, import_react.useCallback)(
    (opts) => {
      var _a, _b, _c, _d, _e, _f, _g, _h;
      const { rec, rowResolved, event, sceneElementName, floorMapItemId } = opts;
      const ev = event ?? SYNTHETIC_MOUSE_EVENT;
      const consumed = onFloorMapBookingClick == null ? void 0 : onFloorMapBookingClick({
        event: ev,
        raw: rec,
        row: rowResolved,
        dataSources,
        mode: "read"
      });
      if (consumed === true) return;
      const utils = (_a = engineCtx == null ? void 0 : engineCtx.appHelper) == null ? void 0 : _a.utils;
      const shopId = ((_b = utils == null ? void 0 : utils.getData) == null ? void 0 : _b.call(utils, "shop_id")) ?? ((_g = (_f = (_e = (_d = (_c = utils == null ? void 0 : utils.store) == null ? void 0 : _c.getState) == null ? void 0 : _d.call(_c)) == null ? void 0 : _e.global) == null ? void 0 : _f.globalConfig) == null ? void 0 : _g.id);
      const n = Number(shopId);
      const isLegacyCheckoutShop = Number.isFinite(n) && n === 2155;
      const recHasBooking = (() => {
        const rid = rec.id;
        const bid = rec.booking_id;
        return rid != null && String(rid).trim() !== "" || bid != null && String(bid).trim() !== "";
      })();
      if (isLegacyCheckoutShop && reservationBiz !== "dine_in" && recHasBooking) {
        (_h = utils == null ? void 0 : utils.action) == null ? void 0 : _h.call(utils, {
          type: "pisell1.handleOpenHostCheckoutDrawer",
          data: { item: rec }
        });
        return;
      }
      const sn = sceneElementName == null ? void 0 : sceneElementName.trim();
      setBookingDetailSceneName(sn && sn !== "" ? sn : void 0);
      lastDetailSyncSigRef.current = bookingRawRealtimeSig(rec);
      setBookingDetailRaw(rec);
      setBookingDetailRow(rowResolved);
      if (floorMapItemId != null && String(floorMapItemId).trim() !== "") {
        setReadModeSelectedFloorItemId(String(floorMapItemId));
      } else {
        setReadModeSelectedFloorItemId(null);
      }
      setBookingDetailOpen(true);
    },
    [dataSources, engineCtx, onFloorMapBookingClick]
  );
  const floorMapItemClickBefore = (0, import_react.useCallback)(
    (args) => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i;
      if (args.mode === "edit") return;
      const elementKind = args.item.elementKind ?? ((_a = args.item._sceneElement) == null ? void 0 : _a.elementKind);
      if (elementKind === import_materials.FLOOR_MAP_IMAGE_ELEMENT_KIND || elementKind === import_materials.FLOOR_MAP_BUILTIN_SHAPE_ELEMENT_KIND || elementKind === import_materials.FLOOR_MAP_STAGE_ELEMENT_KIND) {
        return;
      }
      const rowHit = (0, import_reservationCards.findReservationRow)(args.item, args.dataSources);
      if (resourceSelectMode == null ? void 0 : resourceSelectMode.enabled) {
        const rowResolved2 = rowHit ?? {
          id: String(
            ((_c = (_b = args.item._sceneElement) == null ? void 0 : _b.dataBinding) == null ? void 0 : _c.recordId) ?? args.item.id ?? "unknown"
          ),
          code: ((_d = args.item._sceneElement) == null ? void 0 : _d.name) != null ? String(args.item._sceneElement.name) : "—",
          cardStatus: "available"
        };
        resourceSelectMode.onSelectResource({
          item: args.item,
          row: rowResolved2,
          resource: {
            id: rowResolved2.id,
            relation_id: rowResolved2.id,
            form_id: rowResolved2.form_id,
            code: rowResolved2.code,
            main_field: rowResolved2.main_field,
            raw: rowResolved2
          }
        });
        return;
      }
      const list = rowHit == null ? void 0 : rowHit.floorMapSourceBookings;
      const rec = (0, import_floorMapHostCheckout.resolveFloorMapHostCheckoutRecord)(args.event, list);
      const recHasValidBooking = (() => {
        if (!rec || typeof rec !== "object") return false;
        const rid = rec.id;
        const bid = rec.booking_id;
        return rid != null && String(rid).trim() !== "" || bid != null && String(bid).trim() !== "";
      })();
      const rowResolved = rowHit ?? {
        id: String(
          ((_f = (_e = args.item._sceneElement) == null ? void 0 : _e.dataBinding) == null ? void 0 : _f.recordId) ?? "unknown"
        ),
        code: ((_g = args.item._sceneElement) == null ? void 0 : _g.name) != null ? String(args.item._sceneElement.name) : "—",
        cardStatus: "available"
      };
      const sceneName = ((_h = args.item._sceneElement) == null ? void 0 : _h.name) != null ? String(args.item._sceneElement.name).trim() : void 0;
      const rowBookingCount = typeof (rowHit == null ? void 0 : rowHit.bookingCount) === "number" && Number.isFinite(rowHit.bookingCount) ? rowHit.bookingCount : 0;
      if (!recHasValidBooking && rowBookingCount === 0) {
        const consumed = onFloorMapBookingClick == null ? void 0 : onFloorMapBookingClick({
          event: args.event,
          raw: {},
          row: rowResolved,
          dataSources: args.dataSources,
          mode: "read"
        });
        if (consumed === true) return;
        (0, import_reservationTicketBookingHostParams.openNewReservationBookingFromHost)({
          appHelperUtils: (_i = engineCtx == null ? void 0 : engineCtx.appHelper) == null ? void 0 : _i.utils,
          reservationBiz,
          associatedMenuListIds,
          reservationRuleProduct,
          row: rowResolved
        });
        return;
      }
      const recForDetail = recHasValidBooking ? rec : {};
      showBookingDetail({
        rec: recForDetail,
        rowResolved,
        event: args.event,
        sceneElementName: sceneName,
        floorMapItemId: String(args.item.id)
      });
    },
    [
      showBookingDetail,
      resourceSelectMode,
      onFloorMapBookingClick,
      engineCtx,
      reservationBiz,
      associatedMenuListIds,
      reservationRuleProduct
    ]
  );
  const openBookingDetailFromRaw = (0, import_react.useCallback)(
    (payload) => {
      const rec = payload.raw;
      const rid = rec.id;
      const bid = rec.booking_id;
      const hasId = rid != null && String(rid).trim() !== "" || bid != null && String(bid).trim() !== "";
      if (!hasId) return;
      const rowResolved = payload.row ?? {
        id: String(rid ?? bid ?? "unknown"),
        code: String(rec.relation_form_name ?? bid ?? "—"),
        cardStatus: "booked"
      };
      showBookingDetail({
        rec,
        rowResolved,
        sceneElementName: payload.sceneElementName
      });
    },
    [showBookingDetail]
  );
  return {
    bookingDetailOpen,
    bookingDetailRaw,
    bookingDetailRow,
    bookingDetailSceneName,
    readModeSelectedFloorItemId,
    closeBookingDetailModal,
    closeBookingDetailNow,
    floorMapItemClickBefore,
    openBookingDetailFromRaw
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useFloorMapBookingInteraction
});
