function _array_like_to_array(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 _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(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(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { useEffect, useRef } from "react";
import { useThrottleFn } from "./useThrottleFn";
var SCROLL_TOLERANCE = 20;
/**
 * useAutoScroll Hook - 自动滚动 Hook
 *
 * 该 Hook 提供自动滚动功能，当容器内容增加时自动滚动到底部。
 * 支持用户滚动锁定检测、DOM 变化监听、手动滚动等功能。
 *
 * @description 自动滚动 Hook，提供智能滚动到底部功能
 * @template T - HTMLDivElement 类型
 * @param {Object} props - Hook 配置参数
 * @param {number} [props.SCROLL_TOLERANCE=20] - 滚动到底部的容差阈值
 * @param {(size: {width: number, height: number}) => void} [props.onResize] - 容器尺寸变化回调
 * @param {any[]} [props.deps] - 依赖数组，用于重新初始化 MutationObserver
 * @param {number} [props.timeout=160] - 节流时间间隔（毫秒）
 * @param {'smooth' | 'auto'} [props.scrollBehavior='smooth'] - 自动滚动行为，'smooth' 为平滑滚动，'auto' 为立即滚动（仅影响自动滚动，手动滚动默认为立即滚动）
 *
 * @example
 * ```tsx
 * // 基本用法（默认平滑滚动）
 * const { containerRef, scrollToBottom } = useAutoScroll({
 *   SCROLL_TOLERANCE: 30,
 *   onResize: () => {},
 *   timeout: 200
 * });
 *
 * // 立即滚动
 * const { containerRef, scrollToBottom } = useAutoScroll({
 *   scrollBehavior: 'auto',
 * });
 *
 * // 手动滚动默认为立即滚动，无需平滑滚动
 * scrollToBottom(); // 立即滚动
 * ```
 *
 * @returns {Object} Hook 返回值
 * @returns {React.RefObject<T>} returns.containerRef - 容器引用
 * @returns {() => void} returns.scrollToBottom - 手动滚动到底部方法（立即滚动，无动画）
 *
 * @remarks
 * - 自动检测内容变化并滚动到底部
 * - 支持用户滚动锁定检测
 * - 使用 MutationObserver 监听 DOM 变化
 * - 提供节流功能避免频繁滚动
 * - 支持手动触发滚动
 * - 智能判断是否应该自动滚动
 * - 提供容器尺寸变化回调
 */ export var useAutoScroll = function useAutoScroll() {
    var props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {
        SCROLL_TOLERANCE: SCROLL_TOLERANCE
    };
    var _ref;
    var containerRef = useRef(null);
    var lastScrollHeight = useRef(0);
    /**
   * 记录自动滚动是否处于激活状态（即用户没有主动向上滚动）。
   * 在 smooth scroll 动画过程中 scrollTop 尚未到达目标值，如果此时有新内容
   * 进来，isNearBottom 可能因 scrollTop 还在动画中途而误判为 false，导致
   * 漏掉最后一次滚动。用此标志可以安全地跨帧维持"应该跟底"的意图。
   */ var isAutoScrollEngaged = useRef(true);
    var observer = useRef(null);
    var tolerance = (_ref = props === null || props === void 0 ? void 0 : props.SCROLL_TOLERANCE) !== null && _ref !== void 0 ? _ref : SCROLL_TOLERANCE;
    // 主滚动逻辑
    var _checkScroll = function _checkScroll() {
        var force = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false, behavior = arguments.length > 1 ? arguments[1] : void 0;
        return _async_to_generator(function() {
            var _props_onResize, container, currentScrollHeight, prevScrollHeight, isNearBottom, shouldScroll, scrollBehavior;
            return _ts_generator(this, function(_state) {
                container = containerRef.current;
                if (!container) return [
                    2
                ];
                (_props_onResize = props.onResize) === null || _props_onResize === void 0 ? void 0 : _props_onResize.call(props, {
                    width: container.clientWidth,
                    height: container.clientHeight
                });
                currentScrollHeight = container.scrollHeight;
                prevScrollHeight = lastScrollHeight.current;
                // 使用当前 scrollHeight 判断是否靠近底部，避免 smooth 动画中 scrollTop
                // 尚未到达目标时的误判。
                isNearBottom = container.scrollTop + container.clientHeight >= currentScrollHeight - tolerance;
                shouldScroll = force || currentScrollHeight > prevScrollHeight && (isNearBottom || isAutoScrollEngaged.current);
                if (shouldScroll && container.scrollTo) {
                    scrollBehavior = behavior !== undefined ? behavior : props.scrollBehavior || 'smooth';
                    container.scrollTo({
                        top: currentScrollHeight,
                        behavior: scrollBehavior
                    });
                    isAutoScrollEngaged.current = true;
                } else if (!isNearBottom) {
                    // 用户已经向上滚动远离底部，关闭自动跟随
                    isAutoScrollEngaged.current = false;
                }
                lastScrollHeight.current = currentScrollHeight;
                return [
                    2
                ];
            });
        })();
    };
    var checkScroll = useThrottleFn(_checkScroll, props.timeout || 160);
    // 监听用户手动滚动，判断其是否离开了底部
    useEffect(function() {
        var container = containerRef.current;
        if (!container) return;
        var handleScroll = function handleScroll() {
            var atBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - tolerance;
            if (atBottom) {
                isAutoScrollEngaged.current = true;
            } else {
                isAutoScrollEngaged.current = false;
            }
        };
        container.addEventListener('scroll', handleScroll, {
            passive: true
        });
        return function() {
            return container.removeEventListener('scroll', handleScroll);
        };
    }, _to_consumable_array(props.deps || []));
    // DOM 变化监听（MutationObserver）
    useEffect(function() {
        var container = containerRef.current;
        if (!container) return;
        observer.current = new MutationObserver(function(mutations) {
            var shouldCheck = mutations.some(function(m) {
                var _ref, _ref1;
                var _m_addedNodes, _m_removedNodes;
                return ((_ref = (_m_addedNodes = m.addedNodes) === null || _m_addedNodes === void 0 ? void 0 : _m_addedNodes.length) !== null && _ref !== void 0 ? _ref : 0) > 0 || ((_ref1 = (_m_removedNodes = m.removedNodes) === null || _m_removedNodes === void 0 ? void 0 : _m_removedNodes.length) !== null && _ref1 !== void 0 ? _ref1 : 0) > 0 || m.type === 'characterData';
            });
            if (shouldCheck) checkScroll === null || checkScroll === void 0 ? void 0 : checkScroll();
        });
        observer.current.observe(container, {
            childList: true,
            subtree: true,
            attributes: false,
            characterData: true
        });
        return function() {
            var _observer_current;
            return (_observer_current = observer.current) === null || _observer_current === void 0 ? void 0 : _observer_current.disconnect();
        };
    }, _to_consumable_array(props.deps || []));
    // 暴露手动滚动方法（默认为立即滚动，无需平滑滚动）
    var scrollToBottom = function scrollToBottom() {
        checkScroll === null || checkScroll === void 0 ? void 0 : checkScroll(true, 'auto');
    };
    return {
        containerRef: containerRef,
        scrollToBottom: scrollToBottom
    };
};
export default useAutoScroll;
