var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/clinetSearch/InfiniteScroll/InfiniteScroll.tsx
var InfiniteScroll_exports = {};
__export(InfiniteScroll_exports, {
  default: () => InfiniteScroll_default
});
module.exports = __toCommonJS(InfiniteScroll_exports);
var import_react = __toESM(require("react"));
var InfiniteScroll = ({
  dataLength,
  next,
  hasMore,
  loader = /* @__PURE__ */ import_react.default.createElement("div", null, "Loading..."),
  endMessage,
  height,
  scrollThreshold = 0.8,
  onScroll,
  style,
  className,
  scrollableTarget,
  children,
  inverse = false
}) => {
  const [isLoading, setIsLoading] = (0, import_react.useState)(false);
  const containerRef = (0, import_react.useRef)(null);
  const lastDataLength = (0, import_react.useRef)(dataLength);
  const scrollTimeoutRef = (0, import_react.useRef)(null);
  const isMountedRef = (0, import_react.useRef)(true);
  const lastCallTimeRef = (0, import_react.useRef)(0);
  const throttle = (0, import_react.useCallback)((func, delay) => {
    return (...args) => {
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
      scrollTimeoutRef.current = setTimeout(() => func(...args), delay);
    };
  }, []);
  const getScrollThreshold = (0, import_react.useCallback)(() => {
    if (typeof scrollThreshold === "string" && scrollThreshold.endsWith("px")) {
      return parseInt(scrollThreshold.replace("px", ""), 10);
    }
    return typeof scrollThreshold === "number" ? scrollThreshold : 0.8;
  }, [scrollThreshold]);
  const checkScrollPosition = (0, import_react.useCallback)(
    (element) => {
      if (!element || !hasMore || isLoading) return;
      const threshold = getScrollThreshold();
      const { scrollTop, scrollHeight, clientHeight } = element;
      if (scrollHeight <= 0 || clientHeight <= 0) {
        console.warn("InfiniteScroll: 检测到无效的滚动容器尺寸");
        return;
      }
      const normalizedScrollTop = Math.max(0, scrollTop);
      let shouldLoadMore = false;
      if (inverse) {
        if (typeof threshold === "number" && threshold < 1) {
          const scrollPercentage = normalizedScrollTop / scrollHeight;
          shouldLoadMore = scrollPercentage <= 1 - threshold;
        } else {
          shouldLoadMore = normalizedScrollTop <= threshold;
        }
      } else {
        if (typeof threshold === "number" && threshold < 1) {
          const scrollPercentage = (normalizedScrollTop + clientHeight) / scrollHeight;
          shouldLoadMore = scrollPercentage >= threshold;
        } else {
          const remainingHeight = scrollHeight - normalizedScrollTop - clientHeight;
          shouldLoadMore = remainingHeight <= threshold;
        }
      }
      if (shouldLoadMore) {
        const now = Date.now();
        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]
  );
  const checkInitialLoad = (0, import_react.useCallback)(() => {
    const element = scrollableTarget ? document.getElementById(scrollableTarget) : containerRef.current;
    if (!element || !hasMore || isLoading) return;
    const { scrollHeight, clientHeight } = element;
    if (clientHeight <= 0) {
      console.warn("InfiniteScroll: 容器高度无效，可能容器尚未渲染完成");
      return;
    }
    const needsMoreContent = scrollHeight <= clientHeight || dataLength === 0;
    if (needsMoreContent) {
      const now = Date.now();
      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]);
  const handleScrollInternal = (0, import_react.useCallback)(
    (event) => {
      try {
        const 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]
  );
  const handleScroll = (0, import_react.useMemo)(
    () => throttle(handleScrollInternal, 16),
    // 约60fps
    [throttle, handleScrollInternal]
  );
  (0, import_react.useEffect)(() => {
    if (dataLength !== lastDataLength.current) {
      if (isMountedRef.current) {
        setIsLoading(false);
      }
      lastDataLength.current = dataLength;
    }
  }, [dataLength]);
  (0, import_react.useEffect)(() => {
    return () => {
      isMountedRef.current = false;
    };
  }, []);
  (0, import_react.useEffect)(() => {
    return () => {
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
    };
  }, []);
  (0, import_react.useEffect)(() => {
    const timeoutId = setTimeout(() => {
      checkInitialLoad();
    }, 100);
    return () => clearTimeout(timeoutId);
  }, [checkInitialLoad, dataLength]);
  (0, import_react.useEffect)(() => {
    if (!isLoading && hasMore) {
      const timeoutId = setTimeout(() => {
        checkInitialLoad();
      }, 100);
      return () => clearTimeout(timeoutId);
    }
  }, [isLoading, hasMore, checkInitialLoad]);
  (0, import_react.useEffect)(() => {
    const element = scrollableTarget ? document.getElementById(scrollableTarget) : containerRef.current;
    if (!element) {
      console.warn("InfiniteScroll: 无法找到滚动容器元素");
      return;
    }
    const scrollHandler = handleScroll;
    element.addEventListener("scroll", scrollHandler, { passive: true });
    return () => {
      if (element) {
        element.removeEventListener("scroll", scrollHandler);
      }
    };
  }, [handleScroll, scrollableTarget]);
  const containerStyle = (0, import_react.useMemo)(() => ({
    ...style,
    ...height && {
      height: typeof height === "number" ? `${height}px` : height,
      overflowY: "auto"
    },
    ...inverse && {
      display: "flex",
      flexDirection: "column-reverse"
    }
  }), [style, height, inverse]);
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      ref: !scrollableTarget ? containerRef : void 0,
      className,
      style: containerStyle
    },
    inverse ? /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, isLoading && hasMore && loader, !hasMore && endMessage, children) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, children, isLoading && hasMore && loader, !hasMore && endMessage)
  );
};
var InfiniteScroll_default = InfiniteScroll;
