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");
var import_reservationConstants = require("../reservationConstants");
function useReservationSalesHostData(options) {
  var _a, _b;
  const {
    isInternalListData,
    pisellosRef,
    hasPisellosGetModule,
    debouncedSchedule,
    resourceBoardLoading,
    floorDayBookingLoading,
    floorDayBookingData,
    scheduleDate,
    timeNavigatorPropsProp
  } = 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__";
    }
    const head = d.slice(0, 24);
    const parts = head.map((row) => {
      const r = row;
      return String((r == null ? void 0 : r.booking_id) ?? (r == null ? void 0 : r.id) ?? (r == null ? void 0 : r.bookingId) ?? "");
    });
    return `${d.length}:${parts.join("|")}`;
  }, [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}|${hasPisellosGetModule ? 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;
    setSalesResourceBookings(null);
    const resourceBookingListTimeFormat = "YYYY-MM-DD HH:mm";
    const timeStr = (0, import_dayjs.default)(debouncedSchedule.at).format(
      resourceBookingListTimeFormat
    );
    const currentTimeStr = (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(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,
    debouncedAtMs,
    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 timelineRange = (timeNavigatorPropsProp == null ? void 0 : timeNavigatorPropsProp.range) ?? import_reservationConstants.RESERVATION_TIMELINE_BUSINESS_RANGE;
    const { startStr, endStr } = (0, import_reservationDensity.reservationTimelineRangeStrings)(
      scheduleDate,
      timelineRange
    );
    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,
    (_a = timeNavigatorPropsProp == null ? void 0 : timeNavigatorPropsProp.range) == null ? void 0 : _a.start,
    (_b = timeNavigatorPropsProp == null ? void 0 : timeNavigatorPropsProp.range) == null ? void 0 : _b.end,
    pisellosRef
  ]);
  return { salesResourceBookings, salesTimelineHighlights };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useReservationSalesHostData
});
