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); }
var _excluded = ["children", "className", "style"];
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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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; }
import React, { createContext, useContext, useState, useRef, useEffect, useCallback, useMemo } from 'react';
var IntersectionObserverContext = /*#__PURE__*/createContext({
  initialized: false,
  register: function register() {},
  unregister: function unregister() {}
});
var Provider = IntersectionObserverContext.Provider,
  Consumer = IntersectionObserverContext.Consumer;
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,
    priorityMode = _ref.priorityMode;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    mounted = _useState2[0],
    setMounted = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    initialized = _useState4[0],
    setInitialized = _useState4[1];
  var observerRef = useRef(null);
  var callbackMapRef = useRef(new Map());
  var findCallback = useCallback(function (target) {
    return callbackMapRef.current.get(target);
  }, []);

  // 选择优先级元素的函数
  var selectPriorityEntry = useCallback(function (entries, mode) {
    if (entries.length === 0) return undefined;
    if (entries.length === 1) return entries[0];
    switch (mode) {
      case 'top':
        return entries.reduce(function (prev, curr) {
          return curr.boundingClientRect.top < prev.boundingClientRect.top ? curr : prev;
        });
      case 'bottom':
        return entries.reduce(function (prev, curr) {
          return curr.boundingClientRect.bottom > prev.boundingClientRect.bottom ? curr : prev;
        });
      case 'left':
        return entries.reduce(function (prev, curr) {
          return curr.boundingClientRect.left < prev.boundingClientRect.left ? curr : prev;
        });
      case 'right':
        return entries.reduce(function (prev, curr) {
          return curr.boundingClientRect.right > prev.boundingClientRect.right ? curr : prev;
        });
      default:
        return entries[0];
    }
  }, []);

  // 创建 IntersectionObserver 实例
  var observerOptions = useMemo(function () {
    return {
      root: root,
      rootMargin: rootMargin,
      threshold: threshold
    };
  }, [root, rootMargin, threshold]);
  var createObserver = useCallback(function () {
    if (typeof window !== 'undefined' && !window.IntersectionObserver) {
      console.warn('IntersectionObserver is not supported in this browser');
      return null;
    }
    return new IntersectionObserver(function (entries) {
      if (entries.length === 0) return;
      try {
        // 如果没有设置priorityMode，触发所有元素的回调（包括可见和不可见）
        if (!priorityMode) {
          entries.forEach(function (entry) {
            var callback = findCallback(entry.target);
            if (callback) {
              callback(entry);
            }
          });
          return;
        }

        // 遍历处理所有元素
        var visibleEntries = [];
        var invisibleEntries = [];
        entries.forEach(function (entry) {
          if (entry.isIntersecting) {
            visibleEntries.push(entry);
          } else {
            invisibleEntries.push(entry);
          }
        });

        // 处理不可见元素
        invisibleEntries.forEach(function (entry) {
          var callback = findCallback(entry.target);
          if (callback) {
            callback(entry);
          }
        });

        // 处理可见元素，根据优先级选择一个
        if (visibleEntries.length > 0) {
          var selectedEntry = selectPriorityEntry(visibleEntries, priorityMode);
          if (selectedEntry) {
            var callback = findCallback(selectedEntry.target);
            if (callback) {
              callback(selectedEntry);
            }
          }
        }
      } catch (error) {
        console.error('IntersectionObserver callback error:', error);
      }
    }, observerOptions);
  }, [observerOptions, priorityMode, findCallback, selectPriorityEntry]);

  // 注册元素到观察器
  var register = useCallback(function (_ref2) {
    var ref = _ref2.ref,
      callback = _ref2.callback;
    if (ref !== null && ref !== void 0 && ref.current && observerRef !== null && observerRef !== void 0 && observerRef.current) {
      var element = ref.current;

      // 检查是否已经注册，避免重复注册
      if (callbackMapRef.current.has(element)) {
        return;
      }
      callbackMapRef.current.set(element, callback);
      observerRef.current.observe(element);
    }
  }, []);

  // 从观察器中注销元素
  var unregister = useCallback(function (_ref3) {
    var ref = _ref3.ref;
    if (ref !== null && ref !== void 0 && ref.current && observerRef !== null && observerRef !== void 0 && observerRef.current) {
      var element = ref.current;

      // 从Map中移除回调
      callbackMapRef.current.delete(element);
      observerRef.current.unobserve(element);
    }
  }, []);

  // 初始化观察器
  useEffect(function () {
    if (mounted) {
      // 清理旧的observer
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
      observerRef.current = createObserver();
      setInitialized(true);
    }
  }, [mounted, createObserver]);

  // 组件挂载和清理
  useEffect(function () {
    setMounted(true);
    return function () {
      if (observerRef.current) {
        observerRef.current.disconnect();
        callbackMapRef.current.clear();
        setInitialized(false);
      }
    };
  }, []);
  var contextValue = {
    initialized: initialized,
    register: register,
    unregister: unregister
  };
  return /*#__PURE__*/React.createElement(Provider, {
    value: contextValue
  }, children);
};

// IntersectionTrigger Hook - 内部使用
var useIntersectionTrigger = function useIntersectionTrigger(elementRef) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _options$once = options.once,
    once = _options$once === void 0 ? false : _options$once,
    onHide = options.onHide,
    onShow = options.onShow;
  var _useContext = useContext(IntersectionObserverContext),
    initialized = _useContext.initialized,
    register = _useContext.register,
    unregister = _useContext.unregister;
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    isIntersecting = _useState6[0],
    setIsIntersecting = _useState6[1];
  var cleanup = useCallback(function () {
    return unregister({
      ref: elementRef
    });
  }, [elementRef, unregister]);

  // 使用useCallback优化回调函数，避免竞态条件
  var intersectionCallback = useCallback(function (entry) {
    if (entry.isIntersecting) {
      onShow === null || onShow === void 0 || onShow(cleanup);
      if (once) {
        unregister({
          ref: elementRef
        });
      }
    } else {
      onHide === null || onHide === void 0 || onHide(cleanup);
    }
    setIsIntersecting(entry.isIntersecting);
  }, [onShow, onHide, once, cleanup, unregister, elementRef]);
  var registerRef = useRef();
  registerRef.current = function () {
    return register({
      ref: elementRef,
      callback: intersectionCallback
    });
  };
  useEffect(function () {
    if (initialized) {
      var _registerRef$current;
      (_registerRef$current = registerRef.current) === null || _registerRef$current === void 0 || _registerRef$current.call(registerRef);
    }
    return function () {
      cleanup();
    };
  }, [initialized, cleanup]);
  return {
    isIntersecting: isIntersecting
  };
};

// IntersectionTrigger 组件
export var IntersectionTrigger = function IntersectionTrigger(_ref4) {
  var children = _ref4.children,
    className = _ref4.className,
    _ref4$style = _ref4.style,
    style = _ref4$style === void 0 ? {} : _ref4$style,
    options = _objectWithoutProperties(_ref4, _excluded);
  var elementRef = useRef(null);
  // 使用内部 hook
  var _useIntersectionTrigg = useIntersectionTrigger(elementRef, options),
    isIntersecting = _useIntersectionTrigg.isIntersecting;
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    ref: elementRef,
    style: _objectSpread({
      width: '100%',
      height: '100%'
    }, style)
  }, children);
};

// 导出类型和组件

export { IntersectionObserverContext, Consumer as IntersectionObserverConsumer };
export default IntersectionObserverProvider;