function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
 * venueBooking 通用工具函数
 * 包含日期处理、时段格式化、网格布局、样式映射等工具
 * 注意：可用性 / 价格 / 预订状态等现在由 PisellOS venueBooking 模块直接提供，
 * 本文件只保留 UI 展示所需的纯辅助函数。
 */
import dayjs from 'dayjs';
import { locales } from '@pisell/utils';
export var SLOT_MINUTES = 30;
export var SLOTS_PER_HOUR = 2;
export var AUTO_VIEW_HOURS = 5;
export var FIRST_COLUMN_WIDTH = 120;
export var SLOT_MIN_WIDTH = 70;

// ── Date helpers (dayjs) ──

export function formatDateKey(date) {
  return date.format('YYYY-MM-DD');
}
export function parseDateKey(key) {
  return dayjs(key);
}
export function getWeekDays(anchor) {
  var weekStart = anchor.startOf('week');
  return Array.from({
    length: 7
  }, function (_, i) {
    return weekStart.add(i, 'day');
  });
}
export function getMonthLabel(date) {
  return date.format('MMMM YYYY');
}
export function getMonthDays(date) {
  var firstOfMonth = date.startOf('month');
  var daysInMonth = date.daysInMonth();
  var firstDayOfWeek = firstOfMonth.day();
  var offset = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1;
  var cells = [];
  for (var i = 0; i < offset; i++) cells.push(null);
  for (var d = 1; d <= daysInMonth; d++) {
    cells.push(firstOfMonth.date(d));
  }
  while (cells.length % 7 !== 0) cells.push(null);
  return cells;
}
export function getWeekdayShortLabel(date) {
  var weekday = date.day();
  if (weekday === 1) return String(locales.getText('pisell2.venue.calendar.weekday.short.mon') || '周一');
  if (weekday === 2) return String(locales.getText('pisell2.venue.calendar.weekday.short.tue') || '周二');
  if (weekday === 3) return String(locales.getText('pisell2.venue.calendar.weekday.short.wed') || '周三');
  if (weekday === 4) return String(locales.getText('pisell2.venue.calendar.weekday.short.thu') || '周四');
  if (weekday === 5) return String(locales.getText('pisell2.venue.calendar.weekday.short.fri') || '周五');
  if (weekday === 6) return String(locales.getText('pisell2.venue.calendar.weekday.short.sat') || '周六');
  return String(locales.getText('pisell2.venue.calendar.weekday.short.sun') || '周日');
}

// ── Time helpers ──

export function pad(n) {
  return String(n).padStart(2, '0');
}
export function timeToMinutes(time) {
  var _time$split$map = time.split(':').map(Number),
    _time$split$map2 = _slicedToArray(_time$split$map, 2),
    h = _time$split$map2[0],
    m = _time$split$map2[1];
  return h * 60 + m;
}
export function minutesToTime(minutes) {
  return "".concat(pad(Math.floor(minutes / 60)), ":").concat(pad(minutes % 60));
}
export function isHourBoundary(slot) {
  return slot.endsWith(':00');
}

/**
 * 格式化小时列头
 * 使用 i18n 模板 `pisell2.venue.time.hour.format`，支持 {suffix} / {hour} 两个占位符
 *   - en / pt: "{hour}{suffix}" → "6pm"
 *   - zh-CN / zh-TW: "{suffix}{hour}点/點" → "下午6点"
 *   - ja: "{suffix}{hour}時" → "午後6時"
 * 未命中模板时回退到 "{hour}{suffix}" 兼容旧行为
 */
export function formatHourHeader(slot) {
  var _slot$split$map = slot.split(':').map(Number),
    _slot$split$map2 = _slicedToArray(_slot$split$map, 1),
    hour = _slot$split$map2[0];
  var suffix = hour >= 12 ? locales.getText('pisell2.venue.time.pm') || 'pm' : locales.getText('pisell2.venue.time.am') || 'am';
  var hour12 = hour % 12 === 0 ? 12 : hour % 12;
  var template = locales.getText('pisell2.venue.time.hour.format') || '{hour}{suffix}';
  return template.replace('{hour}', String(hour12)).replace('{suffix}', suffix);
}

/** 从 timeLabels 中提取整点小时（用于表头合并列） */
export function buildHourGroups(timeLabels) {
  return timeLabels.filter(function (slot) {
    return slot.endsWith(':00');
  });
}

// ── DateMeta：从 dateSummary 获取日期元数据 ──

/**
 * 从 API 返回的 dateSummary 中查找指定日期的展示信息
 * 替代原来基于 mock 数据自行计算的逻辑
 */
