// @ts-nocheck
import React from 'react';
import { courtDaySummary, dayOccupancy, fmtDate, formatHourLabel } from "../utils/bookingCalendarDateUtils";
import { CALENDAR_EMPTY_DASHED_SLOT_CLASSNAME, dayRowHeight, frozenColWidth } from "../const/bookingCalendarConstants";
import { CALENDAR_WEEKDAY_IDS, tCal } from "../calendarI18n";
import { getGridBookingRowStateClasses } from "../utils/BookingCalendarStyle";
import { getRemainingToneClass } from "../bookingCalendarViewShared";
import { BookingCalendarGroupRowHeader } from "./BookingCalendarGroupRowHeader";

/**
 * 周视图：7 日网格 + 左侧分组（可折叠），单元格调起日视图；格内 drop 触发改期草稿。
 */
export function BookingCalendarWeekView(_ref) {
  var calendarProps = _ref.calendarProps,
    isLight = _ref.isLight,
    weekDays = _ref.weekDays,
    bookings = _ref.bookings,
    courts = _ref.courts,
    hourSlots = _ref.hourSlots,
    slotStepHours = _ref.slotStepHours,
    visibleCourts = _ref.visibleCourts,
    visibleCourtRows = _ref.visibleCourtRows,
    isBusinessHour = _ref.isBusinessHour,
    goToDayFromCell = _ref.goToDayFromCell,
    handleGridDropMove = _ref.handleGridDropMove,
    openBookingDetail = _ref.openBookingDetail,
    setDraggingItem = _ref.setDraggingItem,
    setCollapsedGroups = _ref.setCollapsedGroups,
    overflowPopover = _ref.overflowPopover,
    setOverflowPopover = _ref.setOverflowPopover,
    overflowListModal = _ref.overflowListModal,
    setOverflowListModal = _ref.setOverflowListModal,
    overflowPanelRef = _ref.overflowPanelRef;
  var props = calendarProps;
  var todayKey = fmtDate(new Date());
  /** 与下方 grid `minmax(…px, 1fr)` 一致：窄屏由外层 overflow-auto + min-w-0 定视口宽，本值撑开 scrollWidth */
  var weekDayColMinPx = 150;
  var weekGridMinWidthPx = frozenColWidth + weekDays.length * weekDayColMinPx;
  return /*#__PURE__*/React.createElement("div", {
    key: "week-".concat(fmtDate(weekDays[0])),
    className: "flex min-h-0 flex-1 flex-col"
  }, /*#__PURE__*/React.createElement("div", {
    className: "relative flex min-h-0 min-w-0 flex-1 flex-col"
  }, /*#__PURE__*/React.createElement("div", {
    className: "theme-panel pisell-scroll-hidden min-h-0 min-w-0 max-h-none flex-1 overflow-auto touch-pan-x touch-pan-y select-none",
    style: {
      overscrollBehavior: 'none'
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "grid",
    style: {
      minWidth: weekGridMinWidthPx,
      gridTemplateColumns: "".concat(frozenColWidth, "px repeat(").concat(weekDays.length, ", minmax(").concat(weekDayColMinPx, "px, 1fr))")
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "grid sticky top-0 z-50",
    style: {
      gridColumn: '1 / -1',
      gridTemplateColumns: "".concat(frozenColWidth, "px repeat(").concat(weekDays.length, ", minmax(").concat(weekDayColMinPx, "px, 1fr))"),
      isolation: 'isolate'
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "sticky left-0 z-30 flex w-[132px] min-w-[132px] max-w-[132px] items-center px-2.5 py-3 font-semibold border-b shadow-[8px_0_16px_rgba(0,0,0,0.08)] ".concat(isLight ? 'theme-sticky theme-border theme-text' : 'bg-[#241d40] border-zinc-800')
  }, tCal('pisell2.recordBoard.calendar.week.headerCourtDate')), weekDays.map(function (day, i) {
    var key = fmtDate(day);
    var isToday = key === todayKey;
    var dayItems = bookings.filter(function (b) {
      return b.date === key;
    });
    var fullyBooked = courts.every(function (court) {
      return hourSlots.filter(isBusinessHour).every(function (h) {
        return dayOccupancy(court.id, key, bookings, hourSlots, slotStepHours)[h];
      });
    });
    return /*#__PURE__*/React.createElement("div", {
      key: key,
      className: "relative z-20 border-b border-l px-1.5 py-2 text-center shadow-[0_8px_16px_rgba(0,0,0,0.06)] ".concat(isLight ? 'theme-border theme-text' : 'border-zinc-800', " ").concat(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]')
    }, /*#__PURE__*/React.createElement("div", {
      className: "text-sm leading-tight ".concat(isLight ? 'theme-text-faint' : 'text-zinc-400')
    }, tCal(CALENDAR_WEEKDAY_IDS[i])), /*#__PURE__*/React.createElement("div", {
      className: "mt-0.5 flex justify-center"
    }, /*#__PURE__*/React.createElement("span", {
      className: "grid h-10 w-10 place-items-center text-3xl font-semibold leading-none",
      "aria-label": isToday ? 'Today' : undefined
    }, day.getDate())));
  })), visibleCourtRows.map(function (row) {
    return /*#__PURE__*/React.createElement(React.Fragment, {
      key: row.id
    }, row.kind === 'group' ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(BookingCalendarGroupRowHeader, {
      isLight: isLight,
      view: "week",
      row: {
        id: row.id,
        label: row.label,
        count: row.count,
        collapsed: row.collapsed
      },
      renderResourceCell: props.renderResourceCell,
      setCollapsedGroups: setCollapsedGroups
    }), weekDays.map(function (day) {
      var key = fmtDate(day);
      var groupCourts = visibleCourts.filter(function (court) {
        return court.type === row.label;
      });
      var noRatioCell = groupCourts.length === 0;
      var total = groupCourts.length;
      var remaining = 0;
      var ratio = 0;
      if (!noRatioCell) {
        /** 周视图汇总：该日该台「有任何条」即算忙，空闲数 = 全组台数 − 有日程的台数 */
        var busyCount = groupCourts.filter(function (court) {
          var summary = courtDaySummary(court.id, key, bookings, hourSlots, slotStepHours);
          return summary.items.length > 0;
        }).length;
        remaining = total - busyCount;
        ratio = total > 0 ? remaining / total : 0;
      }
      return /*#__PURE__*/React.createElement("div", {
        key: "".concat(row.id, "-").concat(key),
        style: {
          minHeight: dayRowHeight
        },
        className: "flex h-full items-center justify-center border-b border-l px-1.5 py-1 text-center text-sm font-medium ".concat(isLight ? 'theme-border' : 'border-zinc-800', " ").concat(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__*/React.createElement("div", {
        className: "text-xs opacity-60"
      }, "\u2014") : /*#__PURE__*/React.createElement("div", {
        className: "text-xs font-semibold leading-none ".concat(getRemainingToneClass(ratio, isLight))
      }, tCal('pisell2.recordBoard.calendar.day.freeRatio', {
        remaining: remaining,
        total: total
      })));
    })) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      className: "sticky left-0 z-30 flex h-full min-h-0 w-[132px] min-w-[132px] max-w-[132px] items-center border-b px-2.5 py-1.5 shadow-[8px_0_16px_rgba(0,0,0,0.06)] ".concat(isLight ? 'theme-sticky theme-border' : 'border-zinc-800 bg-[#1a1a22]'),
      style: {
        minHeight: dayRowHeight
      }
    }, props.renderResourceCell ? props.renderResourceCell({
      view: 'week',
      row: {
        kind: 'court',
        id: row.id,
        name: row.name,
        type: row.type
      },
      isLight: isLight
    }) : /*#__PURE__*/React.createElement("div", {
      className: "pisell-rb-cal-week-resource-name min-w-0 w-full font-semibold text-[16px] leading-tight"
    }, row.name)), weekDays.map(function (day) {
      var key = fmtDate(day);
      var summary = courtDaySummary(row.id, key, bookings, hourSlots, slotStepHours);
      var previewItems = summary.items.slice(0, 3);
      var moreItems = summary.items.slice(3);
      var moreCount = moreItems.length;
      var showMoreTile = moreCount > 0 && previewItems.length > 0;
      return /*#__PURE__*/React.createElement("button", {
        key: "".concat(row.id, "-").concat(key),
        onClick: function onClick() {
          return goToDayFromCell(day, row.id, "week-".concat(row.id, "-").concat(key));
        },
        onDragOver: function onDragOver(e) {
          return e.preventDefault();
        },
        onDrop: function onDrop(e) {
          e.preventDefault();
          handleGridDropMove(key, row.id);
        },
        style: {
          minHeight: dayRowHeight
        },
        className: "relative flex h-full flex-col justify-start border-b border-l p-1 text-left align-top transition outline-none ".concat(isLight ? 'theme-border' : 'border-zinc-700', " ").concat(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')
      }, summary.fullyBooked ? /*#__PURE__*/React.createElement("div", {
        className: "min-h-[28px] w-full rounded-lg bg-zinc-700/70",
        "aria-hidden": true
      }) : summary.items.length > 0 ? /*#__PURE__*/React.createElement("div", {
        className: "flex w-full flex-col items-start gap-1"
      }, previewItems.map(function (item, idx) {
        var isLastVisible = idx === previewItems.length - 1;
        var shrinkForMore = showMoreTile && isLastVisible;
        var layoutClassName = "rounded-lg px-2.5 py-1.5 text-xs text-left ".concat(getGridBookingRowStateClasses(item), " ").concat(shrinkForMore ? 'flex-1 min-w-0' : 'w-full');
        return /*#__PURE__*/React.createElement("div", {
          key: idx,
          className: "flex w-full items-stretch gap-1.5"
        }, props.renderMonthWeekBooking ? /*#__PURE__*/React.createElement("div", {
          className: shrinkForMore ? 'flex-1 min-w-0' : 'w-full'
        }, props.renderMonthWeekBooking({
          item: item,
          dateKey: key,
          view: 'week',
          isLight: isLight,
          layoutClassName: layoutClassName,
          onOpenDetail: openBookingDetail,
          onDragStart: function onDragStart(it) {
            return setDraggingItem(it);
          },
          draggable: false
        })) : /*#__PURE__*/React.createElement("button", {
          type: "button",
          onClick: function onClick(e) {
            e.stopPropagation();
            openBookingDetail(item);
          },
          className: layoutClassName
        }, /*#__PURE__*/React.createElement("div", {
          className: "truncate"
        }, item.name), /*#__PURE__*/React.createElement("div", {
          className: "mt-1 opacity-80"
        }, formatHourLabel(item.startHour), " -", ' ', formatHourLabel(item.endHour))), shrinkForMore && /*#__PURE__*/React.createElement("div", {
          className: "relative h-[52px] w-[52px] shrink-0",
          ref: (overflowPopover === null || overflowPopover === void 0 ? void 0 : overflowPopover.courtId) === row.id && (overflowPopover === null || overflowPopover === void 0 ? void 0 : overflowPopover.date) === key ? overflowPanelRef : null
        }, /*#__PURE__*/React.createElement("button", {
          onMouseEnter: function onMouseEnter(e) {
            e.stopPropagation();
            setOverflowPopover({
              courtId: row.id,
              date: key,
              items: moreItems,
              pinned: false
            });
          },
          onClick: function onClick(e) {
            e.stopPropagation();
            setOverflowPopover(null);
            setOverflowListModal(function (prev) {
              return prev && prev.scope === row.id && prev.date === key ? null : {
                scope: row.id,
                date: key,
                title: tCal('pisell2.recordBoard.calendar.overflow.listTitleAllBookings', {
                  date: key
                }),
                items: summary.items.filter(function (x) {
                  return x.kind === 'booking';
                })
              };
            });
          },
          className: "flex h-[52px] w-[52px] items-center justify-center rounded-xl bg-violet-700/90 text-sm font-semibold text-white"
        }, "+", moreCount)));
      })) : /*#__PURE__*/React.createElement("div", {
        className: "".concat(CALENDAR_EMPTY_DASHED_SLOT_CLASSNAME, " text-center ").concat(isLight ? 'border-[#d8d0eb] text-[#8f86a9]' : 'border-zinc-700 text-zinc-500'),
        "aria-hidden": true
      }));
    })));
  })))));
}