"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const is = require("../_utils/is.js");
const observerPool = /* @__PURE__ */ new WeakMap();
let instance = null;
function createObserverInstance() {
  if (!instance) {
    const observer = new ResizeObserver((entries) => {
      entries.forEach((entry) => {
        var _a;
        const ele = entry.target;
        const ins = observerPool.get(ele);
        if (!ins) {
          return;
        }
        (_a = ins == null ? void 0 : ins.callbacks) == null ? void 0 : _a.forEach((fn) => fn(entry, ins.isFirst));
        if (ins.isFirst) {
          ins.isFirst = false;
        }
      });
    });
    instance = {
      observer,
      record: 0
    };
  }
  return instance;
}
function useResizeObserver() {
  const instance2 = createObserverInstance();
  return {
    /**
     * 监听实例
     */
    observer: instance2,
    /**
     * 创建监听实例
     * el: 监听元素
     * listener: resize回调, 移除监听时需要指定该监听函数
     */
    observe: (el, listener) => {
      if (!el || !is.isFunction(listener)) {
        return null;
      }
      const val = observerPool.get(el);
      if (val) {
        val.callbacks.push(listener);
      } else {
        instance2.observer.observe(el);
        instance2.record++;
        observerPool.set(el, {
          element: el,
          callbacks: [listener],
          isFirst: true
        });
      }
      return instance2;
    },
    /**
     * 移除监听
     * el: 要移除监听的元素
     * listener: 要移除的监听函数，如果不传，则使用初始化时的onResize回调
     */
    unobserve: (el, listener) => {
      if (!el || !is.isFunction(listener) || !instance2) {
        return;
      }
      const val = observerPool.get(el);
      if (val) {
        const idx = val.callbacks.indexOf(listener);
        val.callbacks.splice(idx, 1);
        if (val.callbacks.length === 0) {
          instance2.observer.unobserve(el);
          observerPool.delete(el);
          instance2.record--;
          if (instance2.record === 0) {
            instance2.observer.disconnect();
          }
        }
      }
    },
    destroy() {
      instance2.observer.disconnect();
    }
  };
}
exports.useResizeObserver = useResizeObserver;
