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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 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); }
/**
 * 资源墙（Venue Wall）共用工具：六态键、默认色板、倒计时文案、卡片状态推导、配色合并与 diff。
 */

import { getText } from "../../../../locales";

/** 单态展示配置（与 {@link VENUE_WALL_STATUS_COLOR_MAP} 值同形） */

/** 仅覆盖部分字段；用于 Control Panel / localStorage */

/** 单外观（浅 / 深）下的占用/空闲色与六态覆盖；持久化时 light、dark 各存一份 */

export var VENUE_WALL_STATUS_KEYS = ['inUse', 'endingSoon', 'expired', 'available', 'boardingSoon', 'late'];

/**
 * 六态默认色与占位英文；`getVenueWallStatusToneMap` 会将 label/note 换为 i18n，此处仅作 merge 基底。
 */
export var VENUE_WALL_STATUS_COLOR_MAP = {
  inUse: {
    key: 'inUse',
    label: 'In Use',
    note: 'This court is currently in use.',
    color: '#6f4ae6',
    noteBg: 'rgba(111,74,230,0.92)'
  },
  endingSoon: {
    key: 'endingSoon',
    label: 'Ending Soon',
    note: 'Please leave on time to avoid overtime charges.',
    color: '#f59e0b',
    noteBg: 'rgba(245,158,11,0.96)'
  },
  expired: {
    key: 'expired',
    label: 'Expired',
    note: 'This booking has ended. Please clear the court.',
    color: '#ef4444',
    noteBg: 'rgba(239,68,68,0.96)'
  },
  available: {
    key: 'available',
    label: 'Available',
    note: 'This court is now available.',
    /** 大屏空闲态：淡灰中性色（与占用紫、预约紫区分） */
    color: '#94a3b8',
    noteBg: 'rgba(148,163,184,0.22)'
  },
  boardingSoon: {
    key: 'boardingSoon',
    label: 'Boarding Soon',
    note: 'Please check in to start.',
    color: '#6f4ae6',
    noteBg: 'rgba(111,74,230,0.18)'
  },
  late: {
    key: 'late',
    label: 'Late',
    note: 'Please check in as soon as possible.',
    /** 与超时/结束同系红，大屏提醒迟到 */
    color: '#ef4444',
    noteBg: 'rgba(239,68,68,0.22)'
  }
};

/** 将 `#RGB` / `#RRGGBB` 转为 `rgba(...)`，供渐变与半透明底 */
export function alphaColor(hex, alpha) {
  var clean = hex.replace('#', '');
  var full = clean.length === 3 ? clean.split('').map(function (c) {
    return c + c;
  }).join('') : clean;
  var num = parseInt(full, 16);
  var r = num >> 16 & 255;
  var g = num >> 8 & 255;
  var b = num & 255;
  return "rgba(".concat(r, ", ").concat(g, ", ").concat(b, ", ").concat(alpha, ")");
}

/** 将数值限制在 [min, max]（布局行列、主文案比例等） */
export var clamp = function clamp(value, min, max) {
  return Math.max(min, Math.min(max, value));
};

/** 由卡片字段推导状态键（与演示页 test.tsx 规则一致） */
export function deriveVenueWallStatus(card) {
  var s = card.status;
  if (s === 'available') return 'available';
  if (s === 'boardingSoon') return 'boardingSoon';
  if (s === 'late') return 'late';
  if (s === 'endingSoon') return 'endingSoon';
  if (s === 'expired') return 'expired';
  if (s === 'inUse') return 'inUse';

  /** 兼容旧数据：无 status 时退回 remainingMin 推断（不再看 light 字段） */
  if (card.currentBooking === 'Available to Book') return 'available';
  var rm = card.remainingMin;
  if (rm != null && rm <= 0) return 'expired';
  if (rm != null && rm <= 10) return 'endingSoon';
  return 'inUse';
}

/**
 * ToolBar Sort 写入的 `searchParams.sort`（如 `status:asc:string`）拆出字段名与升降序。
 */
