function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
 * IntersectionObserver 组件
 * 用于监听一组 DOM 元素的可见性状态，并获取第一个可见元素的索引。
 * @example
 * function App() {
 *   return (
 *     <IntersectionObserverProvider
 *       onFirstVisibleIndexChange={(index) => {
 *         console.log('第一个可见元素的索引:', index);
 *       }}
 *       rootMargin="0px 0px -10% 0px" // 自定义根边距
 *     >
 *       <ScrollContainer>
 *         {items.map((item, index) => (
 *           <IntersectionItem key={item.id} index={index}>
 *             <ItemComponent data={item} />
 *           </IntersectionItem>
 *         ))}
 *       </ScrollContainer>
 *     </IntersectionObserverProvider>
 *   );
 * }
 */

import React, { createContext, useContext, useState, useRef, useEffect, useCallback, useMemo } from 'react';
/**
 * 简易 useMemoizedFn hook
 */
function useMemoizedFn(fn) {
  var fnRef = useRef(fn);
  var memoizedFn = useRef();

  // 更新最新的函数引用
  fnRef.current = fn;
  if (!memoizedFn.current) {
    memoizedFn.current = function () {
      return fnRef.current.apply(fnRef, arguments);
    };
  }
  return memoizedFn.current;
}

/**
 * 元素信息接口
 */

/**
 * IntersectionObserver 上下文值接口
 */

/**
 * IntersectionObserver Provider 属性接口
 */

/**
 * IntersectionItem 组件属性接口
 */

/**
 * IntersectionObserver 上下文
 */
