function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
// @ts-nocheck — 日历多视图共用的卡片与分组工具（VIP/Standard + 动态 type 分组、BookingCard 等）
import React, { useEffect, useRef } from 'react';
import { Tooltip } from 'antd';
import { tCal } from "./calendarI18n";
import { formatDateLoose, formatHourLabel, getDisplayStatusTag, getLateMinutes, statusTagMetaParts } from "./utils/bookingCalendarDateUtils";
import { DAY_BOOKING_MICRO_PX, DAY_BOOKING_NARROW_PX } from "./const/bookingCalendarConstants";
import { getBookingStateClasses } from "./utils/BookingCalendarStyle";

/** UI 层：状态徽标文案走 i18n（utils 侧为 {@link statusTagMetaParts}） */
export function statusTagMeta(tag) {
  var p = statusTagMetaParts(tag);
  return p ? {
    label: tCal(p.labelI18nKey),
    className: p.className
  } : null;
}

/** 锁台卡片副标题：操作人、锁台时间等拼接一行 */
export function getBlockMetaLine(item) {
  if (item.kind !== 'block') return '';
  var bits = [];
  if (item.blockBy) bits.push(tCal('pisell2.recordBoard.calendar.card.blockBy', {
    name: item.blockBy
  }));
  if (item.blockedAt) bits.push(formatDateLoose(item.blockedAt));
  return bits.join(' · ');
}
export function getRemainingToneClass(ratio) {
  var isLight = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  if (ratio <= 0.2) return isLight ? 'text-red-600' : 'text-red-300';
  if (ratio <= 0.4) return isLight ? 'text-amber-600' : 'text-amber-300';
  return isLight ? 'theme-text-muted' : 'text-zinc-400';
}

/**
 * @param options.flattenWhenAllGroupsCollapsed
 *   若为 `true`：全部分组折叠时仅有 group 头、无 court 行，会退化为平铺 court（易与「全部展开」混淆）。
 *   日/周/月日历统一为默认 `false`，保留分组头行与折叠态（与底部「全部关闭」预期一致）。
 *
 * 若全部资源只属于**一个**分组（含仅 VIP、仅 Standard、或仅一种自定义 type），日/周视图不展示分组头行，
 * 直接平铺资源行（单组折叠时也同样平铺资源，避免只剩一条分组栏）。
 */
export function buildGroupedCourtRows(courts) {
  var collapsedGroups = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var _options$flattenWhenA = options.flattenWhenAllGroupsCollapsed,
    flattenWhenAllGroupsCollapsed = _options$flattenWhenA === void 0 ? false : _options$flattenWhenA;
  var predefined = ['VIP', 'Standard'];
  var rows = [];
  var consumedIds = new Set();
  predefined.forEach(function (group) {
    var items = courts.filter(function (court) {
      return court.type === group;
    });
    if (items.length === 0) return;
    items.forEach(function (c) {
      return consumedIds.add(c.id);
    });
    rows.push({
      kind: 'group',
      id: "group-".concat(group),
      label: group,
      count: items.length,
      collapsed: !!collapsedGroups[group]
    });
    if (!collapsedGroups[group]) {
      items.forEach(function (court) {
        return rows.push(_objectSpread(_objectSpread({
          kind: 'court'
        }, court), {}, {
          group: group
        }));
      });
    }
  });
  /** 低代码接入：桌位 type 多为 Resource / 自定义 groupType，不能只剩 VIP/Standard 两行否则日周视图为空 */
  var remainder = courts.filter(function (c) {
    return !consumedIds.has(c.id);
  });
  var byType = {};
  remainder.forEach(function (court) {
    var label = court.type && String(court.type).trim() !== '' ? String(court.type) : tCal('pisell2.recordBoard.calendar.common.resourceFallback');
    if (!byType[label]) byType[label] = [];
    byType[label].push(court);
  });
  Object.keys(byType).forEach(function (label) {
    var items = byType[label];
    if (!items.length) return;
    var idSafe = String(label).replace(/\s+/g, '-');
    rows.push({
      kind: 'group',
      id: "group-".concat(idSafe),
      label: label,
      count: items.length,
      collapsed: !!collapsedGroups[label]
    });
    if (!collapsedGroups[label]) {
      items.forEach(function (court) {
        return rows.push(_objectSpread(_objectSpread({
          kind: 'court'
        }, court), {}, {
          group: label
        }));
      });
    }
  });
  var groupRowCount = rows.filter(function (r) {
    return r.kind === 'group';
  }).length;
  /** 仅存在一个资源分组：日/周不展示分组头，直接平铺 court（与同组折叠态无关，避免只显示一行分组栏） */
  if (groupRowCount === 1 && courts.length > 0) {
    var fallbackLabel = tCal('pisell2.recordBoard.calendar.common.resourceFallback');
    return courts.map(function (c) {
      return _objectSpread(_objectSpread({
        kind: 'court'
      }, c), {}, {
        group: c.type && String(c.type).trim() !== '' ? String(c.type) : fallbackLabel
      });
    });
  }
  var courtRowsOnly = rows.filter(function (r) {
    return r.kind === 'court';
  });
  /** 可选：全部分组折叠且仍须展示 court 行时再平铺（日历默认不走此分支） */
  if (flattenWhenAllGroupsCollapsed && courtRowsOnly.length === 0 && courts.length > 0) {
    return courts.map(function (c) {
      return {
        kind: 'court',
        id: c.id,
        name: c.name,
        type: c.type,
        group: c.type
      };
    });
  }
  return rows;
}