export function getDateMetaFromSummary(date, dateSummary) {
  var symbol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '$';
  var dateKey = formatDateKey(date);
  var item = dateSummary.find(function (s) {
    return s.date === dateKey;
  });
  if (!item) {
    return {
      topTag: null,
      startingPrice: null,
      fewLeft: false,
      soldOut: true,
      unavailable: true
    };
  }
  var soldOut = item.status === 'sold_out' || item.status === 'unavailable';
  var fewLeft = item.status === 'few_left';
  var unavailable = item.status === 'unavailable';
  var startingPrice = item.startingPrice ? "".concat(symbol).concat(item.startingPrice, "+") : null;
  return {
    topTag: null,
    // API 暂不返回 topTag，后续可扩展
    startingPrice: soldOut || unavailable ? null : startingPrice,
    fewLeft: fewLeft,
    soldOut: soldOut,
    unavailable: unavailable
  };
}

// ── TimeSlotGrid 辅助函数 ──

/**
 * 获取资源维度的可用性概况（某个资源在当天的整体情况）
 */
export function getResourceCourtMeta(resource) {
  var total = resource.slots.length;
  var availableCount = resource.slots.filter(function (s) {
    return s.status === 'available';
  }).length;
  var ratio = total > 0 ? availableCount / total : 0;
  return {
    soldOut: availableCount === 0,
    fewLeft: availableCount > 0 && ratio < 0.2
  };
}

/**
 * 获取时段维度的可用性概况（某个时间点所有资源的情况）
 */
export function getTimeMetaFromGrid(resources, slotIndex) {
  var availableCount = resources.filter(function (r) {
    return r.slots[slotIndex] && r.slots[slotIndex].status === 'available';
  }).length;
  var ratio = resources.length > 0 ? availableCount / resources.length : 0;
  return {
    soldOut: availableCount === 0,
    fewLeft: availableCount > 0 && ratio < 0.2
  };
}

/**
 * 构建 SlotPriceInfo 用于价格样式映射
 * 从 VenueResourceSlot 的 price 转换为 UI 展示所需的格式
 */
export function buildSlotPriceInfo(slot) {
  var price = slot.price ? parseFloat(slot.price) : 0;
  return {
    price: price,
    originalPrice: null,
    label: '',
    // 后续可从 API 扩展标签信息
    highlight: false
  };
}

// ── 样式映射函数（Tailwind class 返回，不变） ──

export function getPriceColor(params) {
  if (params.highlight) return 'text-emerald-600';
  if (params.courtType === 'Pickleball') return 'vb-primary-text';
  return 'text-zinc-800';
}
export function getSlotTag(priceInfo) {
  if (priceInfo.highlight || priceInfo.label === 'Promo') {
    return {
      text: 'pisell2.venue.label.promo',
      className: 'bg-emerald-50 text-emerald-700 ring-emerald-200'
    };
  }
  if (priceInfo.label === 'Off-Peak') {
    return {
      text: 'pisell2.venue.label.off.peak',
      className: 'bg-zinc-100 text-zinc-600 ring-zinc-200'
    };
  }
  return null;
}

/**
 * 获取列头标签（某个时间点的统一标签）
 * 暂时返回 null，后续 API 可扩展返回标签信息
 */
export function getColumnTag(resources, slotIndex) {
  // API 暂不返回列级别标签，后续可扩展
  return null;
}

// ── Grid layout ──

export function getTableGridStyle(slotCount) {
  return {
    gridTemplateColumns: "".concat(FIRST_COLUMN_WIDTH, "px repeat(").concat(slotCount, ", minmax(").concat(SLOT_MIN_WIDTH, "px, 1fr))"),
    minWidth: "".concat(FIRST_COLUMN_WIDTH + slotCount * SLOT_MIN_WIDTH, "px"),
    width: '100%'
  };
}

// ── Auto-scroll helpers ──

/** 找到第一个有 available 时段的 slot 索引 */
export function getFirstAvailableSlotIndex(grid) {
  if (!grid) return 0;
  var _loop = function _loop(i) {
      var hasAvailable = grid.resources.some(function (r) {
        return r.slots[i] && r.slots[i].status === 'available';
      });
      if (hasAvailable) return {
        v: i
      };
    },
    _ret;
  for (var i = 0; i < grid.timeLabels.length; i++) {
    _ret = _loop(i);
    if (_ret) return _ret.v;
  }
  return 0;
}
export function getSuggestedStartHourIndex(params) {
  var firstAvailableIndex = params.firstAvailableIndex,
    totalHours = params.totalHours;
  var earliestHour = Math.floor(firstAvailableIndex / SLOTS_PER_HOUR) + 1;
  var maxStartHour = Math.max(1, totalHours - AUTO_VIEW_HOURS + 1);
  if (earliestHour <= AUTO_VIEW_HOURS) return 1;
  return Math.max(1, Math.min(maxStartHour, earliestHour));
}

// ── Display helpers ──

export function formatRange(start, end) {
  return "".concat(start, " - ").concat(end);
}
export function getDateDisplay(dateKey) {
  return dayjs(dateKey).format('ddd, D MMM YYYY');
}