/**
 * SalesSdk 全局 Holder 字典同步桥（供 booking selectHolderModal 等非 Context 组件调用）。
 */

var upsertHolderOptionsFn = null;
var reloadHolderOptionsFn = null;

/**
 * 由 SalesSdkHolderProvider 挂载时注册。
 *
 * @example
 * const off = registerHolderOptionsSyncBridge({ upsertHolderOptions, reload });
 * return off;
 */
export function registerHolderOptionsSyncBridge(api) {
  upsertHolderOptionsFn = api.upsertHolderOptions;
  reloadHolderOptionsFn = api.reload;
  return function () {
    if (upsertHolderOptionsFn === api.upsertHolderOptions) {
      upsertHolderOptionsFn = null;
      reloadHolderOptionsFn = null;
    }
  };
}

/**
 * 将原始 Holder 记录乐观写入购物车展示字典。
 *
 * @example
 * syncHolderOptionsFromRaw([{ form_record_id: 52981, main_field: 'Tom' }]);
 */
export function syncHolderOptionsFromRaw(rawHolders) {
  var _upsertHolderOptionsF;
  if (!(rawHolders !== null && rawHolders !== void 0 && rawHolders.length)) return;
  (_upsertHolderOptionsF = upsertHolderOptionsFn) === null || _upsertHolderOptionsF === void 0 || _upsertHolderOptionsF(rawHolders);
}

/**
 * 触发全局 Holder 字典重新拉取。
 *
 * @example
 * reloadGlobalHolderOptions();
 */
export function reloadGlobalHolderOptions() {
  var _reloadHolderOptionsF;
  (_reloadHolderOptionsF = reloadHolderOptionsFn) === null || _reloadHolderOptionsF === void 0 || _reloadHolderOptionsF();
}

/**
 * 按 holder_id 从 pet.holders 中挑出对应记录并同步。
 *
 * @example
 * syncHolderOptionsByIds([52981], petHolders);
 */
export function syncHolderOptionsByIds(holderIds, rawHolders) {
  if (!holderIds.length) return;
  var list = Array.isArray(rawHolders) ? rawHolders : [];
  var idSet = new Set(holderIds.map(function (id) {
    return String(id);
  }));
  var matched = list.filter(function (item) {
    var _ref, _item$form_record_id;
    var id = (_ref = (_item$form_record_id = item === null || item === void 0 ? void 0 : item.form_record_id) !== null && _item$form_record_id !== void 0 ? _item$form_record_id : item === null || item === void 0 ? void 0 : item.id) !== null && _ref !== void 0 ? _ref : item === null || item === void 0 ? void 0 : item.value;
    return id !== undefined && id !== null && idSet.has(String(id));
  });
  if (matched.length) {
    syncHolderOptionsFromRaw(matched);
    return;
  }
  syncHolderOptionsFromRaw(holderIds.map(function (id) {
    return {
      form_record_id: id
    };
  }));
}