import { useCallback, useEffect, useLayoutEffect, useRef, useState, } from "react";
export function useAgentTerminalScroll(input) {
    const { messages, textareaRef, activePlaceholderInput, effectiveIsFocused } = input;
    const messagesContainerRef = useRef(null);
    const shouldMaintainFocusRef = useRef(false);
    const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
    const scrollToBottom = useCallback(() => {
        const container = messagesContainerRef.current;
        if (!container)
            return;
        container.scrollTop = container.scrollHeight;
    }, []);
    const isAtBottom = useCallback(() => {
        const container = messagesContainerRef.current;
        if (!container)
            return true;
        const threshold = 100;
        return (container.scrollHeight - container.scrollTop - container.clientHeight <
            threshold);
    }, []);
    const handleScroll = useCallback(() => {
        const atBottom = isAtBottom();
        if (atBottom !== shouldAutoScroll) {
            setShouldAutoScroll(atBottom);
        }
    }, [isAtBottom, shouldAutoScroll]);
    useEffect(() => {
        const textarea = textareaRef.current;
        if (!textarea)
            return;
        try {
            textarea.focus({ preventScroll: true });
        }
        catch {
            textarea.focus();
        }
        const end = textarea.value.length;
        textarea.selectionStart = end;
        textarea.selectionEnd = end;
    }, [textareaRef]);
    useLayoutEffect(() => {
        if (shouldAutoScroll) {
            scrollToBottom();
        }
    }, [messages, scrollToBottom, shouldAutoScroll]);
    useEffect(() => {
        if (shouldMaintainFocusRef.current &&
            textareaRef.current &&
            !activePlaceholderInput &&
            effectiveIsFocused) {
            textareaRef.current.focus();
        }
    }, [messages, activePlaceholderInput, effectiveIsFocused, textareaRef]);
    return {
        messagesContainerRef,
        shouldAutoScroll,
        setShouldAutoScroll,
        shouldMaintainFocusRef,
        scrollToBottom,
        handleScroll,
    };
}
//# sourceMappingURL=useAgentTerminalScroll.js.map