/** 周/月/资源跨窗口 pill 左右续画标记（◀/▶）；自定义 `renderMonthWeekBooking` 时由格容器包裹渲染 */
export function CalendarGridBookingClipMarkers(_ref) {
  var clippedLeft = _ref.clippedLeft,
    clippedRight = _ref.clippedRight,
    _ref$size = _ref.size,
    size = _ref$size === void 0 ? 'sm' : _ref$size;
  var textClass = size === 'xs' ? 'text-[9px]' : 'text-[10px]';
  return /*#__PURE__*/React.createElement(React.Fragment, null, clippedLeft ? /*#__PURE__*/React.createElement("span", {
    "aria-hidden": true,
    className: "pointer-events-none absolute left-0.5 top-1/2 z-[2] -translate-y-1/2 ".concat(textClass, " leading-none opacity-80")
  }, "\u25C0") : null, clippedRight ? /*#__PURE__*/React.createElement("span", {
    "aria-hidden": true,
    className: "pointer-events-none absolute right-0.5 top-1/2 z-[2] -translate-y-1/2 ".concat(textClass, " leading-none opacity-80")
  }, "\u25B6") : null);
}

/** 日视图 overlay 内单条预约/锁台：窄宽自适应与 Tooltip */
export function BookingCard(_ref2) {
  var _item$name;
  var booking = _ref2.booking,
    dayKey = _ref2.dayKey,
    onOpenDetail = _ref2.onOpenDetail,
    _onDragStart = _ref2.onDragStart,
    onJumpNext = _ref2.onJumpNext,
    overlayWidthPx = _ref2.overlayWidthPx;
  /** HTML5 拖拽结束后浏览器常对源元素追加一次 click，避免误开详情 */
  var suppressDetailClickAfterDragRef = useRef(false);
  var suppressDetailClickTimerRef = useRef(null);
  useEffect(function () {
    return function () {
      if (suppressDetailClickTimerRef.current != null) {
        window.clearTimeout(suppressDetailClickTimerRef.current);
      }
    };
  }, []);
  var armSuppressDetailClickAfterDrag = function armSuppressDetailClickAfterDrag() {
    suppressDetailClickAfterDragRef.current = true;
    if (suppressDetailClickTimerRef.current != null) {
      window.clearTimeout(suppressDetailClickTimerRef.current);
    }
    suppressDetailClickTimerRef.current = window.setTimeout(function () {
      suppressDetailClickAfterDragRef.current = false;
      suppressDetailClickTimerRef.current = null;
    }, 500);
  };
  var item = booking.item,
    span = booking.span,
    start = booking.start,
    continuesNext = booking.continuesNext,
    continuesPrev = booking.continuesPrev;
  var displayTag = getDisplayStatusTag(item, dayKey);
  var lateMinutes = getLateMinutes(item, dayKey);
  var stateClass = getBookingStateClasses(item, dayKey);
  var w = overlayWidthPx != null && Number.isFinite(overlayWidthPx) ? overlayWidthPx : Number.POSITIVE_INFINITY;
  var narrow = w < DAY_BOOKING_NARROW_PX;
  var micro = w < DAY_BOOKING_MICRO_PX;
  var microMark = Array.from(String((_item$name = item.name) !== null && _item$name !== void 0 ? _item$name : '').trim())[0] || '·';

  /**
   * 跨日延续视觉标记：booking 的 segment 已被 buildOverlayBookings 截到当日 grid 范围内
   *   - `continuesPrev` → 起点在前一日（左端贴边） → 在 pill 左端绘 ◀
   *   - `continuesNext` → 终点在次日（右端贴边） → 在 pill 右端绘 ▶
   */
  var renderClipMarkers = function renderClipMarkers() {
    return /*#__PURE__*/React.createElement(React.Fragment, null, continuesPrev && /*#__PURE__*/React.createElement("span", {
      "aria-hidden": true,
      className: "pointer-events-none absolute left-1 top-1/2 z-[1] -translate-y-1/2 text-[10px] leading-none opacity-90"
    }, "\u25C0"), continuesNext && /*#__PURE__*/React.createElement("span", {
      "aria-hidden": true,
      className: "pointer-events-none absolute right-1 top-1/2 z-[1] -translate-y-1/2 text-[10px] leading-none opacity-90"
    }, "\u25B6"));
  };
  var tooltipTitle = /*#__PURE__*/React.createElement("div", {
    className: "max-w-[260px] space-y-1 text-left"
  }, /*#__PURE__*/React.createElement("div", {
    className: "text-sm font-semibold"
  }, item.name), item.kind === 'block' && item.note && /*#__PURE__*/React.createElement("div", {
    className: "text-xs opacity-90"
  }, item.note), /*#__PURE__*/React.createElement("div", {
    className: "text-xs tabular-nums opacity-90"
  }, formatHourLabel(start), " - ", formatHourLabel(start + span)), item.kind === 'block' && getBlockMetaLine(item) && /*#__PURE__*/React.createElement("div", {
    className: "text-[11px] opacity-80"
  }, getBlockMetaLine(item)), continuesNext && /*#__PURE__*/React.createElement("div", {
    className: "text-[11px] text-violet-200"
  }, tCal('pisell2.recordBoard.calendar.card.continuesNext')), item.kind !== 'block' && displayTag && statusTagMeta(displayTag) && /*#__PURE__*/React.createElement("div", {
    className: "text-[11px] opacity-90"
  }, statusTagMeta(displayTag).label, lateMinutes && displayTag === 'late' ? " \xB7 ".concat(tCal('pisell2.recordBoard.calendar.card.lateMinutesDetail', {
    n: lateMinutes
  })) : ''));
  var wrapNarrow = function wrapNarrow(node) {
    return narrow ? /*#__PURE__*/React.createElement(Tooltip, {
      title: tooltipTitle,
      placement: "top",
      mouseEnterDelay: 0.12,
      destroyTooltipOnHide: true
    }, node) : node;
  };
  if (item.kind === 'block') {
    var blockWide = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      className: "truncate text-sm font-medium"
    }, item.name), item.note && /*#__PURE__*/React.createElement("div", {
      className: "mt-1 truncate text-xs text-zinc-200/90"
    }, item.note), getBlockMetaLine(item) && /*#__PURE__*/React.createElement("div", {
      className: "mt-1 truncate text-[10px] text-zinc-300/80"
    }, getBlockMetaLine(item)));
    var blockCompact = micro ? /*#__PURE__*/React.createElement("span", {
      className: "flex h-full w-full items-center justify-center text-[11px] font-semibold leading-none"
    }, microMark) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      className: "truncate text-[11px] font-medium leading-tight"
    }, item.name), getBlockMetaLine(item) && /*#__PURE__*/React.createElement("div", {
      className: "mt-0.5 truncate text-[10px] opacity-80"
    }, getBlockMetaLine(item)));
    var blockPad = micro ? 'px-0.5 py-0.5 flex items-center justify-center' : narrow ? 'px-2 py-2' : 'px-3 py-3 text-left';
    return wrapNarrow( /*#__PURE__*/React.createElement("button", {
      type: "button",
      "aria-label": narrow ? "".concat(item.name, ", ").concat(formatHourLabel(start), " - ").concat(formatHourLabel(start + span)) : undefined,
      onClick: function onClick(e) {
        e.stopPropagation();
        onOpenDetail(item);
      },
      className: "absolute inset-x-0 inset-y-0 rounded-2xl overflow-hidden ".concat(blockPad, " ").concat(narrow && !micro ? 'text-left' : '', " ").concat(stateClass)
    }, renderClipMarkers(), narrow ? blockCompact : blockWide));
  }

  /** 宽卡片：纵向紧密排列，去掉 flex-1 + mt-auto，避免单 lane 时在标题与徽标之间留出「假第二行」空白 */
  var bookingWide = /*#__PURE__*/React.createElement("div", {
    className: "flex min-h-0 min-w-0 w-full flex-col gap-1 overflow-hidden text-left"
  }, /*#__PURE__*/React.createElement("div", {
    className: "truncate text-sm font-medium leading-tight"
  }, item.name), /*#__PURE__*/React.createElement("div", {
    className: "truncate text-xs opacity-90 tabular-nums"
  }, formatHourLabel(start), " - ", formatHourLabel(start + span)), continuesNext && /*#__PURE__*/React.createElement("span", {
    role: "button",
    tabIndex: 0,
    onClick: function onClick(e) {
      e.stopPropagation();
      onJumpNext();
    },
    onKeyDown: function onKeyDown(e) {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        e.stopPropagation();
        onJumpNext();
      }
    },
    className: "inline-flex max-w-full cursor-pointer truncate rounded-lg bg-white/10 px-2 py-1 text-left text-[10px] leading-tight text-violet-100 sm:text-[11px]"
  }, tCal('pisell2.recordBoard.calendar.card.continuesNext')), (displayTag || lateMinutes) && /*#__PURE__*/React.createElement("div", {
    className: "flex shrink-0 flex-wrap items-center justify-end gap-1"
  }, lateMinutes && displayTag === 'late' && /*#__PURE__*/React.createElement("span", {
    className: "rounded-md bg-black/25 px-1.5 py-0.5 text-[10px] font-semibold text-white/90 backdrop-blur-[2px] opacity-80 sm:px-2"
  }, tCal('pisell2.recordBoard.calendar.card.lateMinutesBadge', {
    n: lateMinutes
  })), displayTag && statusTagMeta(displayTag) && /*#__PURE__*/React.createElement("span", {
    className: "rounded-lg px-1.5 py-0.5 text-[10px] font-semibold backdrop-blur-[2px] sm:px-2 ".concat(statusTagMeta(displayTag).className, " ").concat(lateMinutes ? 'opacity-80' : '')
  }, statusTagMeta(displayTag).label)));
  var bookingCompact = micro ? /*#__PURE__*/React.createElement("span", {
    className: "flex h-full w-full items-center justify-center text-[11px] font-semibold leading-none"
  }, microMark) : /*#__PURE__*/React.createElement("div", {
    className: "flex min-h-0 min-w-0 flex-col justify-start overflow-hidden"
  }, /*#__PURE__*/React.createElement("div", {
    className: "truncate text-[11px] font-medium leading-tight tabular-nums"
  }, item.name, " \xB7 ", formatHourLabel(start), "\u2013", formatHourLabel(start + span)));
  var bookingPad = micro ? 'px-0.5 py-0.5' : narrow ? 'px-1.5 py-1.5' : 'px-2 py-2 sm:px-4 sm:py-3';
  var bookingFlexMain = micro ? 'flex items-center justify-center' : 'flex min-h-0 flex-col justify-start';
  var bookingAlign = !narrow ? 'text-left' : micro ? '' : 'justify-start';

  // 跨日 booking 不支持拖拽改约（与 BookingCalendar.handleDropMove 早返回保持一致）
  var crossDay = !!(continuesPrev || continuesNext);
  return wrapNarrow( /*#__PURE__*/React.createElement("button", {
    type: "button",
    draggable: !crossDay,
    "aria-label": narrow ? "".concat(item.name, ", ").concat(formatHourLabel(start), " - ").concat(formatHourLabel(start + span)) : undefined,
    onDragStart: function onDragStart(e) {
      if (crossDay) {
        e.preventDefault();
        return;
      }
      e.stopPropagation();
      _onDragStart(item);
    },
    onDragEnd: function onDragEnd(e) {
      e.stopPropagation();
      armSuppressDetailClickAfterDrag();
    },
    onClick: function onClick(e) {
      if (suppressDetailClickAfterDragRef.current) {
        suppressDetailClickAfterDragRef.current = false;
        if (suppressDetailClickTimerRef.current != null) {
          window.clearTimeout(suppressDetailClickTimerRef.current);
          suppressDetailClickTimerRef.current = null;
        }
        e.preventDefault();
        e.stopPropagation();
        return;
      }
      e.stopPropagation();
      onOpenDetail(item);
    },
    className: "absolute inset-x-0 inset-y-0 rounded-2xl overflow-hidden ".concat(bookingFlexMain, " ").concat(bookingAlign, " ").concat(bookingPad, " ").concat(stateClass)
  }, renderClipMarkers(), narrow ? bookingCompact : bookingWide));
}