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); }
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 _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, { useRef, useEffect, useState, useCallback, useMemo } from 'react';
var InfiniteScroll = function InfiniteScroll(_ref) {
  var dataLength = _ref.dataLength,
    next = _ref.next,
    hasMore = _ref.hasMore,
    _ref$loader = _ref.loader,
    loader = _ref$loader === void 0 ? /*#__PURE__*/React.createElement("div", null, "Loading...") : _ref$loader,
    endMessage = _ref.endMessage,
    height = _ref.height,
    _ref$scrollThreshold = _ref.scrollThreshold,
    scrollThreshold = _ref$scrollThreshold === void 0 ? 0.8 : _ref$scrollThreshold,
    onScroll = _ref.onScroll,
    style = _ref.style,
    className = _ref.className,
    scrollableTarget = _ref.scrollableTarget,
    children = _ref.children,
    _ref$inverse = _ref.inverse,
    inverse = _ref$inverse === void 0 ? false : _ref$inverse;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isLoading = _useState2[0],
    setIsLoading = _useState2[1];
  var containerRef = useRef(null);
  var lastDataLength = useRef(dataLength);
  var scrollTimeoutRef = useRef(null);
  var isMountedRef = useRef(true);
  var lastCallTimeRef = useRef(0);

  // 节流函数
  var throttle = useCallback(function (func, delay) {
    return function () {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
      scrollTimeoutRef.current = setTimeout(function () {
        return func.apply(void 0, args);
      }, delay);
    };
  }, []);

  // 计算滚动阈值
  var getScrollThreshold = useCallback(function () {
    if (typeof scrollThreshold === 'string' && scrollThreshold.endsWith('px')) {
      return parseInt(scrollThreshold.replace('px', ''), 10);
    }
    return typeof scrollThreshold === 'number' ? scrollThreshold : 0.8;
  }, [scrollThreshold]);

  // 检查是否需要加载更多
  var checkScrollPosition = useCallback(function (element) {
    if (!element || !hasMore || isLoading) return;
    var threshold = getScrollThreshold();
    var scrollTop = element.scrollTop,
      scrollHeight = element.scrollHeight,
      clientHeight = element.clientHeight;

    // 防止无效的滚动值（但不直接返回，而是记录警告）
    if (scrollHeight <= 0 || clientHeight <= 0) {
      console.warn('InfiniteScroll: 检测到无效的滚动容器尺寸');
      return;
    }

    // 防止scrollTop为负值（某些浏览器可能出现）
    var normalizedScrollTop = Math.max(0, scrollTop);
    var shouldLoadMore = false;
    if (inverse) {
      // 反向滚动模式：检查是否滚动到顶部
      if (typeof threshold === 'number' && threshold < 1) {
        // 百分比阈值
        var scrollPercentage = normalizedScrollTop / scrollHeight;
        shouldLoadMore = scrollPercentage <= 1 - threshold;
      } else {
        // 像素阈值
        shouldLoadMore = normalizedScrollTop <= threshold;
      }
    } else {
      // 正常滚动模式：检查是否滚动到底部
      if (typeof threshold === 'number' && threshold < 1) {
        // 百分比阈值
        var _scrollPercentage = (normalizedScrollTop + clientHeight) / scrollHeight;
        shouldLoadMore = _scrollPercentage >= threshold;
      } else {
        // 像素阈值
        var remainingHeight = scrollHeight - normalizedScrollTop - clientHeight;
        shouldLoadMore = remainingHeight <= threshold;
      }
    }
    if (shouldLoadMore) {
      var now = Date.now();
      // 防重复调用机制：500ms内只允许一次调用
      if (now - lastCallTimeRef.current < 500) {
        return;
      }
      lastCallTimeRef.current = now;
      setIsLoading(true);
      try {
        next();
      } catch (error) {
        console.error('InfiniteScroll: 加载更多数据时发生错误:', error);
        if (isMountedRef.current) {
          setIsLoading(false);
        }
      }
    }
  }, [hasMore, isLoading, next, getScrollThreshold, inverse]);

  // 检查内容高度是否足够，如果不够则自动加载更多
  var checkInitialLoad = useCallback(function () {
    var element = scrollableTarget ? document.getElementById(scrollableTarget) : containerRef.current;
    if (!element || !hasMore || isLoading) return;
    var scrollHeight = element.scrollHeight,
      clientHeight = element.clientHeight;

    // 防止无效的容器尺寸
    if (clientHeight <= 0) {
      console.warn('InfiniteScroll: 容器高度无效，可能容器尚未渲染完成');
      return;
    }

    // 如果内容高度不足以填满容器，或者没有任何内容，自动加载更多
    var needsMoreContent = scrollHeight <= clientHeight || dataLength === 0;
    if (needsMoreContent) {
      var now = Date.now();
      // 防重复调用机制：500ms内只允许一次调用
      if (now - lastCallTimeRef.current < 500) {
        return;
      }
      lastCallTimeRef.current = now;
      setIsLoading(true);
      try {
        next();
      } catch (error) {
        console.error('InfiniteScroll: 初始加载时发生错误:', error);
        if (isMountedRef.current) {
          setIsLoading(false);
        }
      }
    }
  }, [hasMore, isLoading, next, scrollableTarget, dataLength]);

  // 滚动事件处理（使用节流）
  var handleScrollInternal = useCallback(function (event) {
    try {
      // 获取正确的滚动元素
      var element = event.target;

      // 额外的安全检查
      if (!element || typeof element.scrollTop === 'undefined') {
        console.warn('InfiniteScroll: 无效的滚动目标元素');
        return;
      }
      checkScrollPosition(element);
      if (onScroll) {
        onScroll(event);
      }
    } catch (error) {
      console.error('InfiniteScroll: 滚动事件处理时发生错误:', error);
    }
  }, [checkScrollPosition, onScroll]);
  var handleScroll = useMemo(function () {
    return throttle(handleScrollInternal, 16);
  },
  // 约60fps
  [throttle, handleScrollInternal]);

  // 监听数据长度变化，重置加载状态
  useEffect(function () {
    if (dataLength !== lastDataLength.current) {
      if (isMountedRef.current) {
        setIsLoading(false);
      }
      lastDataLength.current = dataLength;
    }
  }, [dataLength]);

  // 组件卸载时的清理
  useEffect(function () {
    return function () {
      isMountedRef.current = false;
    };
  }, []);

  // 清理定时器
  useEffect(function () {
    return function () {
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
    };
  }, []);

  // 检查初始内容高度，确保首屏有足够内容
  useEffect(function () {
    // 使用setTimeout确保DOM已经渲染
    var timeoutId = setTimeout(function () {
      checkInitialLoad();
    }, 100);
    return function () {
      return clearTimeout(timeoutId);
    };
  }, [checkInitialLoad, dataLength]);

  // 当数据加载完成后，再次检查是否需要继续加载
  useEffect(function () {
    if (!isLoading && hasMore) {
      var timeoutId = setTimeout(function () {
        checkInitialLoad();
      }, 100);
      return function () {
        return clearTimeout(timeoutId);
      };
    }
  }, [isLoading, hasMore, checkInitialLoad]);

  // 设置滚动监听
  useEffect(function () {
    var element = scrollableTarget ? document.getElementById(scrollableTarget) : containerRef.current;
    if (!element) {
      console.warn('InfiniteScroll: 无法找到滚动容器元素');
      return;
    }

    // 使用类型安全的事件处理器
    var scrollHandler = handleScroll;
    element.addEventListener('scroll', scrollHandler, {
      passive: true
    });
    return function () {
      // 确保清理所有事件监听器
      if (element) {
        element.removeEventListener('scroll', scrollHandler);
      }
    };
  }, [handleScroll, scrollableTarget]);
  var containerStyle = useMemo(function () {
    return _objectSpread(_objectSpread(_objectSpread({}, style), height && {
      height: typeof height === 'number' ? "".concat(height, "px") : height,
      overflowY: 'auto'
    }), inverse && {
      display: 'flex',
      flexDirection: 'column-reverse'
    });
  }, [style, height, inverse]);
  return /*#__PURE__*/React.createElement("div", {
    ref: !scrollableTarget ? containerRef : undefined,
    className: className,
    style: containerStyle
  }, inverse ? /*#__PURE__*/React.createElement(React.Fragment, null, isLoading && hasMore && loader, !hasMore && endMessage, children) : /*#__PURE__*/React.createElement(React.Fragment, null, children, isLoading && hasMore && loader, !hasMore && endMessage));
};
export default InfiniteScroll;