"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSmartScroll = useSmartScroll;
const react_1 = require("react");
const SCROLL_THRESHOLD = 10;
function useSmartScroll({ isStreaming = false, messagesCount, status, }) {
    const containerRef = (0, react_1.useRef)(null);
    const userScrolledUpRef = (0, react_1.useRef)(false);
    const scrollToBottom = (0, react_1.useCallback)((behavior = 'instant') => {
        if (!userScrolledUpRef.current) {
            const container = containerRef.current;
            if (container) {
                container.scrollTo({
                    top: container.scrollHeight,
                    behavior,
                });
            }
        }
    }, []);
    // Initial scroll to bottom
    (0, react_1.useEffect)(() => {
        scrollToBottom();
    }, []);
    // Handle user scroll events
    (0, react_1.useEffect)(() => {
        const container = containerRef.current;
        if (!container) {
            return undefined;
        }
        const handleScroll = () => {
            if (!container) {
                return;
            }
            const { scrollTop, scrollHeight, clientHeight } = container;
            const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
            const scrolledUp = distanceFromBottom > SCROLL_THRESHOLD;
            userScrolledUpRef.current = scrolledUp;
        };
        container.addEventListener('scroll', handleScroll, { passive: true });
        return () => {
            container.removeEventListener('scroll', handleScroll);
        };
    }, []);
    // Handle DOM mutations during streaming
    (0, react_1.useEffect)(() => {
        const container = containerRef.current;
        if (!container || !isStreaming) {
            return undefined;
        }
        const observer = new MutationObserver(() => {
            scrollToBottom('instant');
        });
        observer.observe(container, {
            childList: true,
            subtree: true,
            attributes: true,
            characterData: true,
        });
        return () => {
            observer.disconnect();
        };
    }, [isStreaming]);
    // Handle status changes
    (0, react_1.useEffect)(() => {
        scrollToBottom('smooth');
    }, [status]);
    (0, react_1.useEffect)(() => {
        if (messagesCount) {
            scrollToBottom('smooth');
        }
    }, [messagesCount]);
    return {
        containerRef,
        scrollToBottom,
    };
}
//# sourceMappingURL=useSmartScroll.js.map
