"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    useChatScroll: ()=>useChatScroll,
    AutopilotChatScrollProvider: ()=>AutopilotChatScrollProvider
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const index_cjs_namespaceObject = require("../service/index.cjs");
const external_chat_service_provider_cjs_namespaceObject = require("./chat-service.provider.cjs");
const external_streaming_provider_cjs_namespaceObject = require("./streaming-provider.cjs");
const AutopilotChatScrollContext = /*#__PURE__*/ external_react_default().createContext(null);
const AutopilotChatScrollProvider = ({ children })=>{
    const chatService = (0, external_chat_service_provider_cjs_namespaceObject.useChatService)();
    const { streaming } = (0, external_streaming_provider_cjs_namespaceObject.useStreaming)();
    const contentRef = external_react_default().useRef(null);
    const previousHeightRef = external_react_default().useRef(0);
    const isDraggingScrollBarRef = external_react_default().useRef(false);
    const useInstantScrollRef = external_react_default().useRef(true);
    const isLoadingMoreMessagesRef = external_react_default().useRef(false);
    const shouldShowLoadingMoreMessagesRef = external_react_default().useRef(true);
    const prependingRef = external_react_default().useRef(false);
    const scrollTopBeforePrependRef = external_react_default().useRef(0);
    const scrollHeightBeforePrependRef = external_react_default().useRef(0);
    const [overflowContainer, setOverflowContainer] = external_react_default().useState(null);
    const [autoScroll, setAutoScroll] = external_react_default().useState(true);
    const [isOverflow, setIsOverflow] = external_react_default().useState(false);
    const [isContainerWide, setIsContainerWide] = external_react_default().useState(false);
    const checkOverflow = external_react_default().useCallback(()=>{
        if (overflowContainer) {
            const hasOverflow = overflowContainer.scrollHeight > overflowContainer.clientHeight;
            setIsOverflow(hasOverflow);
        }
    }, [
        overflowContainer
    ]);
    const checkContainerWidth = external_react_default().useCallback(()=>{
        if (overflowContainer) {
            const containerWidth = overflowContainer.clientWidth;
            const isWide = containerWidth > parseInt(index_cjs_namespaceObject.CHAT_WIDTH_FULL_SCREEN_MAX_WIDTH, 10);
            setIsContainerWide(isWide);
        }
    }, [
        overflowContainer
    ]);
    const scrollToBottom = external_react_default().useCallback(({ force = false, behavior = 'smooth' } = {})=>{
        if (!force && !autoScroll) return;
        if (!autoScroll && force) setAutoScroll(true);
        if (overflowContainer) overflowContainer.scrollTo({
            top: overflowContainer.scrollHeight,
            behavior: streaming ? 'instant' : behavior
        });
    }, [
        autoScroll,
        overflowContainer,
        streaming
    ]);
    const handleResize = external_react_default().useCallback(()=>{
        if (!contentRef.current || !overflowContainer) return;
        const newHeight = contentRef.current.scrollHeight;
        checkOverflow();
        if (prependingRef.current) {
            const heightDifference = newHeight - scrollHeightBeforePrependRef.current;
            const newScrollTop = scrollTopBeforePrependRef.current + heightDifference;
            overflowContainer.scrollTo({
                top: newScrollTop,
                behavior: 'instant'
            });
            prependingRef.current = false;
            previousHeightRef.current = newHeight;
            return;
        }
        if (!autoScroll) {
            previousHeightRef.current = newHeight;
            return;
        }
        if (newHeight > previousHeightRef.current) {
            const distance = overflowContainer.scrollHeight - overflowContainer.scrollTop - overflowContainer.clientHeight;
            const isNearBottom = distance < index_cjs_namespaceObject.CHAT_SCROLL_BOTTOM_BUFFER;
            scrollToBottom({
                force: true,
                behavior: isNearBottom || streaming || useInstantScrollRef.current ? 'instant' : 'smooth'
            });
        }
        previousHeightRef.current = newHeight;
    }, [
        contentRef,
        autoScroll,
        scrollToBottom,
        streaming,
        overflowContainer,
        checkOverflow
    ]);
    const handleWheel = external_react_default().useCallback((event)=>{
        if (!overflowContainer) return;
        if (event.deltaY < 0 && overflowContainer.scrollHeight > overflowContainer.clientHeight) setAutoScroll(false);
        else if (event.deltaY > 0 && overflowContainer.scrollHeight - overflowContainer.scrollTop - overflowContainer.clientHeight < index_cjs_namespaceObject.CHAT_SCROLL_BOTTOM_BUFFER) setAutoScroll(true);
    }, [
        setAutoScroll,
        overflowContainer
    ]);
    const handleScroll = external_react_default().useCallback(()=>{
        if (!overflowContainer) return;
        if (0 === overflowContainer.scrollTop && !isLoadingMoreMessagesRef.current && shouldShowLoadingMoreMessagesRef.current && chatService?.getConfig()?.paginatedMessages) {
            chatService._eventBus.publish(index_cjs_namespaceObject.AutopilotChatEvent.ConversationLoadMore);
            chatService.__internalService__.publish(index_cjs_namespaceObject.AutopilotChatInternalEvent.SetIsLoadingMoreMessages, true);
        }
    }, [
        overflowContainer,
        chatService,
        isLoadingMoreMessagesRef
    ]);
    const handleKeyDown = external_react_default().useCallback((event)=>{
        if (!overflowContainer) return;
        if ('ArrowUp' === event.key) setAutoScroll(false);
        if ('ArrowDown' === event.key) {
            const distance = overflowContainer.scrollHeight - overflowContainer.scrollTop - overflowContainer.clientHeight;
            if (distance < index_cjs_namespaceObject.CHAT_SCROLL_BOTTOM_BUFFER) setAutoScroll(true);
        }
    }, [
        overflowContainer
    ]);
    const handleMouseDown = external_react_default().useCallback((event)=>{
        if (!overflowContainer) return;
        overflowContainer.focus();
        const scrollbarWidth = overflowContainer.offsetWidth - overflowContainer.clientWidth;
        const scrollbarXStart = overflowContainer.getBoundingClientRect().right - scrollbarWidth;
        if (event.clientX >= scrollbarXStart) {
            isDraggingScrollBarRef.current = true;
            setAutoScroll(false);
        }
    }, [
        overflowContainer
    ]);
    const handleMouseUp = external_react_default().useCallback(()=>{
        if (isDraggingScrollBarRef.current) {
            isDraggingScrollBarRef.current = false;
            if (overflowContainer) {
                const distance = overflowContainer.scrollHeight - overflowContainer.scrollTop - overflowContainer.clientHeight;
                if (distance < index_cjs_namespaceObject.CHAT_SCROLL_BOTTOM_BUFFER) setAutoScroll(true);
            }
        }
    }, [
        overflowContainer
    ]);
    external_react_default().useEffect(()=>{
        const content = contentRef.current;
        if (!content || !overflowContainer || !chatService) return;
        checkOverflow();
        checkContainerWidth();
        const resizeObserver = new ResizeObserver(handleResize);
        resizeObserver.observe(content);
        const containerResizeObserver = new ResizeObserver(()=>{
            checkOverflow();
            checkContainerWidth();
        });
        containerResizeObserver.observe(overflowContainer);
        overflowContainer.addEventListener('mousedown', handleMouseDown);
        overflowContainer.addEventListener('mouseup', handleMouseUp);
        overflowContainer.addEventListener('keydown', handleKeyDown);
        overflowContainer.addEventListener('wheel', handleWheel, {
            passive: true
        });
        overflowContainer.addEventListener('scroll', handleScroll, {
            passive: true
        });
        const unsubscribeRequestIntercept = chatService.intercept(index_cjs_namespaceObject.AutopilotChatInterceptableEvent.Request, ()=>{
            setAutoScroll(true);
            useInstantScrollRef.current = false;
        });
        const unsubscribeNewChat = chatService.on(index_cjs_namespaceObject.AutopilotChatEvent.NewChat, ()=>{
            setAutoScroll(true);
            useInstantScrollRef.current = false;
        });
        const unsubscribeOpenConversation = chatService.on(index_cjs_namespaceObject.AutopilotChatEvent.OpenConversation, ()=>{
            setAutoScroll(true);
        });
        const unsubscribeSetConversation = chatService.on(index_cjs_namespaceObject.AutopilotChatEvent.SetConversation, ()=>{
            useInstantScrollRef.current = true;
        });
        const unsubscribeModeChange = chatService.on(index_cjs_namespaceObject.AutopilotChatEvent.ModeChange, ()=>{
            useInstantScrollRef.current = true;
        });
        const unsubscribeToggleAutoScroll = chatService.__internalService__.on(index_cjs_namespaceObject.AutopilotChatInternalEvent.ToggleAutoScroll, (autoScrollValue)=>{
            setAutoScroll(autoScrollValue);
        });
        const unsubscribeSetIsLoadingMoreMessages = chatService.__internalService__.on(index_cjs_namespaceObject.AutopilotChatInternalEvent.SetIsLoadingMoreMessages, (value)=>{
            isLoadingMoreMessagesRef.current = value;
        });
        const unsubscribeShouldShowLoadingMoreMessages = chatService.__internalService__.on(index_cjs_namespaceObject.AutopilotChatInternalEvent.ShouldShowLoadingMoreMessages, (value)=>{
            shouldShowLoadingMoreMessagesRef.current = value;
        });
        const unsubscribePrependOlderMessages = chatService.__internalService__.on(index_cjs_namespaceObject.AutopilotChatInternalEvent.PrependOlderMessages, ()=>{
            if (overflowContainer && contentRef.current) {
                prependingRef.current = true;
                scrollTopBeforePrependRef.current = overflowContainer.scrollTop;
                scrollHeightBeforePrependRef.current = contentRef.current.scrollHeight;
            }
        });
        return ()=>{
            resizeObserver.disconnect();
            containerResizeObserver.disconnect();
            overflowContainer.removeEventListener('wheel', handleWheel);
            overflowContainer.removeEventListener('mousedown', handleMouseDown);
            overflowContainer.removeEventListener('mouseup', handleMouseUp);
            overflowContainer.removeEventListener('keydown', handleKeyDown);
            overflowContainer.removeEventListener('scroll', handleScroll);
            unsubscribeRequestIntercept();
            unsubscribeNewChat();
            unsubscribeOpenConversation();
            unsubscribeSetConversation();
            unsubscribeModeChange();
            unsubscribeToggleAutoScroll();
            unsubscribeSetIsLoadingMoreMessages();
            unsubscribeShouldShowLoadingMoreMessages();
            unsubscribePrependOlderMessages();
        };
    }, [
        handleResize,
        handleWheel,
        handleKeyDown,
        handleMouseUp,
        handleMouseDown,
        handleScroll,
        chatService,
        overflowContainer,
        checkOverflow,
        checkContainerWidth
    ]);
    const value = external_react_default().useMemo(()=>({
            autoScroll,
            scrollToBottom,
            overflowContainer,
            setOverflowContainer,
            contentRef,
            isOverflow,
            isContainerWide
        }), [
        autoScroll,
        scrollToBottom,
        overflowContainer,
        setOverflowContainer,
        contentRef,
        isOverflow,
        isContainerWide
    ]);
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(AutopilotChatScrollContext.Provider, {
        value: value,
        children: children
    });
};
const useChatScroll = ()=>{
    const context = external_react_default().useContext(AutopilotChatScrollContext);
    if (!context) throw new Error('useChatScroll must be used within a AutopilotChatScrollProvider');
    return context;
};
exports.AutopilotChatScrollProvider = __webpack_exports__.AutopilotChatScrollProvider;
exports.useChatScroll = __webpack_exports__.useChatScroll;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AutopilotChatScrollProvider",
    "useChatScroll"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