var IntersectionObserverContext = /*#__PURE__*/createContext({
  initialized: false,
  registerElement: function registerElement() {},
  unregisterElement: function unregisterElement() {},
  registerElements: function registerElements() {},
  clearAll: function clearAll() {},
  firstVisibleIndex: -1
});
export var IntersectionObserverProvider = function IntersectionObserverProvider(_ref) {
  var children = _ref.children,
    _ref$root = _ref.root,
    root = _ref$root === void 0 ? null : _ref$root,
    _ref$rootMargin = _ref.rootMargin,
    rootMargin = _ref$rootMargin === void 0 ? '0px' : _ref$rootMargin,
    _ref$threshold = _ref.threshold,
    threshold = _ref$threshold === void 0 ? 0 : _ref$threshold,
    onFirstVisibleIndexChange = _ref.onFirstVisibleIndexChange,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    initialized = _useState2[0],
    setInitialized = _useState2[1];
  var _useState3 = useState(-1),
    _useState4 = _slicedToArray(_useState3, 2),
    firstVisibleIndex = _useState4[0],
    setFirstVisibleIndex = _useState4[1];
  var observerRef = useRef(null);
  var elementsMapRef = useRef(new Map());
  var pendingRegistrationsRef = useRef([]);
  var firstVisibleIndexRef = useRef(-1);
  var onFirstVisibleIndexChangeRef = useRef(onFirstVisibleIndexChange);

  // 同步回调函数引用
  useEffect(function () {
    onFirstVisibleIndexChangeRef.current = onFirstVisibleIndexChange;
  });

  // 同步索引值
  useEffect(function () {
    firstVisibleIndexRef.current = firstVisibleIndex;
  });

  /**
   * 计算第一个可见元素的索引
   */
  var calculateFirstVisibleIndex = useCallback(function () {
    var minIndex = -1;

    // 直接在迭代中找最小索引，避免创建数组和排序
    elementsMapRef.current.forEach(function (elementInfo) {
      if (elementInfo.isVisible) {
        if (minIndex === -1 || elementInfo.index < minIndex) {
          minIndex = elementInfo.index;
        }
      }
    });
    return minIndex;
  }, []);

  /**
   * 更新第一个可见元素索引
   */
  var updateFirstVisibleIndex = useMemoizedFn(function () {
    var newIndex = calculateFirstVisibleIndex();
    if (newIndex !== firstVisibleIndexRef.current) {
      var _onFirstVisibleIndexC;
      setFirstVisibleIndex(newIndex);
      (_onFirstVisibleIndexC = onFirstVisibleIndexChangeRef.current) === null || _onFirstVisibleIndexC === void 0 || _onFirstVisibleIndexC.call(onFirstVisibleIndexChangeRef, newIndex);
    }
  });

  /**
   * 创建 IntersectionObserver 实例
   */
  var observerOptions = useMemo(function () {
    return {
      root: root,
      rootMargin: rootMargin,
      threshold: threshold
    };
  }, [root, rootMargin, threshold]);
  var createObserver = useCallback(function () {
    if (disabled) {
      return null;
    }
    if (typeof window === 'undefined' || !window.IntersectionObserver) {
      console.warn('IntersectionObserver is not supported in this browser');
      return null;
    }
    return new IntersectionObserver(function (entries) {
      var hasChanged = false;
      entries.forEach(function (entry) {
        var elementInfo = elementsMapRef.current.get(entry.target);
        if (elementInfo) {
          var wasVisible = elementInfo.isVisible;
          var isVisible = entry.isIntersecting;
          if (wasVisible !== isVisible) {
            elementInfo.isVisible = isVisible;
            hasChanged = true;
          }
        }
      });
      if (hasChanged) {
        updateFirstVisibleIndex();
      }
    }, observerOptions);
  }, [observerOptions, disabled]);

  /**
   * 实际执行注册逻辑
   */
  var doRegisterElement = useCallback(function (element, index) {
    if (!observerRef.current || !element) {
      return false;
    }

    // 如果元素已存在，更新索引
    if (elementsMapRef.current.has(element)) {
      var _elementInfo = elementsMapRef.current.get(element);
      if (_elementInfo.index !== index) {
        _elementInfo.index = index;
      }
      return true;
    }
    var elementInfo = {
      element: element,
      index: index,
      isVisible: false
    };
    elementsMapRef.current.set(element, elementInfo);
    observerRef.current.observe(element);
    return true;
  }, []);

  /**
   * 处理待注册队列中的元素
   */
  var processPendingRegistrations = useMemoizedFn(function () {
    var pending = pendingRegistrationsRef.current;
    pendingRegistrationsRef.current = [];
    pending.forEach(function (_ref2) {
      var element = _ref2.element,
        index = _ref2.index;
      doRegisterElement(element, index);
    });
  });

  /**
   * 注册元素
   */
  var registerElement = useCallback(function (element, index) {
    if (!element) {
      return;
    }

    // 如果 observer 准备好了，直接注册
    if (observerRef.current) {
      doRegisterElement(element, index);
      return;
    }

    // 如果 observer 还没准备好，添加到待注册队列
    var existingIndex = pendingRegistrationsRef.current.findIndex(function (item) {
      return item.element === element;
    });
    if (existingIndex === -1) {
      pendingRegistrationsRef.current.push({
        element: element,
        index: index
      });
    } else {
      // 更新已存在元素的索引
      pendingRegistrationsRef.current[existingIndex].index = index;
    }
  }, [doRegisterElement]);

  /**
   * 注销元素
   */
  var unregisterElement = useCallback(function (element) {
    if (!element) {
      return;
    }

    // 从待注册队列中移除
    var pendingIndex = pendingRegistrationsRef.current.findIndex(function (item) {
      return item.element === element;
    });
    if (pendingIndex !== -1) {
      pendingRegistrationsRef.current.splice(pendingIndex, 1);
    }

    // 从已注册的元素中移除
    if (observerRef.current && elementsMapRef.current.has(element)) {
      elementsMapRef.current.delete(element);
      observerRef.current.unobserve(element);
      updateFirstVisibleIndex();
    }
  }, []);

  /**
   * 批量注册元素
   */
  var registerElements = useCallback(function (elements) {
    elements.forEach(function (_ref3) {
      var element = _ref3.element,
        index = _ref3.index;
      registerElement(element, index);
    });
  }, [registerElement]);

  /**
   * 清除所有注册的元素
   */
  var clearAll = useCallback(function () {
    // 清除待注册队列
    pendingRegistrationsRef.current = [];

    // 注销所有已注册的元素
    if (observerRef.current) {
      elementsMapRef.current.forEach(function (_, element) {
        observerRef.current.unobserve(element);
      });
    }

    // 清除映射
    elementsMapRef.current.clear();

    // 重置索引
    updateFirstVisibleIndex();
  }, []);

  /**
   * 初始化 IntersectionObserver
   */
  useEffect(function () {
    var observer = createObserver();
    if (observer) {
      observerRef.current = observer;

      // 处理在 observer 创建前尝试注册的元素
      processPendingRegistrations();
      setInitialized(true);
    }
    return function () {
      if (observerRef.current) {
        observerRef.current.disconnect();
        observerRef.current = null;
      }
      elementsMapRef.current.clear();
      pendingRegistrationsRef.current = [];
      setInitialized(false);
      setFirstVisibleIndex(-1);
    };
  }, [createObserver]);
  var contextValue = useMemo(function () {
    return {
      initialized: initialized,
      registerElement: registerElement,
      unregisterElement: unregisterElement,
      registerElements: registerElements,
      clearAll: clearAll,
      firstVisibleIndex: firstVisibleIndex
    };
  }, [initialized, registerElement, unregisterElement, registerElements, clearAll, firstVisibleIndex]);
  return /*#__PURE__*/React.createElement(IntersectionObserverContext.Provider, {
    value: contextValue
  }, children);
};

/**
 * 使用 IntersectionObserver 的 Hook
 * @returns {Object} 包含注册元素函数和第一个可见元素索引的对象
 */
export var useIntersectionObserver = function useIntersectionObserver() {
  var context = useContext(IntersectionObserverContext);
  if (!context) {
    throw new Error('useIntersectionObserver must be used within IntersectionObserverProvider');
  }
  return context;
};

/**
 * IntersectionItem 组件
 * 自动注册元素到 IntersectionObserver 中
 */
export var IntersectionItem = function IntersectionItem(_ref4) {
  var index = _ref4.index,
    children = _ref4.children,
    className = _ref4.className,
    style = _ref4.style;
  var elementRef = useRef(null);
  var _useIntersectionObser = useIntersectionObserver(),
    initialized = _useIntersectionObser.initialized,
    registerElement = _useIntersectionObser.registerElement,
    unregisterElement = _useIntersectionObser.unregisterElement;
  useEffect(function () {
    var element = elementRef.current;
    if (initialized && element) {
      registerElement(element, index);
      return function () {
        unregisterElement(element);
      };
    }
  }, [initialized, index, registerElement, unregisterElement]);
  return /*#__PURE__*/React.createElement("div", {
    ref: elementRef,
    className: className,
    style: style
  }, children);
};

// 导出类型和组件

export { IntersectionObserverContext };
export default IntersectionObserverProvider;