export function parseRecordBoardToolbarSortParam(sort) {
  if (sort == null || typeof sort !== 'string') return null;
  var idx = sort.indexOf(':');
  if (idx <= 0) return null;
  var field = sort.slice(0, idx);
  var rest = sort.slice(idx + 1);
  var dirSep = rest.indexOf(':');
  var dirRaw = dirSep >= 0 ? rest.slice(0, dirSep) : rest;
  if (dirRaw !== 'asc' && dirRaw !== 'desc') return null;
  return {
    field: field,
    dir: dirRaw
  };
}

/** 当 Sort 字段名匹配这些 key（忽略大小写）时，资源墙按占用态重排卡片 */
export var DEFAULT_RESOURCE_WALL_STATUS_SORT_FIELD_KEYS = ['status'];
export function matchesResourceWallStatusSortField(sortField, keys) {
  var n = sortField.trim().toLowerCase();
  return keys.some(function (k) {
    return k.trim().toLowerCase() === n;
  });
}

/**
 * 用于资源墙排序：占用/将结/已结束为 1，其余为 0（与 {@link deriveVenueWallStatus} 一致）。
 * asc → 空闲侧在前；desc → 占用侧在前。
 */
export function venueWallOccupiedSortRank(card) {
  var k = deriveVenueWallStatus(card);
  return k === 'inUse' || k === 'endingSoon' || k === 'expired' ? 1 : 0;
}
export function formatDurationHM(minAbs) {
  var safe = Number.isFinite(minAbs) ? Math.max(0, Math.floor(minAbs)) : 0;
  if (safe < 60) return "".concat(safe, "m");
  var h = Math.floor(safe / 60);
  var m = safe % 60;
  /** `11h 28m`：h 与分钟之间加空格，避免 `11h28m` 连成一体难读 */
  return "".concat(h, "h ").concat(String(m).padStart(2, '0'), "m");
}

/**
 * 将「剩余/超支分钟数」格式化为跑码条/主副标题用短文案（走 i18n 模板，负值表示 overtime）。
 */
export function formatVenueWallCountdown(min) {
  if (min < 0) {
    var n = formatDurationHM(Math.abs(min));
    return getText('pisell-resource-wall-countdown-overtime').replace('{n}', n);
  }
  if (min === 0) return getText('pisell-resource-wall-countdown-ending-now');
  return getText('pisell-resource-wall-countdown-left').replace('{n}', formatDurationHM(min));
}
function cloneTone(t) {
  return _objectSpread({}, t);
}

/**
 * 合并默认六态配色与业务覆盖，供 {@link VenueWallCard} 与 Control Panel 表单初值共用。
 */
export function getVenueWallStatusToneMap(overrides) {
  var out = {};
  var _iterator = _createForOfIteratorHelper(VENUE_WALL_STATUS_KEYS),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var key = _step.value;
      var base = cloneTone(VENUE_WALL_STATUS_COLOR_MAP[key]);
      base.label = getText("pisell-resource-wall-tone-".concat(key, "-label"));
      base.note = getText("pisell-resource-wall-tone-".concat(key, "-note"));
      var patch = overrides === null || overrides === void 0 ? void 0 : overrides[key];
      out[key] = patch ? _objectSpread(_objectSpread(_objectSpread({}, base), patch), {}, {
        key: key
      }) : base;
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return out;
}

/**
 * 将编辑后的完整六态表压成「相对默认」的 overrides，便于持久化与 props 传递。
 */
export function diffVenueWallStatusToneOverrides(draft) {
  var defaults = getVenueWallStatusToneMap();
  var out = {};
  var _iterator2 = _createForOfIteratorHelper(VENUE_WALL_STATUS_KEYS),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var k = _step2.value;
      var d = draft[k];
      var b = defaults[k];
      var patch = {};
      if (d.label !== b.label) patch.label = d.label;
      if (d.note !== b.note) patch.note = d.note;
      if (d.color !== b.color) patch.color = d.color;
      if (d.noteBg !== b.noteBg) patch.noteBg = d.noteBg;
      if (Object.keys(patch).length > 0) out[k] = patch;
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return out;
}