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); }
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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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 _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); }
export function asRecord(value) {
  if (!value || _typeof(value) !== 'object' || Array.isArray(value)) {
    return undefined;
  }
  return value;
}
export function asRecordList(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  return value.map(function (item) {
    return asRecord(item);
  }).filter(Boolean);
}
export function asString(value) {
  if (value === undefined || value === null || value === '') {
    return undefined;
  }
  return String(value);
}
export function asNumber(value) {
  var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var next = Number(value);
  return Number.isFinite(next) ? next : fallback;
}
function getMetadataRecord(source) {
  var _asRecord;
  return asRecord((_asRecord = asRecord(source)) === null || _asRecord === void 0 ? void 0 : _asRecord.metadata) || {};
}
function getCustomerIdentity(orderDetail) {
  return (orderDetail === null || orderDetail === void 0 ? void 0 : orderDetail.customer_with_extra) || (orderDetail === null || orderDetail === void 0 ? void 0 : orderDetail.customer);
}
export function defaultFormatHourLabel(hour) {
  var normalizedMinutes = Math.round(hour * 60);
  var wholeHours = Math.floor(normalizedMinutes / 60);
  var minutes = normalizedMinutes % 60;
  return "".concat(String(wholeHours).padStart(2, '0'), ":").concat(String(minutes).padStart(2, '0'));
}
export function getHourStep(hourSlots) {
  if (hourSlots.length < 2) {
    return 1;
  }
  var sorted = _toConsumableArray(hourSlots).sort(function (a, b) {
    return a - b;
  });
  var minStep = Number.POSITIVE_INFINITY;
  for (var index = 1; index < sorted.length; index += 1) {
    var step = sorted[index] - sorted[index - 1];
    if (step > 0 && step < minStep) {
      minStep = step;
    }
  }
  return Number.isFinite(minStep) ? minStep : 1;
}
export function getFallbackHourSlots() {
  return Array.from({
    length: 24
  }, function (_, index) {
    return index;
  });
}
export function nearestHourInSlots(hour, slots) {
  if (!Number.isFinite(hour) || slots.length === 0) return hour;
  var best = slots[0];
  var bestDist = Math.abs(hour - best);
  var _iterator = _createForOfIteratorHelper(slots),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var slot = _step.value;
      var distance = Math.abs(hour - slot);
      if (distance < bestDist - 1e-9) {
        bestDist = distance;
        best = slot;
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return best;
}
export function alignBookingDraftToSlots(targetHour, durationHours, slots) {
  if (!Number.isFinite(durationHours) || durationHours < 0 || slots.length === 0) {
    return targetHour;
  }
  var endRaw = targetHour + durationHours;
  var endAligned = nearestHourInSlots(endRaw, slots);
  var startAligned = nearestHourInSlots(endAligned - durationHours, slots);
  var endCheck = nearestHourInSlots(startAligned + durationHours, slots);
  startAligned = nearestHourInSlots(endCheck - durationHours, slots);
  return startAligned;
}
function formatDateKey(date) {
  var year = date.getFullYear();
  var month = "".concat(date.getMonth() + 1).padStart(2, '0');
  var day = "".concat(date.getDate()).padStart(2, '0');
  return "".concat(year, "-").concat(month, "-").concat(day);
}
export function getNormalizedDateTime(dateKey, hour) {
  var date = new Date("".concat(dateKey, "T00:00:00"));
  if (Number.isNaN(date.getTime())) {
    return {
      date: dateKey,
      time: defaultFormatHourLabel(hour)
    };
  }
  var minutes = Math.round(hour * 60);
  date.setMinutes(date.getMinutes() + minutes);
  return {
    date: formatDateKey(date),
    time: "".concat(String(date.getHours()).padStart(2, '0'), ":").concat(String(date.getMinutes()).padStart(2, '0'))
  };
}
function normalizeCombinedResource(value) {
  var record = asRecord(value);
  if (!record || !Array.isArray(record.resource_ids)) {
    return undefined;
  }
  return {
    status: asNumber(record.status, 0),
    resource_ids: record.resource_ids.map(function (resourceId) {
      return Number(resourceId);
    }).filter(function (resourceId) {
      return Number.isFinite(resourceId);
    })
  };
}
export function getItemRaw(item) {
  return asRecord(item.raw) || {};
}
export function getOrderId(item) {
  var raw = getItemRaw(item);
  var orderId = raw.order_id;
  if (typeof orderId === 'string' || typeof orderId === 'number') {
    return orderId;
  }
  return null;
}
export function getItemResourceRecords(item) {
  var rawResources = asRecordList(getItemRaw(item).resources);
  if (rawResources.length > 0) {
    return rawResources.map(normalizeResourceNode);
  }
  return asRecordList(item.resources).map(normalizeResourceNode);
}
function normalizeResourceNode(resource) {
  return {
    form_id: resource.form_id,
    relation_type: resource.relation_type,
    relation_id: resource.relation_id,
    capacity: asNumber(resource.capacity, 0),
    like_status: resource.like_status,
    metadata: getMetadataRecord(resource),
    children: asRecordList(resource.children).map(normalizeResourceNode)
  };
}
export function normalizeCourt(court) {
  return {
    id: court.id,
    name: court.name,
    form_id: court.form_id,
    relation_id: court.relation_id,
    relation_type: court.relation_type,
    resource_id: court.resource_id,
    capacity: asNumber(court.capacity, 0),
    like_status: court.like_status,
    metadata: getMetadataRecord(court),
    raw: asRecord(court.raw)
  };
}
export function getScheduleResourceList(response) {
  if (Array.isArray(response)) {
    return asRecordList(response);
  }
  var record = asRecord(response);
  if (Array.isArray(record === null || record === void 0 ? void 0 : record.list)) {
    return asRecordList(record.list);
  }
  if (Array.isArray(record === null || record === void 0 ? void 0 : record.data)) {
    return asRecordList(record.data);
  }
  return [];
}
export function buildScheduleResourceCourt(resource, formName) {
  var id = asString(resource.id);
  var name = asString(resource.main_field);
  if (!id || !name) {
    return null;
  }
  var combinedResource = normalizeCombinedResource(resource.combined_resource);
  return {
    id: id,
    name: name,
    form_id: resource.form_id,
    relation_id: resource.id,
    resource_id: resource.id,
    relation_type: 'form',
    capacity: asNumber(resource.capacity, 0),
    like_status: 'common',
    metadata: _objectSpread({
      form_name: formName,
      resource_name: name
    }, combinedResource ? {
      combined_resource: combinedResource
    } : {}),
    raw: resource
  };
}
export function mergeCourts(lists) {
  var merged = new Map();
  var _iterator2 = _createForOfIteratorHelper(lists),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var list = _step2.value;
      var _iterator3 = _createForOfIteratorHelper(list),
        _step3;
      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var court = _step3.value;
          if (!(court !== null && court !== void 0 && court.id)) {
            continue;
          }
          merged.set(court.id, _objectSpread(_objectSpread(_objectSpread({}, merged.get(court.id)), court), {}, {
            metadata: _objectSpread(_objectSpread({}, getMetadataRecord(merged.get(court.id))), getMetadataRecord(court))
          }));
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return Array.from(merged.values());
}
function buildCombinedChildren(targetCourt, resourceCourtMap) {
  var combinedResource = normalizeCombinedResource(targetCourt.metadata.combined_resource);
  if (!combinedResource || combinedResource.resource_ids.length === 0) {
    return undefined;
  }
  var children = combinedResource.resource_ids.map(function (resourceId) {
    return resourceCourtMap.get(String(resourceId));
  }).filter(function (court) {
    return Boolean(court);
  }).map(function (court) {
    return {
      form_id: court.form_id,
      relation_type: court.relation_type,
      relation_id: court.relation_id,
      capacity: court.capacity,
      like_status: court.like_status,
      metadata: _objectSpread(_objectSpread({}, court.metadata), {}, {
        form_name: court.metadata.form_name,
        resource_name: court.metadata.resource_name
      })
    };
  });
  return children.length > 0 ? children : undefined;
}
function buildChangedResource(originalResource, targetCourt, resourceCourtMap) {
  var metadata = _objectSpread(_objectSpread(_objectSpread({}, originalResource.metadata), targetCourt.metadata), {}, {
    form_name: targetCourt.metadata.form_name,
    resource_name: targetCourt.metadata.resource_name
  });
  var combinedResource = normalizeCombinedResource(targetCourt.metadata.combined_resource);
  if (combinedResource) {
    metadata.combined_resource = combinedResource;
  } else {
    delete metadata.combined_resource;
  }
  var children = buildCombinedChildren(targetCourt, resourceCourtMap);
  return _objectSpread({
    form_id: targetCourt.form_id,
    relation_type: targetCourt.relation_type,
    relation_id: targetCourt.relation_id,
    capacity: targetCourt.capacity,
    like_status: targetCourt.like_status,
    metadata: metadata
  }, children ? {
    children: children
  } : {});
}

/** Convert a single event_resource record into the submit payload format. */
function normalizeEventResourceForSubmit(res) {
  var children = asRecordList(res.children).map(normalizeEventResourceForSubmit);
  return _objectSpread({
    form_id: res.form_id,
    relation_type: res.relation_type || 'form',
    relation_id: res.relation_id,
    capacity: asNumber(res.capacity, 0),
    like_status: res.like_status || 'common',
    metadata: asRecord(res.metadata) || {}
  }, children.length > 0 ? {
    children: children
  } : {});
}

/**
 * Build the resources array for submit from the authoritative event_resources list
 * (sourced from orderDetail) and the per-resource court selections made in the UI.
 * When a resource's selected court differs from its original relation_id the resource
 * is replaced via buildChangedResource; otherwise it is emitted as-is.
 */
export function buildSubmitResourcesFromEventResources(eventResources, resourceCourtIds, resourceCourtMap) {
  return eventResources.map(function (res, i) {
    var selectedId = resourceCourtIds[i];
    var originalId = String(res.relation_id);
    if (selectedId && selectedId !== originalId) {
      var targetCourt = resourceCourtMap.get(selectedId);
      if (targetCourt) {
        return buildChangedResource(normalizeResourceNode(res), targetCourt, resourceCourtMap);
      }
    }
    return normalizeEventResourceForSubmit(res);
  });
}
function getSubmitScheduleId(raw, orderDetail) {
  var _orderDetail$bookings;
  var rawScheduleId = raw.schedule_id;
  if (rawScheduleId !== undefined && rawScheduleId !== null && rawScheduleId !== '') {
    return rawScheduleId;
  }
  var rawId = raw.id;
  if (rawId === undefined || rawId === null || rawId === '') {
    return undefined;
  }
  var matchedBooking = ((orderDetail === null || orderDetail === void 0 || (_orderDetail$bookings = orderDetail.bookings) === null || _orderDetail$bookings === void 0 ? void 0 : _orderDetail$bookings.list) || []).find(function (booking) {
    return String(booking === null || booking === void 0 ? void 0 : booking.id) === String(rawId);
  });
  return matchedBooking === null || matchedBooking === void 0 ? void 0 : matchedBooking.schedule_id;
}
export function buildSubmitPayload(args) {
  var item = args.item,
    draft = args.draft,
    duration = args.duration,
    nextEndHour = args.nextEndHour,
    currentEventResources = args.currentEventResources,
    resourceCourtIds = args.resourceCourtIds,
    resourceCourtMap = args.resourceCourtMap,
    orderDetail = args.orderDetail;
  var raw = getItemRaw(item);
  var rawMetadata = getMetadataRecord(raw);
  var start = getNormalizedDateTime(draft.targetDate, draft.targetHour);
  var end = getNormalizedDateTime(draft.targetDate, nextEndHour);
  var metadata = _objectSpread({}, rawMetadata);
  var resources = buildSubmitResourcesFromEventResources(currentEventResources, resourceCourtIds, resourceCourtMap);
  return {
    id: raw.id,
    relation_id: raw.relation_id,
    like_status: raw.like_status,
    relation_type: raw.relation_type,
    is_all: asNumber(raw.is_all, 0),
    schedule_id: getSubmitScheduleId(raw, orderDetail),
    sub_type: raw.sub_type,
    select_date: draft.targetDate,
    number: raw.number,
    metadata: metadata,
    resources: resources,
    start_date: start.date,
    start_time: start.time,
    end_date: end.date,
    end_time: end.time,
    duration: Math.max(0, Math.round(duration * 60))
  };
}
export function buildCustomer(args) {
  var _contacts$phone;
  var orderDetail = args.orderDetail,
    selectedCustomer = args.selectedCustomer,
    fallbackCustomerText = args.fallbackCustomerText;
  if (selectedCustomer) {
    return selectedCustomer;
  }
  var customer = getCustomerIdentity(orderDetail);
  var contacts = orderDetail === null || orderDetail === void 0 ? void 0 : orderDetail.contacts_info;
  return {
    name: (customer === null || customer === void 0 ? void 0 : customer.display_name) || (customer === null || customer === void 0 ? void 0 : customer.nickname) || fallbackCustomerText,
    phone: (contacts === null || contacts === void 0 || (_contacts$phone = contacts.phone) === null || _contacts$phone === void 0 ? void 0 : _contacts$phone.phone) || (customer === null || customer === void 0 ? void 0 : customer.phone) || '',
    email: (contacts === null || contacts === void 0 ? void 0 : contacts.email) || (customer === null || customer === void 0 ? void 0 : customer.email) || '',
    memberId: (customer === null || customer === void 0 ? void 0 : customer.member_id) || ''
  };
}