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/hooks/useReservationSalesHostData.ts
var useReservationSalesHostData_exports = {};
__export(useReservationSalesHostData_exports, {
  useReservationSalesHostData: () => useReservationSalesHostData
});
module.exports = __toCommonJS(useReservationSalesHostData_exports);
var import_react = require("react");
var import_dayjs = __toESM(require("dayjs"));
var import_reservationDensity = require("../data/reservationDensity");
var import_reservationTablesMerge = require("../data/reservationTablesMerge");
function useReservationSalesHostData(options) {
  const {
    isInternalListData,
    pisellosRef,
    hasPisellosGetModule,
    debouncedSchedule,
    followWallClock,
    resourceBoardLoading,
    floorDayBookingLoading,
    floorDayBookingData,
    floorDayBookingDataVersion,
    scheduleDate,
    timeNavigatorPropsProp,
    timelineRange,
    operatingDayBoundary
  } = options;
  const [salesResourceBookings, setSalesResourceBookings] = (0, import_react.useState)(null);
  const salesBookingRequestRef = (0, import_react.useRef)(0);
  const resourceListHostSkipRef = (0, import_react.useRef)(false);
  const resourceListRetryGateRef = (0, import_react.useRef)("");
  const debouncedAtMs = (debouncedSchedule == null ? void 0 : debouncedSchedule.at) != null && (0, import_dayjs.default)(debouncedSchedule.at).isValid() ? (0, import_dayjs.default)(debouncedSchedule.at).valueOf() : null;
  const floorDayBookingDepKey = (0, import_react.useMemo)(() => {
    const d = floorDayBookingData;
    if (!Array.isArray(d) || d.length === 0) {
      return "__empty__";
    }
    let h = 5381;
    const accChar = (s) => {
      for (let i = 0; i < s.length; i++) {
        h = (h << 5) + h ^ s.charCodeAt(i) | 0;
      }
      h = (h << 5) + h + 31 | 0;
    };
    for (let i = 0; i < d.length; i++) {
      const row = d[i];
      if (!row) {
        accChar("null");
        continue;
      }
      accChar(String(row.booking_id ?? row.id ?? row.bookingId ?? ""));
      accChar(String(row.status ?? ""));
      accChar(String(row.start_time ?? row.start_date ?? ""));
      accChar(String(row.end_time ?? row.end_date ?? ""));
      const order = row.order;
      accChar(String((order == null ? void 0 : order.payment_status) ?? row.order_payment_status ?? ""));
    }
    return `${d.length}:${h}`;
  }, [floorDayBookingData]);
  const floorDayBookingDataRef = (0, import_react.useRef)(floorDayBookingData);
  floorDayBookingDataRef.current = floorDayBookingData;
  (0, import_react.useEffect)(() => {
    const pisellosNow = pisellosRef.current;
    if (!isInternalListData) {
      setSalesResourceBookings((p) => p == null ? p : null);
      return;
    }
    if (!(pisellosNow == null ? void 0 : pisellosNow.getModule)) {
      setSalesResourceBookings((p) => p == null ? p : null);
      return;
    }
    if (!(debouncedSchedule == null ? void 0 : debouncedSchedule.at) || !(0, import_dayjs.default)(debouncedSchedule.at).isValid()) {
      return;
    }
    if (resourceBoardLoading || floorDayBookingLoading) {
      return;
    }
    const list = floorDayBookingDataRef.current;
    if (!Array.isArray(list)) {
      return;
    }
    const retryGateKey = `${debouncedAtMs ?? "na"}|${floorDayBookingDepKey}|v${floorDayBookingDataVersion}|${hasPisellosGetModule ? 1 : 0}|fw${followWallClock ? 1 : 0}`;
    if (retryGateKey !== resourceListRetryGateRef.current) {
      resourceListRetryGateRef.current = retryGateKey;
      resourceListHostSkipRef.current = false;
    }
    if (resourceListHostSkipRef.current) {
      return;
    }
    let salesModule;
    try {
      salesModule = pisellosNow.getModule("sales");
    } catch {
      setSalesResourceBookings((p) => p == null ? p : null);
      return;
    }
    const fn = salesModule == null ? void 0 : salesModule.getResourceBookingList;
    if (typeof fn !== "function") {
      setSalesResourceBookings((p) => p == null ? p : null);
      return;
    }
    const reqId = ++salesBookingRequestRef.current;
    const resourceBookingListTimeFormat = "YYYY-MM-DD HH:mm";
    const timeStr = (0, import_dayjs.default)(debouncedSchedule.at).format(
      resourceBookingListTimeFormat
    );
    const currentTimeStr = followWallClock ? timeStr : (0, import_dayjs.default)().format(resourceBookingListTimeFormat);
    const applyHostList = (raw) => {
      if (salesBookingRequestRef.current !== reqId) return;
      const normalized = (0, import_reservationTablesMerge.normalizeSalesResourceBookingListResult)(raw);
      setSalesResourceBookings(normalized);
      resourceListHostSkipRef.current = false;
    };
    const revertToLocalFilter = () => {
      if (salesBookingRequestRef.current !== reqId) return;
      setSalesResourceBookings((p) => p == null ? p : null);
    };
    try {
      const result = fn.call(salesModule, timeStr, list, currentTimeStr);
      if (result != null && typeof result.then === "function") {
        result.then(applyHostList).catch((e) => {
          resourceListHostSkipRef.current = true;
          if (process.env.NODE_ENV !== "production") {
            console.warn(
              "[PisellReservation] sales.getResourceBookingList rejected（非宿主或 sales 未就绪时将不再重试，直至日程或列表数据变化）",
              e
            );
          }
          revertToLocalFilter();
        });
      } else {
        applyHostList(result);
      }
    } catch (e) {
      resourceListHostSkipRef.current = true;
      if (process.env.NODE_ENV !== "production") {
        console.warn(
          "[PisellReservation] sales.getResourceBookingList error",
          e
        );
      }
      revertToLocalFilter();
    }
  }, [
    isInternalListData,
    hasPisellosGetModule,
    resourceBoardLoading,
    floorDayBookingLoading,
    floorDayBookingDepKey,
    /**
     * 兜底信号：哪怕 cheap hash 没变，只要有 WS 推送 mutate 就重跑 host call。
     * 配合 `resourceListRetryGateRef` 保证非宿主场景不会重复打接口。
     */
    floorDayBookingDataVersion,
    debouncedAtMs,
    followWallClock,
    pisellosRef
  ]);
  const [salesTimelineHighlights, setSalesTimelineHighlights] = (0, import_react.useState)(null);
  const timelineHighlightsReqRef = (0, import_react.useRef)(0);
  const timelineHighlightsMissingLoggedRef = (0, import_react.useRef)(false);
  const scheduleDayMs = (0, import_dayjs.default)(scheduleDate).startOf("day").valueOf();
  (0, import_react.useEffect)(() => {
    if (!isInternalListData) {
      setSalesTimelineHighlights(null);
    }
  }, [isInternalListData]);
  (0, import_react.useEffect)(() => {
    if (!isInternalListData) return;
    const pisellosNow = pisellosRef.current;
    if (!(pisellosNow == null ? void 0 : pisellosNow.getModule)) return;
    if (resourceBoardLoading || floorDayBookingLoading) return;
    const bookingList = floorDayBookingDataRef.current;
    if (!Array.isArray(bookingList)) return;
    let salesModule;
    try {
      salesModule = pisellosNow.getModule("sales");
    } catch {
      return;
    }
    const highlightsFn = salesModule == null ? void 0 : salesModule.getTimelineHighlights;
    if (typeof highlightsFn !== "function") {
      setSalesTimelineHighlights(null);
      if (!timelineHighlightsMissingLoggedRef.current) {
        timelineHighlightsMissingLoggedRef.current = true;
        console.warn(
          "[PisellReservation] sales.getTimelineHighlights 未注册或非函数；时间轴密度退回本地计算"
        );
      }
      return;
    }
    const reqId = ++timelineHighlightsReqRef.current;
    const { startStr, endStr } = (0, import_reservationDensity.reservationTimelineRangeStrings)(
      scheduleDate,
      timelineRange,
      operatingDayBoundary,
      (0, import_dayjs.default)()
    );
    const applyHighlights = (raw) => {
      if (timelineHighlightsReqRef.current !== reqId) return;
      const normalized = (0, import_reservationDensity.normalizeSalesTimelineHighlightsRaw)(raw);
      setSalesTimelineHighlights(normalized);
    };
    try {
      const out = highlightsFn.call(salesModule, bookingList, startStr, endStr);
      if (out != null && typeof out.then === "function") {
        out.then(applyHighlights).catch((e) => {
          if (process.env.NODE_ENV !== "production") {
            console.warn(
              "[PisellReservation] sales.getTimelineHighlights Promise 失败",
              e
            );
          }
        });
      } else {
        applyHighlights(out);
      }
    } catch (e) {
      if (process.env.NODE_ENV !== "production") {
        console.warn(
          "[PisellReservation] sales.getTimelineHighlights 同步调用异常",
          e
        );
      }
    }
  }, [
    isInternalListData,
    hasPisellosGetModule,
    resourceBoardLoading,
    floorDayBookingLoading,
    floorDayBookingDepKey,
    scheduleDayMs,
    debouncedAtMs,
    timelineRange.start,
    timelineRange.end,
    pisellosRef,
    operatingDayBoundary
  ]);
  return { salesResourceBookings, salesTimelineHighlights };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useReservationSalesHostData
});
