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 _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); }
import { useCallback, useRef, useSyncExternalStore } from 'react';

/**
 * OS 模块订阅句柄：所有 OS 模块（BaseModule 子类）都暴露 `effectsOn(event, cb): () => void`。
 */

/**
 * 浅比较两个对象的"自身可枚举属性"。null/undefined 视作空对象。
 */
function shallowEqual(a, b) {
  if (Object.is(a, b)) return true;
  if (_typeof(a) !== 'object' || a === null || _typeof(b) !== 'object' || b === null) {
    return false;
  }
  var ka = Object.keys(a);
  var kb = Object.keys(b);
  if (ka.length !== kb.length) return false;
  for (var _i = 0, _ka = ka; _i < _ka.length; _i++) {
    var k = _ka[_i];
    if (!Object.prototype.hasOwnProperty.call(b, k)) return false;
    if (!Object.is(a[k], b[k])) return false;
  }
  return true;
}

/**
 * 通用 useSyncExternalStore 适配 OS effects 事件。
 *
 * 设计点：
 *  - subscribe 通过 `module.effectsOn(evt, onStoreChange)` 注册多事件，返回组合 cleanup。
 *  - getSnapshot 在 React 内部维护 lastSnapshotRef + isEqual 浅比较，确保未变更时返回稳定引用，
 *    避免 React 18 在 useSyncExternalStore 中因引用变化反复 tear（getServerSnapshot 同体引用）。
 *  - 调用方传入的 events 数组用 join('|') 作为 subscribe 依赖项，避免数组每次新引用导致重订阅。
 *
 * 示例：
 *   const data = useSyncOsModule(
 *     bookingTicket,
 *     ['onSalesOrderLoaded'],
 *     () => ({
 *       tempOrder: bookingTicket?.getTempOrder() ?? null,
 *       summary: bookingTicket?.getSalesOrder()?.summary ?? null,
 *     }),
 *   );
 */
export function useSyncOsModule(module, events, getSnapshot) {
  var isEqual = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : shallowEqual;
  var lastSnapshotRef = useRef({
    value: undefined,
    initialized: false
  });
  var stableGetSnapshot = useCallback(function () {
    var next = getSnapshot();
    var cache = lastSnapshotRef.current;
    if (!cache.initialized) {
      cache.value = next;
      cache.initialized = true;
      return next;
    }
    if (isEqual(cache.value, next)) {
      return cache.value;
    }
    cache.value = next;
    return next;
    // 调用方在每次调用 useSyncOsModule 时传入新 getSnapshot 闭包，
    // 但 useSyncExternalStore 仅在 subscribe 触发时调用 getSnapshot，
    // 所以此处对 getSnapshot 不放进 deps（保持函数本体可变但语义稳定即可）。
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isEqual]);
  var eventsKey = events.join('|');
  var subscribe = useCallback(function (onStoreChange) {
    if (!module) return function () {};
    var offs = events.map(function (evt) {
      return module.effectsOn(evt, onStoreChange);
    });
    return function () {
      var _iterator = _createForOfIteratorHelper(offs),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var off = _step.value;
          try {
            off();
          } catch (_unused) {
            // 静默处理：OS 卸载顺序不保证，已下线模块的 off 可能抛错，不影响订阅清理整体性。
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    };
    // events 数组用 join 串后作为依赖，避免每次 [] 新引用引发重订阅
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [module, eventsKey]);
  return useSyncExternalStore(subscribe, stableGetSnapshot, stableGetSnapshot);
}