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/pisellRecordBoard/shellFrame/Calendar/view/BookingCalendarResourceView.tsx
var BookingCalendarResourceView_exports = {};
__export(BookingCalendarResourceView_exports, {
  BookingCalendarResourceView: () => BookingCalendarResourceView
});
module.exports = __toCommonJS(BookingCalendarResourceView_exports);
var import_react = __toESM(require("react"));
var import_bookingCalendarDateUtils = require("../utils/bookingCalendarDateUtils");
var import_bookingCalendarConstants = require("../const/bookingCalendarConstants");
var import_BookingCalendarStyle = require("../utils/BookingCalendarStyle");
var import_bookingCalendarAxis = require("../utils/bookingCalendarAxis");
var import_bookingCalendarViewShared = require("../bookingCalendarViewShared");
var import_BookingCalendarGroupRowHeader = require("./BookingCalendarGroupRowHeader");
var import_calendarI18n = require("../calendarI18n");
var BookingCalendarResourceView = import_react.default.memo(BookingCalendarResourceViewInner);
function BookingCalendarResourceViewInner({
  calendarProps,
  isLight,
  anchorDate,
  monthDays,
  slotColWidth,
  bookings,
  visibleCourts,
  visibleCourtRows,
  hourSlots,
  slotStepHours,
  handleGridDropMove,
  openBookingDetail,
  setDraggingItem,
  setCollapsedGroups,
  setOverflowListModal,
  resourceMonthScrollToTodayToken,
  resourceDayHeaderRemaining,
  toggleResourceCell,
  selectedResourceCells,
  tickFillMode
}) {
  const props = calendarProps;
  const todayKey = (0, import_bookingCalendarDateUtils.fmtDate)(/* @__PURE__ */ new Date());
  const monthKeyPrefix = `${anchorDate.getFullYear()}-${anchorDate.getMonth()}`;
  const bookingsSignature = (0, import_react.useMemo)(() => {
    if (!Array.isArray(bookings) || bookings.length === 0) return "[]";
    return bookings.map(
      (b) => `${(b == null ? void 0 : b.id) ?? ""}|${(b == null ? void 0 : b.courtId) ?? ""}|${(b == null ? void 0 : b.date) ?? ""}|${(b == null ? void 0 : b.endDate) ?? ""}|${(b == null ? void 0 : b.kind) ?? ""}|${(b == null ? void 0 : b.startHour) ?? ""}|${(b == null ? void 0 : b.endHour) ?? ""}`
    ).join(";");
  }, [bookings]);
  const bookingsStable = (0, import_react.useMemo)(() => bookings, [bookingsSignature]);
  const scrollRef = (0, import_react.useRef)(null);
  const dragRef = (0, import_react.useRef)({ dragging: false, startX: 0, startY: 0, startLeft: 0, startTop: 0, moved: false });
  const [dragging, setDragging] = (0, import_react.useState)(false);
  const [virt, setVirt] = (0, import_react.useState)({
    i0: 0,
    i1: 0,
    r0: 0,
    r1: 0,
    ready: false
  });
  const rafRef = (0, import_react.useRef)(null);
  const rowPrefixRef = (0, import_react.useRef)([0]);
  const nCols = monthDays.length;
  const updateVirt = (0, import_react.useCallback)(() => {
    const root = scrollRef.current;
    if (!root || nCols <= 0) return;
    const sl = root.scrollLeft;
    const st = root.scrollTop;
    const vw = root.clientWidth;
    const vh = root.clientHeight;
    let i0 = Math.floor((sl - import_bookingCalendarConstants.frozenColWidth) / slotColWidth) - import_bookingCalendarConstants.DAY_VIEW_COL_BUFFER;
    let i1 = Math.ceil((sl + vw - import_bookingCalendarConstants.frozenColWidth) / slotColWidth) - 1 + import_bookingCalendarConstants.DAY_VIEW_COL_BUFFER;
    i0 = Math.max(0, i0);
    i1 = Math.min(nCols - 1, i1);
    if (i0 > i1) {
      i0 = 0;
      i1 = nCols - 1;
    }
    const pfx = rowPrefixRef.current;
    const nr = Math.max(0, pfx.length - 1);
    let r0 = 0;
    let r1 = nr > 0 ? nr - 1 : 0;
    if (nr > 0) {
      const bodyTop = import_bookingCalendarConstants.dayHeaderHeight;
      const vTop = st;
      const vBot = st + vh;
      const buf = import_bookingCalendarConstants.DAY_VIEW_ROW_BUFFER_PX;
      for (let r = 0; r < nr; r += 1) {
        const y1 = bodyTop + (pfx[r + 1] ?? 0);
        if (y1 > vTop - buf) {
          r0 = r;
          break;
        }
      }
      for (let r = nr - 1; r >= 0; r -= 1) {
        const y0 = bodyTop + (pfx[r] ?? 0);
        if (y0 < vBot + buf) {
          r1 = r;
          break;
        }
      }
      if (r0 > r1) {
        r0 = 0;
        r1 = nr - 1;
      }
    }
    setVirt(
      (prev) => prev.ready && prev.i0 === i0 && prev.i1 === i1 && prev.r0 === r0 && prev.r1 === r1 ? prev : { i0, i1, r0, r1, ready: true }
    );
  }, [nCols, slotColWidth]);
  const scheduleVirt = (0, import_react.useCallback)(() => {
    if (rafRef.current != null) return;
    rafRef.current = requestAnimationFrame(() => {
      rafRef.current = null;
      updateVirt();
    });
  }, [updateVirt]);
  (0, import_react.useLayoutEffect)(() => {
    const root = scrollRef.current;
    if (!root) return void 0;
    scheduleVirt();
    const onScroll = () => scheduleVirt();
    root.addEventListener("scroll", onScroll, { passive: true });
    let ro = null;
    if (typeof ResizeObserver !== "undefined") {
      ro = new ResizeObserver(() => scheduleVirt());
      try {
        ro.observe(root);
      } catch {
      }
    }
    return () => {
      root.removeEventListener("scroll", onScroll);
      ro == null ? void 0 : ro.disconnect();
      if (rafRef.current != null) cancelAnimationFrame(rafRef.current);
      rafRef.current = null;
    };
  }, [monthKeyPrefix, scheduleVirt, nCols]);
  (0, import_react.useLayoutEffect)(() => {
    if (!resourceMonthScrollToTodayToken) return;
    const root = scrollRef.current;
    if (!root || monthDays.length === 0) return;
    const idx = monthDays.findIndex((d) => (0, import_bookingCalendarDateUtils.fmtDate)(d) === (0, import_bookingCalendarDateUtils.getViewNowReference)().dateKey);
    if (idx < 0) return;
    const targetLeft = import_bookingCalendarConstants.frozenColWidth + idx * slotColWidth - root.clientWidth / 2 + slotColWidth / 2;
    root.scrollLeft = Math.max(0, Math.min(targetLeft, root.scrollWidth - root.clientWidth));
  }, [resourceMonthScrollToTodayToken, monthKeyPrefix, monthDays, slotColWidth]);
  const onMouseDown = (0, import_react.useCallback)((e) => {
    if (e.button !== 0 || !scrollRef.current) return;
    dragRef.current = {
      dragging: true,
      startX: e.clientX,
      startY: e.clientY,
      startLeft: scrollRef.current.scrollLeft,
      startTop: scrollRef.current.scrollTop,
      moved: false
    };
    setDragging(true);
  }, []);
  const onMouseMove = (0, import_react.useCallback)((e) => {
    if (!dragRef.current.dragging || !scrollRef.current) return;
    const dx = e.clientX - dragRef.current.startX;
    const dy = e.clientY - dragRef.current.startY;
    if (Math.abs(dx) > 3 || Math.abs(dy) > 3) dragRef.current.moved = true;
    scrollRef.current.scrollLeft = dragRef.current.startLeft - dx;
    scrollRef.current.scrollTop = dragRef.current.startTop - dy;
  }, []);
  const onMouseUp = (0, import_react.useCallback)(() => {
    dragRef.current.dragging = false;
    setDragging(false);
  }, []);
  const visibleColIndices = (0, import_react.useMemo)(() => {
    if (!virt.ready) {
      const out2 = [];
      for (let i = 0; i < nCols; i += 1) out2.push(i);
      return out2;
    }
    const out = [];
    for (let i = virt.i0; i <= virt.i1; i += 1) out.push(i);
    return out;
  }, [virt, nCols]);
  const summaryCache = (0, import_react.useMemo)(() => {
    const m = /* @__PURE__ */ new Map();
    const visibleCourtIds = [];
    for (const r of visibleCourtRows) {
      if ((r == null ? void 0 : r.kind) === "court" && r.id) visibleCourtIds.push(String(r.id));
    }
    const visibleDateKeys = visibleColIndices.map((ci) => monthDays[ci]).filter(Boolean).map((d) => (0, import_bookingCalendarDateUtils.fmtDate)(d));
    for (const cid of visibleCourtIds) {
      for (const dk of visibleDateKeys) {
        m.set(`${cid}	${dk}`, (0, import_bookingCalendarDateUtils.courtDaySummary)(cid, dk, bookingsStable, hourSlots, slotStepHours));
      }
    }
    return m;
  }, [
    visibleCourtRows,
    visibleColIndices,
    monthDays,
    bookingsStable,
    hourSlots,
    slotStepHours
  ]);
  const getSummary = (0, import_react.useCallback)(
    (courtId, dateKey) => summaryCache.get(`${courtId}	${dateKey}`) ?? (0, import_bookingCalendarDateUtils.courtDaySummary)(courtId, dateKey, bookingsStable, hourSlots, slotStepHours),
    [summaryCache, bookingsStable, hourSlots, slotStepHours]
  );
  const monthFirstKey = (0, import_react.useMemo)(
    () => monthDays[0] ? (0, import_bookingCalendarDateUtils.fmtDate)(monthDays[0]) : "",
    [monthDays]
  );
  const monthLastKey = (0, import_react.useMemo)(
    () => monthDays.length > 0 ? (0, import_bookingCalendarDateUtils.fmtDate)(monthDays[monthDays.length - 1]) : "",
    [monthDays]
  );
  const bookingsByCourt = (0, import_react.useMemo)(() => {
    const m = /* @__PURE__ */ new Map();
    if (!monthFirstKey || !monthLastKey) return m;
    for (const b of bookingsStable) {
      if (!(b == null ? void 0 : b.courtId)) continue;
      if (!(0, import_bookingCalendarDateUtils.bookingIntersectsDateWindow)(b, monthFirstKey, monthLastKey)) continue;
      const cid = String(b.courtId);
      const arr = m.get(cid);
      if (arr) arr.push(b);
      else m.set(cid, [b]);
    }
    return m;
  }, [bookingsStable, monthFirstKey, monthLastKey]);
  const monthDateKeys = (0, import_react.useMemo)(
    () => monthDays.map((d) => (0, import_bookingCalendarDateUtils.fmtDate)(d)),
    [monthDays]
  );
  const courtRowMetrics = (0, import_react.useMemo)(() => {
    var _a;
    const m = /* @__PURE__ */ new Map();
    for (const [cid, items] of bookingsByCourt) {
      const { perDateLanes, laneCount } = (0, import_bookingCalendarDateUtils.assignPerDateLanesCrossDayUnified)(
        items,
        monthDateKeys
      );
      const entries = [];
      const overflowByDate = /* @__PURE__ */ new Map();
      const seenIds = /* @__PURE__ */ new Set();
      const pushOverflow = (dateKey, it) => {
        const idKey = String(it.id);
        const arr = overflowByDate.get(dateKey);
        if (arr) {
          if (!arr.some((x) => String(x.id) === idKey)) arr.push(it);
        } else {
          overflowByDate.set(dateKey, [it]);
        }
      };
      for (const it of items) {
        const idKey = String(it.id);
        if (seenIds.has(idKey)) continue;
        seenIds.add(idKey);
        let displayLane = 0;
        let showPill = false;
        for (const dateKey of monthDateKeys) {
          const lane = (_a = perDateLanes.get(dateKey)) == null ? void 0 : _a.get(idKey);
          if (lane === void 0) continue;
          displayLane = lane;
          if (lane < import_bookingCalendarConstants.RESOURCE_VIEW_MAX_LANE) showPill = true;
          if (lane >= import_bookingCalendarConstants.RESOURCE_VIEW_MAX_LANE) pushOverflow(dateKey, it);
        }
        if (showPill) entries.push({ item: it, lane: displayLane });
      }
      m.set(cid, { entries, laneCount, overflowByDate });
    }
    return m;
  }, [bookingsByCourt, monthDateKeys]);
  const rowHeights = (0, import_react.useMemo)(() => {
    const padY = import_bookingCalendarConstants.RESOURCE_VIEW_CELL_PADDING_Y_PX;
    const cardH = import_bookingCalendarConstants.RESOURCE_VIEW_BOOKING_CARD_EST_PX;
    const gap = 4;
    const moreH = import_bookingCalendarConstants.RESOURCE_VIEW_MORE_TILE_MIN_PX;
    return visibleCourtRows.map((row) => {
      if (row.kind === "group") return import_bookingCalendarConstants.groupRowHeight;
      const metric = courtRowMetrics.get(String(row.id));
      const laneCount = (metric == null ? void 0 : metric.laneCount) ?? 0;
      const visibleLanes = Math.min(laneCount, import_bookingCalendarConstants.RESOURCE_VIEW_MAX_LANE);
      const hasOverflow = laneCount > import_bookingCalendarConstants.RESOURCE_VIEW_MAX_LANE;
      if (visibleLanes === 0) return import_bookingCalendarConstants.dayRowHeight;
      let content = visibleLanes * cardH + (visibleLanes - 1) * gap;
      if (hasOverflow) content += gap + moreH;
      return Math.max(import_bookingCalendarConstants.dayRowHeight, padY + content);
    });
  }, [visibleCourtRows, courtRowMetrics]);
  const gridTemplateRows = (0, import_react.useMemo)(
    () => visibleCourtRows.map(
      (row, i) => row.kind === "group" ? `${import_bookingCalendarConstants.groupRowHeight}px` : `${rowHeights[i]}px`
    ).join(" "),
    [visibleCourtRows, rowHeights]
  );
  const rowPrefixTop = (0, import_react.useMemo)(() => {
    const arr = new Array(rowHeights.length + 1);
    arr[0] = 0;
    for (let i = 0; i < rowHeights.length; i += 1) {
      arr[i + 1] = arr[i] + (rowHeights[i] ?? 0);
    }
    return arr;
  }, [rowHeights]);
  (0, import_react.useLayoutEffect)(() => {
    rowPrefixRef.current = rowPrefixTop;
    scheduleVirt();
  }, [rowPrefixTop, scheduleVirt]);
  const contentHeight = import_bookingCalendarConstants.dayHeaderHeight + rowPrefixTop[rowPrefixTop.length - 1];
  const selectionSigByCourtId = (0, import_react.useMemo)(() => {
    const grp = /* @__PURE__ */ new Map();
    for (const s of selectedResourceCells) {
      const cid = String(s.courtId);
      let arr = grp.get(cid);
      if (!arr) {
        arr = [];
        grp.set(cid, arr);
      }
      arr.push(s.dateKey);
    }
    const m = /* @__PURE__ */ new Map();
    grp.forEach((arr, cid) => {
      arr.sort();
      m.set(cid, arr.join("|"));
    });
    return m;
  }, [selectedResourceCells]);
  const monthLabel = `${anchorDate.getFullYear()} / ${anchorDate.getMonth() + 1}`;
  return /* @__PURE__ */ import_react.default.createElement("div", { key: `resource-${monthKeyPrefix}`, className: "flex min-h-0 flex-1 flex-col" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "relative flex min-h-0 flex-1 flex-col" }, /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      ref: scrollRef,
      onMouseDown,
      onMouseMove,
      onMouseUp,
      onMouseLeave: onMouseUp,
      style: { overscrollBehavior: "none" },
      className: `pisell-scroll-hidden relative border min-h-0 max-h-none flex-1 overflow-auto touch-pan-x touch-pan-y select-none ${isLight ? "theme-panel theme-border" : "border-zinc-800 bg-[#121217]"} ${dragging ? "cursor-grabbing" : "cursor-grab"}`
    },
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "relative",
        style: {
          minWidth: `${import_bookingCalendarConstants.frozenColWidth + nCols * slotColWidth}px`,
          minHeight: `${contentHeight}px`
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: "grid sticky top-0 z-50",
          style: {
            gridTemplateColumns: `${import_bookingCalendarConstants.frozenColWidth}px repeat(${nCols}, ${slotColWidth}px)`
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: `sticky left-0 top-0 z-[60] flex h-full min-h-0 w-[132px] min-w-[132px] max-w-[132px] flex-col justify-center px-2.5 font-semibold border-b shadow-[8px_0_16px_rgba(0,0,0,0.08)] ${isLight ? "surface-brand-side text-slate-900" : "bg-[#241d40] border-zinc-800 text-zinc-100"}`
          },
          /* @__PURE__ */ import_react.default.createElement("span", { className: "text-lg font-bold leading-tight" }, monthLabel)
        ),
        visibleColIndices.map((ci) => {
          const day = monthDays[ci];
          if (!day) return null;
          const key = (0, import_bookingCalendarDateUtils.fmtDate)(day);
          const isToday = key === todayKey;
          const remaining = resourceDayHeaderRemaining[key];
          return /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              key: `rh-${key}`,
              className: `relative z-20 border-b border-l px-1 py-2 text-center shadow-[0_8px_16px_rgba(0,0,0,0.06)] ${isLight ? "theme-border theme-text" : "border-zinc-800"} ${isToday ? isLight ? "bg-gradient-to-b from-violet-50 to-white" : "bg-gradient-to-b from-violet-950 to-[#1a1a22]" : isLight ? "theme-panel-soft" : "bg-[#1a1a22]"}`,
              style: { gridColumn: ci + 2 }
            },
            /* @__PURE__ */ import_react.default.createElement("div", { className: "flex justify-center" }, /* @__PURE__ */ import_react.default.createElement(
              "span",
              {
                className: "grid h-10 w-10 place-items-center text-3xl font-semibold leading-none",
                "aria-label": isToday ? "Today" : void 0
              },
              day.getDate()
            )),
            remaining && remaining.total > 0 && /* @__PURE__ */ import_react.default.createElement(
              "div",
              {
                className: `mt-1 text-[11px] font-semibold leading-tight ${(0, import_bookingCalendarViewShared.getRemainingToneClass)(
                  remaining.ratio,
                  isLight
                )}`
              },
              (0, import_calendarI18n.tCal)("pisell2.recordBoard.calendar.day.freeRatio", {
                remaining: remaining.remaining,
                total: remaining.total
              })
            )
          );
        })
      ),
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: "grid relative",
          style: {
            gridTemplateColumns: `${import_bookingCalendarConstants.frozenColWidth}px repeat(${nCols}, ${slotColWidth}px)`,
            gridTemplateRows
          }
        },
        visibleCourtRows.map((row, rowIndex) => {
          if (virt.ready && (rowIndex < virt.r0 || rowIndex > virt.r1)) {
            return /* @__PURE__ */ import_react.default.createElement(
              "div",
              {
                key: `${row.id}-skip`,
                className: `pointer-events-none border-b ${isLight ? "theme-border" : "border-zinc-800"}`,
                style: { gridColumn: "1 / -1", gridRow: rowIndex + 1 },
                "aria-hidden": true
              }
            );
          }
          return row.kind === "group" ? /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, { key: row.id }, /* @__PURE__ */ import_react.default.createElement(
            import_BookingCalendarGroupRowHeader.BookingCalendarGroupRowHeader,
            {
              isLight,
              view: "resource",
              row: {
                id: row.id,
                label: row.label,
                count: row.count,
                collapsed: row.collapsed
              },
              renderResourceCell: props.renderResourceCell,
              setCollapsedGroups,
              style: { gridRow: rowIndex + 1, gridColumn: 1 }
            }
          ), visibleColIndices.map((ci) => {
            const day = monthDays[ci];
            if (!day) return null;
            const key = (0, import_bookingCalendarDateUtils.fmtDate)(day);
            const groupCourts = visibleCourts.filter(
              (c) => c.type === row.label
            );
            const total = groupCourts.length;
            const noRatioCell = total === 0;
            let remaining = 0;
            let ratio = 0;
            if (!noRatioCell) {
              const busy = groupCourts.filter(
                (c) => getSummary(c.id, key).items.length > 0
              ).length;
              remaining = total - busy;
              ratio = remaining / total;
            }
            return /* @__PURE__ */ import_react.default.createElement(
              "div",
              {
                key: `${row.id}-${key}`,
                style: { gridRow: rowIndex + 1, gridColumn: ci + 2 },
                className: `flex h-full items-center justify-center border-b border-l px-1.5 py-1 text-center text-sm font-medium ${isLight ? "theme-border" : "border-zinc-800"} ${noRatioCell ? isLight ? "bg-slate-100 theme-text-faint" : "bg-zinc-800/80 text-zinc-500" : isLight ? "theme-panel-soft" : "bg-[#151a2f] text-zinc-300"}`
              },
              noRatioCell ? /* @__PURE__ */ import_react.default.createElement("div", { className: "text-xs opacity-60" }, "—") : /* @__PURE__ */ import_react.default.createElement(
                "div",
                {
                  className: `text-xs font-semibold leading-none ${(0, import_bookingCalendarViewShared.getRemainingToneClass)(
                    ratio,
                    isLight
                  )}`
                },
                (0, import_calendarI18n.tCal)("pisell2.recordBoard.calendar.day.freeRatio", {
                  remaining,
                  total
                })
              )
            );
          })) : /* @__PURE__ */ import_react.default.createElement(
            ResourceCourtRow,
            {
              key: row.id,
              courtId: String(row.id),
              courtName: row.name,
              courtType: row.type,
              rowIndex,
              visibleColIndices,
              monthDays,
              getSummary,
              toggleResourceCell,
              isLight,
              renderResourceCell: props.renderResourceCell,
              handleGridDropMove,
              selectedSig: selectionSigByCourtId.get(String(row.id)) ?? ""
            }
          );
        }),
        /* @__PURE__ */ import_react.default.createElement(
          BookingOverlay,
          {
            visibleCourtRows,
            visibleColIndices,
            monthDays,
            rowPrefixTop,
            rowHeights,
            slotColWidth,
            hourSlots,
            slotStepHours,
            virt,
            courtRowMetrics,
            bookingsByCourt,
            isLight,
            renderMonthWeekBooking: props.renderMonthWeekBooking,
            openBookingDetail,
            setDraggingItem,
            handleGridDropMove,
            setOverflowListModal,
            tickFillMode
          }
        )
      )
    )
  )));
}
var ResourceCourtRow = import_react.default.memo(function ResourceCourtRow2({
  courtId,
  courtName,
  courtType,
  rowIndex,
  visibleColIndices,
  monthDays,
  getSummary,
  toggleResourceCell,
  isLight,
  renderResourceCell,
  handleGridDropMove,
  selectedSig
}) {
  const selectedDateKeys = (0, import_react.useMemo)(
    () => selectedSig ? new Set(selectedSig.split("|")) : null,
    [selectedSig]
  );
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: `sticky left-0 z-30 flex h-full min-h-0 w-[132px] min-w-[132px] max-w-[132px] flex-col justify-center border-b px-2.5 py-1.5 shadow-[8px_0_16px_rgba(0,0,0,0.06)] ${isLight ? "surface-brand-side-muted" : "border-zinc-800 bg-[#1a1a22]"}`,
      style: { gridRow: rowIndex + 1, gridColumn: 1 }
    },
    renderResourceCell ? renderResourceCell({
      view: "resource",
      row: { kind: "court", id: courtId, name: courtName, type: courtType },
      isLight
    }) : /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-rb-cal-week-resource-name min-w-0 w-full font-semibold text-[16px] leading-tight" }, courtName)
  ), visibleColIndices.map((ci) => {
    const day = monthDays[ci];
    if (!day) return null;
    const key = (0, import_bookingCalendarDateUtils.fmtDate)(day);
    const summary = getSummary(courtId, key);
    return /* @__PURE__ */ import_react.default.createElement(
      ResourceCourtCell,
      {
        key: `${courtId}-${key}`,
        courtId,
        dateKey: key,
        rowIndex,
        colIndex: ci,
        summary,
        selected: (selectedDateKeys == null ? void 0 : selectedDateKeys.has(key)) ?? false,
        isLight,
        toggleResourceCell,
        handleGridDropMove
      }
    );
  }));
});
var ResourceCourtCell = import_react.default.memo(function ResourceCourtCell2({
  courtId,
  dateKey,
  rowIndex,
  colIndex,
  summary,
  selected,
  isLight,
  toggleResourceCell,
  handleGridDropMove
}) {
  return /* @__PURE__ */ import_react.default.createElement(
    "button",
    {
      type: "button",
      onClick: () => toggleResourceCell(courtId, dateKey),
      onDragOver: (e) => e.preventDefault(),
      onDrop: (e) => {
        e.preventDefault();
        handleGridDropMove(dateKey, courtId);
      },
      style: {
        gridRow: rowIndex + 1,
        gridColumn: colIndex + 2,
        contain: "layout paint style"
      },
      className: `relative flex w-full min-h-0 flex-col justify-start border-b border-l p-1 text-left align-top outline-none ${isLight ? "theme-border" : "border-zinc-700"} ${summary.fullyBooked ? isLight ? "bg-slate-100 theme-text-faint" : "bg-zinc-800 text-zinc-500" : summary.hasBlock ? isLight ? "bg-red-50 border-red-200" : "bg-red-950/30 border-red-800/40" : summary.occupiedHours.length > 0 ? isLight ? "bg-violet-50" : "bg-[#1c1630]" : isLight ? "theme-grid-cell" : "bg-zinc-900"} ${selected ? isLight ? "ring-1 ring-inset ring-violet-400/75 bg-violet-400/10" : "ring-1 ring-inset ring-violet-400/70 bg-white/10" : ""}`
    },
    summary.items.length === 0 ? /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: `${import_bookingCalendarConstants.CALENDAR_EMPTY_DASHED_SLOT_CLASSNAME} text-center ${isLight ? "border-[#d8d0eb] text-[#8f86a9]" : "border-zinc-700 text-zinc-500"}`
      },
      selected ? (0, import_calendarI18n.tCal)("pisell2.recordBoard.calendar.day.selected") : null
    ) : null
  );
});
var OVERLAY_CELL_PAD = 4;
var OVERLAY_ITEM_GAP = 4;
var PROPORTIONAL_MIN_BOOKING_W = 24;
var BookingOverlay = import_react.default.memo(function BookingOverlay2({
  visibleCourtRows,
  visibleColIndices,
  monthDays,
  rowPrefixTop,
  rowHeights,
  slotColWidth,
  hourSlots,
  slotStepHours,
  virt,
  courtRowMetrics,
  bookingsByCourt,
  isLight,
  renderMonthWeekBooking,
  openBookingDetail,
  setDraggingItem,
  handleGridDropMove,
  setOverflowListModal,
  tickFillMode
}) {
  const dateKeyToCol = (0, import_react.useMemo)(() => {
    const m = /* @__PURE__ */ new Map();
    monthDays.forEach((d, i) => m.set((0, import_bookingCalendarDateUtils.fmtDate)(d), i));
    return m;
  }, [monthDays]);
  const items = (0, import_react.useMemo)(() => {
    const out = [];
    const lastColIdx = monthDays.length - 1;
    if (lastColIdx < 0) return out;
    const dayGridMin = (hourSlots == null ? void 0 : hourSlots[0]) ?? 0;
    const dayGridSpan = ((hourSlots == null ? void 0 : hourSlots.length) ?? 24) * (slotStepHours || 1);
    const colAxis = {
      originUnit: 0,
      scalePerUnit: slotColWidth,
      tickUnit: 1,
      minSize: 0
    };
    for (let rowIdx = 0; rowIdx < visibleCourtRows.length; rowIdx += 1) {
      if (virt.ready && (rowIdx < virt.r0 || rowIdx > virt.r1)) continue;
      const row = visibleCourtRows[rowIdx];
      if ((row == null ? void 0 : row.kind) !== "court" || !row.id) continue;
      const courtId = String(row.id);
      const metric = courtRowMetrics.get(courtId);
      if (!metric) continue;
      const courtItems = bookingsByCourt.get(courtId) ?? [];
      if (courtItems.length === 0) continue;
      const cellTop = rowPrefixTop[rowIdx] ?? 0;
      for (const entry of metric.entries) {
        const it = entry.item;
        const lane = entry.lane;
        if (lane >= import_bookingCalendarConstants.RESOURCE_VIEW_MAX_LANE) continue;
        const startStr = String(it.date);
        const endStr = String(it.endDate ?? it.date);
        const rawStartCol = dateKeyToCol.get(startStr);
        const rawEndCol = dateKeyToCol.get(endStr);
        let startCol = rawStartCol ?? -1;
        let endCol = rawEndCol ?? -1;
        const clippedLeft = rawStartCol === void 0 && startStr < ((0, import_bookingCalendarDateUtils.fmtDate)(monthDays[0]) ?? "");
        const clippedRight = rawEndCol === void 0 && endStr > ((0, import_bookingCalendarDateUtils.fmtDate)(monthDays[lastColIdx]) ?? "");
        if (rawStartCol === void 0) startCol = clippedLeft ? 0 : -1;
        if (rawEndCol === void 0) endCol = clippedRight ? lastColIdx : -1;
        if (startCol < 0 || endCol < 0 || endCol < startCol) continue;
        if (virt.ready && (endCol < virt.i0 || startCol > virt.i1))
          continue;
        const startHourVal = Number.isFinite(Number(it.startHour)) ? Number(it.startHour) : dayGridMin;
        const endHourVal = Number.isFinite(Number(it.endHour)) ? Number(it.endHour) : dayGridMin;
        const startUnit = tickFillMode === "snap" || clippedLeft ? startCol : (0, import_bookingCalendarAxis.dayGridUnit)(startCol, startHourVal, dayGridMin, dayGridSpan);
        const endUnit = tickFillMode === "snap" || clippedRight ? endCol + 1 : (0, import_bookingCalendarAxis.dayGridUnit)(endCol, endHourVal, dayGridMin, dayGridSpan);
        const span = (0, import_bookingCalendarAxis.mapAxisSpan)(colAxis, startUnit, endUnit, tickFillMode);
        let left = import_bookingCalendarConstants.frozenColWidth + span.offset + OVERLAY_CELL_PAD;
        let width = span.size - OVERLAY_CELL_PAD * 2;
        if (tickFillMode !== "snap") {
          const colInnerW = slotColWidth - OVERLAY_CELL_PAD * 2;
          if (startCol === endCol) {
            width = Math.max(PROPORTIONAL_MIN_BOOKING_W, Math.min(width, colInnerW));
            const colLeft = import_bookingCalendarConstants.frozenColWidth + startCol * slotColWidth + OVERLAY_CELL_PAD;
            const colRight = colLeft + colInnerW;
            if (left + width > colRight) left = colRight - width;
            if (left < colLeft) left = colLeft;
          } else {
            width = Math.max(PROPORTIONAL_MIN_BOOKING_W, width);
          }
        }
        const top = cellTop + OVERLAY_CELL_PAD + lane * (import_bookingCalendarConstants.RESOURCE_VIEW_BOOKING_CARD_EST_PX + OVERLAY_ITEM_GAP);
        out.push({
          kind: "booking",
          key: `${courtId}	${it.id}`,
          item: it,
          courtId,
          dateKey: startStr,
          top,
          left,
          width,
          height: import_bookingCalendarConstants.RESOURCE_VIEW_BOOKING_CARD_EST_PX,
          clippedLeft,
          clippedRight,
          crossDay: (0, import_bookingCalendarDateUtils.isCrossDayBooking)(it)
        });
      }
      if (metric.laneCount > import_bookingCalendarConstants.RESOURCE_VIEW_MAX_LANE) {
        const visibleLanes = import_bookingCalendarConstants.RESOURCE_VIEW_MAX_LANE;
        const tileTop = cellTop + OVERLAY_CELL_PAD + visibleLanes * (import_bookingCalendarConstants.RESOURCE_VIEW_BOOKING_CARD_EST_PX + OVERLAY_ITEM_GAP);
        for (const colIdx of visibleColIndices) {
          const day = monthDays[colIdx];
          if (!day) continue;
          const dateKey = (0, import_bookingCalendarDateUtils.fmtDate)(day);
          const overflowItems = metric.overflowByDate.get(dateKey);
          if (!overflowItems || overflowItems.length === 0) continue;
          const allHits = courtItems.filter(
            (b) => (0, import_bookingCalendarDateUtils.getBookingSegmentForDate)(b, dateKey) != null
          );
          out.push({
            kind: "more",
            key: `${courtId}	${dateKey}	more`,
            courtId,
            dateKey,
            top: tileTop,
            left: colIdx * slotColWidth + import_bookingCalendarConstants.frozenColWidth + OVERLAY_CELL_PAD,
            width: slotColWidth - OVERLAY_CELL_PAD * 2,
            moreItems: overflowItems,
            moreCount: overflowItems.length,
            allItems: allHits
          });
        }
      }
    }
    return out;
  }, [
    visibleCourtRows,
    visibleColIndices,
    monthDays,
    rowPrefixTop,
    slotColWidth,
    hourSlots,
    slotStepHours,
    virt,
    courtRowMetrics,
    bookingsByCourt,
    dateKeyToCol,
    tickFillMode
  ]);
  const overlayHeight = rowPrefixTop[rowPrefixTop.length - 1] ?? rowHeights.reduce((a, b) => a + b, 0);
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      "aria-hidden": true,
      style: {
        position: "absolute",
        top: 0,
        left: 0,
        width: "100%",
        height: overlayHeight,
        pointerEvents: "none",
        zIndex: 5
      }
    },
    items.map((it) => {
      if (it.kind === "booking") {
        const radiusClass = it.crossDay ? `${it.clippedLeft ? "rounded-l-none" : "rounded-l-lg"} ${it.clippedRight ? "rounded-r-none" : "rounded-r-lg"}` : "rounded-lg";
        const layoutClassName = `flex flex-col justify-center px-2.5 py-1.5 text-xs text-left w-full h-full ${radiusClass} ${(0, import_BookingCalendarStyle.getGridBookingRowStateClasses)(it.item)}`;
        return /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            key: it.key,
            style: {
              position: "absolute",
              top: it.top,
              left: it.left,
              width: it.width,
              height: it.height,
              pointerEvents: "auto"
            },
            onDragOver: (e) => e.preventDefault(),
            onDrop: (e) => {
              e.preventDefault();
              handleGridDropMove(it.dateKey, it.courtId);
            }
          },
          renderMonthWeekBooking ? /* @__PURE__ */ import_react.default.createElement("div", { className: "relative h-full w-full min-h-0" }, renderMonthWeekBooking({
            item: it.item,
            dateKey: it.dateKey,
            view: "resource",
            isLight,
            layoutClassName,
            onOpenDetail: openBookingDetail,
            onDragStart: (i) => setDraggingItem(i),
            // 资源视图本就不支持 pill 拖拽改约（cell 级 drop 由 handleGridDropMove 接管）
            draggable: false
          }), /* @__PURE__ */ import_react.default.createElement(
            import_bookingCalendarViewShared.CalendarGridBookingClipMarkers,
            {
              clippedLeft: it.clippedLeft,
              clippedRight: it.clippedRight
            }
          )) : /* @__PURE__ */ import_react.default.createElement(
            "button",
            {
              type: "button",
              onClick: (e) => {
                e.stopPropagation();
                openBookingDetail(it.item);
              },
              className: `relative ${layoutClassName}`
            },
            it.clippedLeft && /* @__PURE__ */ import_react.default.createElement(
              "span",
              {
                "aria-hidden": true,
                className: "absolute left-0.5 top-1/2 -translate-y-1/2 text-[10px] leading-none opacity-80"
              },
              "◀"
            ),
            it.clippedRight && /* @__PURE__ */ import_react.default.createElement(
              "span",
              {
                "aria-hidden": true,
                className: "absolute right-0.5 top-1/2 -translate-y-1/2 text-[10px] leading-none opacity-80"
              },
              "▶"
            ),
            /* @__PURE__ */ import_react.default.createElement("div", { className: "truncate" }, it.item.name),
            /* @__PURE__ */ import_react.default.createElement("div", { className: "mt-1 opacity-80 truncate" }, it.crossDay ? `${(0, import_bookingCalendarDateUtils.formatShortMonthDay)(it.item.date)} ${(0, import_bookingCalendarDateUtils.formatHourLabel)(
              it.item.startHour
            )} - ${(0, import_bookingCalendarDateUtils.formatShortMonthDay)(
              it.item.endDate ?? it.item.date
            )} ${(0, import_bookingCalendarDateUtils.formatHourLabel)(it.item.endHour)}` : `${(0, import_bookingCalendarDateUtils.formatHourLabel)(it.item.startHour)} - ${(0, import_bookingCalendarDateUtils.formatHourLabel)(
              it.item.endHour
            )}`)
          )
        );
      }
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          key: it.key,
          style: {
            position: "absolute",
            top: it.top,
            left: it.left,
            width: it.width,
            minHeight: import_bookingCalendarConstants.RESOURCE_VIEW_MORE_TILE_MIN_PX,
            pointerEvents: "auto"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          "button",
          {
            type: "button",
            onClick: (e) => {
              e.stopPropagation();
              setOverflowListModal(
                (prev) => prev && prev.scope === it.courtId && prev.date === it.dateKey ? null : {
                  scope: it.courtId,
                  date: it.dateKey,
                  title: (0, import_calendarI18n.tCal)(
                    "pisell2.recordBoard.calendar.overflow.listTitleAllBookings",
                    { date: it.dateKey }
                  ),
                  items: it.allItems
                }
              );
            },
            style: { minHeight: import_bookingCalendarConstants.RESOURCE_VIEW_MORE_TILE_MIN_PX },
            className: "flex w-full items-center justify-center rounded-xl bg-violet-700/90 px-2.5 py-1 text-xs font-semibold text-white"
          },
          "+",
          it.moreCount
        )
      );
    })
  );
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BookingCalendarResourceView
});
