"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__, {
    AutopilotChatHistory: ()=>AutopilotChatHistory
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const react_namespaceObject = require("@lingui/react");
const Search_namespaceObject = require("@mui/icons-material/Search");
var Search_default = /*#__PURE__*/ __webpack_require__.n(Search_namespaceObject);
const material_namespaceObject = require("@mui/material");
const apollo_core_namespaceObject = require("@uipath/apollo-core");
var apollo_core_default = /*#__PURE__*/ __webpack_require__.n(apollo_core_namespaceObject);
const external_date_fns_namespaceObject = require("date-fns");
const external_debounce_namespaceObject = require("debounce");
var external_debounce_default = /*#__PURE__*/ __webpack_require__.n(external_debounce_namespaceObject);
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const external_react_focus_lock_namespaceObject = require("react-focus-lock");
var external_react_focus_lock_default = /*#__PURE__*/ __webpack_require__.n(external_react_focus_lock_namespaceObject);
const index_cjs_namespaceObject = require("../../../ap-skeleton/index.cjs");
const external_ap_text_field_index_cjs_namespaceObject = require("../../../ap-text-field/index.cjs");
const external_ap_typography_index_cjs_namespaceObject = require("../../../ap-typography/index.cjs");
const use_scheduled_callback_cjs_namespaceObject = require("../../hooks/use-scheduled-callback.cjs");
const chat_service_provider_cjs_namespaceObject = require("../../providers/chat-service.provider.cjs");
const chat_state_provider_cjs_namespaceObject = require("../../providers/chat-state-provider.cjs");
const chat_width_provider_cjs_namespaceObject = require("../../providers/chat-width-provider.cjs");
const external_service_index_cjs_namespaceObject = require("../../service/index.cjs");
const external_chat_history_group_cjs_namespaceObject = require("./chat-history-group.cjs");
const ChatHistoryContainer = (0, material_namespaceObject.styled)('div')(({ isFullScreen, width, fullScreenContainer })=>({
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: 'var(--color-background)',
        padding: `${apollo_core_default().Spacing.SpacingXs} 0`,
        boxSizing: 'border-box',
        height: isFullScreen ? `calc(${fullScreenContainer?.clientHeight}px - ${apollo_core_default().Spacing.SpacingBase})` : external_service_index_cjs_namespaceObject.CHAT_HISTORY_SIDE_BY_SIDE_MAX_HEIGHT,
        width: isFullScreen ? Math.min(width, external_service_index_cjs_namespaceObject.CHAT_HISTORY_FULL_SCREEN_WIDTH) : Math.min(width, external_service_index_cjs_namespaceObject.CHAT_HISTORY_SIDE_BY_SIDE_MAX_WIDTH - 2 * parseInt(apollo_core_default().Spacing.SpacingBase, 10)),
        '& .chat-history-search': {
            width: `calc(100% - 2 * ${apollo_core_default().Spacing.SpacingBase})`,
            marginLeft: apollo_core_default().Spacing.SpacingBase,
            '& .MuiInputBase-root': {
                backgroundColor: 'var(--color-background)'
            }
        },
        '& .chat-history-content': {
            outline: 'none',
            flex: 1,
            overflowY: 'auto',
            marginRight: `calc(-${apollo_core_default().Spacing.SpacingBase})`,
            paddingRight: apollo_core_default().Spacing.SpacingBase
        }
    }));
const EmptyStateContainer = (0, material_namespaceObject.styled)('div')(()=>({
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100%'
    }));
const HistorySkeletonContainer = (0, material_namespaceObject.styled)('div')(()=>({
        padding: apollo_core_default().Spacing.SpacingBase,
        '& .skeleton-item': {
            padding: apollo_core_default().Spacing.SpacingXs,
            marginBottom: apollo_core_default().Spacing.SpacingXs
        }
    }));
const HistorySkeletonLoader = ()=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(HistorySkeletonContainer, {
        children: [
            ...Array(6)
        ].map((_, index)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
                className: "skeleton-item",
                children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(index_cjs_namespaceObject.ApSkeleton, {
                    style: {
                        width: '90%',
                        height: apollo_core_default().Spacing.SpacingL
                    }
                })
            }, index))
    });
const DEBOUNCE_DELAY_IN_MS = 400;
const LOAD_MORE_THRESHOLD_IN_PX = 50;
const AutopilotChatHistoryComponent = ({ open, isFullScreen })=>{
    const { _ } = (0, react_namespaceObject.useLingui)();
    const chatService = (0, chat_service_provider_cjs_namespaceObject.useChatService)();
    const internalService = chatService?.__internalService__;
    const [history, setHistory] = (0, external_react_namespaceObject.useState)(chatService?.getHistory() ?? []);
    const [searchQuery, setSearchQuery] = (0, external_react_namespaceObject.useState)('');
    const [isLoadingMore, setIsLoadingMore] = (0, external_react_namespaceObject.useState)(false);
    const [isSearching, setIsSearching] = (0, external_react_namespaceObject.useState)(false);
    const [scrollContainer, setScrollContainer] = (0, external_react_namespaceObject.useState)(null);
    const popperContainerRef = (0, external_react_namespaceObject.useRef)(null);
    const isLoadingMoreRef = (0, external_react_namespaceObject.useRef)(false);
    const shouldShowLoadingMoreRef = (0, external_react_namespaceObject.useRef)(true);
    const appendingRef = (0, external_react_namespaceObject.useRef)(false);
    const scrollTopBeforeAppendRef = (0, external_react_namespaceObject.useRef)(0);
    const searchQueryRef = (0, external_react_namespaceObject.useRef)('');
    const { historyOpen, historyAnchorElement, fullScreenContainer, spacing, portalContainer } = (0, chat_state_provider_cjs_namespaceObject.useChatState)();
    const popoverActionRef = (0, external_react_namespaceObject.useRef)(null);
    const updatePosition = (0, external_react_namespaceObject.useCallback)(()=>{
        if (popoverActionRef.current) popoverActionRef.current.updatePosition();
    }, []);
    const schedulePositionUpdate = (0, use_scheduled_callback_cjs_namespaceObject.useScheduledCallback)(updatePosition);
    const handleTransitionEnter = (0, external_react_namespaceObject.useCallback)(()=>{
        schedulePositionUpdate();
    }, [
        schedulePositionUpdate
    ]);
    const handleTransitionEntered = (0, external_react_namespaceObject.useCallback)(()=>{
        schedulePositionUpdate();
    }, [
        schedulePositionUpdate
    ]);
    const { width } = (0, chat_width_provider_cjs_namespaceObject.useChatWidth)();
    const handleScroll = (0, external_react_namespaceObject.useCallback)(()=>{
        if (!scrollContainer || !chatService) return;
        const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
        const scrollBottom = scrollHeight - scrollTop - clientHeight;
        if (scrollBottom < LOAD_MORE_THRESHOLD_IN_PX && !isLoadingMoreRef.current && shouldShowLoadingMoreRef.current && chatService.getConfig()?.paginatedHistory) {
            chatService._eventBus.publish(external_service_index_cjs_namespaceObject.AutopilotChatEvent.HistoryLoadMore, {
                searchText: searchQueryRef.current
            });
            internalService.publish(external_service_index_cjs_namespaceObject.AutopilotChatInternalEvent.SetIsLoadingMoreHistory, true);
        }
    }, [
        scrollContainer,
        chatService,
        internalService
    ]);
    const debouncedSearch = (0, external_react_namespaceObject.useMemo)(()=>external_debounce_default()((newSearchQuery)=>{
            if (chatService?.getConfig()?.paginatedHistory) {
                chatService._eventBus.publish(external_service_index_cjs_namespaceObject.AutopilotChatEvent.HistorySearch, {
                    searchText: newSearchQuery
                });
                internalService.publish(external_service_index_cjs_namespaceObject.AutopilotChatInternalEvent.SetIsLoadingMoreHistory, false);
            }
        }, DEBOUNCE_DELAY_IN_MS), [
        chatService,
        internalService
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (!chatService || !internalService) return;
        const unsubscribeSetHistory = chatService.on(external_service_index_cjs_namespaceObject.AutopilotChatEvent.SetHistory, (newHistory)=>{
            setHistory(newHistory);
            setIsSearching(false);
        });
        const unsubscribeSetIsLoadingMore = internalService.on(external_service_index_cjs_namespaceObject.AutopilotChatInternalEvent.SetIsLoadingMoreHistory, (value)=>{
            isLoadingMoreRef.current = value;
            setIsLoadingMore(value);
        });
        const unsubscribeShouldShowLoading = internalService.on(external_service_index_cjs_namespaceObject.AutopilotChatInternalEvent.ShouldShowLoadingMoreHistory, (value)=>{
            shouldShowLoadingMoreRef.current = value;
        });
        const unsubscribeAppendOlderHistory = internalService.on(external_service_index_cjs_namespaceObject.AutopilotChatInternalEvent.AppendOlderHistory, ()=>{
            if (scrollContainer) {
                appendingRef.current = true;
                scrollTopBeforeAppendRef.current = scrollContainer.scrollTop;
            }
        });
        return ()=>{
            unsubscribeSetHistory();
            unsubscribeSetIsLoadingMore();
            unsubscribeShouldShowLoading();
            unsubscribeAppendOlderHistory();
        };
    }, [
        chatService,
        internalService,
        scrollContainer
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (!scrollContainer || !historyOpen || !chatService) return;
        scrollContainer.addEventListener('scroll', handleScroll, {
            passive: true
        });
        return ()=>{
            scrollContainer.removeEventListener('scroll', handleScroll);
        };
    }, [
        scrollContainer,
        handleScroll,
        historyOpen,
        chatService
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (appendingRef.current && scrollContainer) {
            scrollContainer.scrollTop = scrollTopBeforeAppendRef.current;
            appendingRef.current = false;
        }
    }, [
        history,
        scrollContainer
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        searchQueryRef.current = searchQuery;
    }, [
        searchQuery
    ]);
    const groupedHistory = (0, external_react_namespaceObject.useMemo)(()=>{
        const filteredHistory = chatService?.getConfig()?.paginatedHistory ? history : history.filter((item)=>item.name.toLowerCase().includes(searchQuery.toLowerCase()));
        const grouped = filteredHistory.reduce((acc, item)=>{
            const date = new Date(item.timestamp);
            const currentDate = new Date();
            const daysAgo = (0, external_date_fns_namespaceObject.differenceInDays)(currentDate, date);
            let groupTitle = '';
            if ((0, external_date_fns_namespaceObject.isToday)(date)) groupTitle = _({
                id: 'autopilot-chat.history.group.today'
            });
            else if ((0, external_date_fns_namespaceObject.isYesterday)(date)) groupTitle = _({
                id: 'autopilot-chat.history.group.yesterday'
            });
            else if (daysAgo <= 7) groupTitle = _({
                id: 'autopilot-chat.history.group.last-week'
            });
            else if (daysAgo <= 30) groupTitle = _({
                id: 'autopilot-chat.history.group.last-30-days'
            });
            else {
                const monthsAgo = (0, external_date_fns_namespaceObject.differenceInMonths)(currentDate, date);
                const count = monthsAgo;
                groupTitle = _({
                    id: 'autopilot-chat.history.group.months-ago',
                    values: {
                        count: count
                    }
                });
            }
            const existingGroup = acc.find((group)=>group.title === groupTitle);
            if (existingGroup) existingGroup.items.push(item);
            else acc.push({
                title: groupTitle,
                items: [
                    item
                ]
            });
            return acc;
        }, []);
        grouped.sort((a, b)=>{
            const getDate = (group)=>{
                if (0 === group.items.length) return new Date();
                return new Date(group.items[0].timestamp);
            };
            return getDate(b).getTime() - getDate(a).getTime();
        });
        grouped.forEach((group)=>{
            group.items.sort((a, b)=>new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
        });
        return grouped;
    }, [
        history,
        searchQuery,
        chatService,
        _
    ]);
    const handleSearchTextChange = (0, external_react_namespaceObject.useCallback)((searchText)=>{
        const newSearchText = searchText || '';
        setSearchQuery(newSearchText);
        if (chatService?.getConfig()?.paginatedHistory) {
            setIsSearching(true);
            debouncedSearch(newSearchText);
        }
    }, [
        chatService,
        debouncedSearch
    ]);
    const hasHistoryData = history.length > 0 || searchQuery || isSearching;
    const hasNoSearchResults = 0 === groupedHistory.length && searchQuery;
    const showSkeletonLoader = isSearching && chatService?.getConfig()?.paginatedHistory;
    const showLoadMoreSpinner = isLoadingMore && chatService?.getConfig()?.paginatedHistory;
    const renderEmptyState = (message)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(EmptyStateContainer, {
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_ap_typography_index_cjs_namespaceObject.ApTypography, {
                color: 'var(--color-foreground)',
                variant: spacing.primaryFontToken,
                children: message
            })
        });
    const renderHistoryGroups = ()=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(jsx_runtime_namespaceObject.Fragment, {
            children: [
                groupedHistory.map((group)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_chat_history_group_cjs_namespaceObject.AutopilotChatHistoryGroup, {
                        group: group,
                        isHistoryOpen: historyOpen
                    }, group.title)),
                showLoadMoreSpinner && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
                    style: {
                        display: 'flex',
                        justifyContent: 'center',
                        margin: spacing.compactMode ? apollo_core_default().Spacing.SpacingXs : apollo_core_default().Spacing.SpacingBase
                    },
                    children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(material_namespaceObject.CircularProgress, {
                        size: 20
                    })
                })
            ]
        });
    const renderHistoryContent = ()=>{
        if (showSkeletonLoader) return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(HistorySkeletonLoader, {});
        if (hasNoSearchResults) return renderEmptyState(_({
            id: 'autopilot-chat.history.no-results'
        }));
        return renderHistoryGroups();
    };
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(material_namespaceObject.Popover, {
        open: open && historyOpen,
        anchorEl: historyAnchorElement,
        onClose: ()=>{
            chatService?.toggleHistory();
        },
        container: portalContainer,
        anchorOrigin: {
            vertical: 'bottom',
            horizontal: 'left'
        },
        transformOrigin: {
            vertical: 'top',
            horizontal: 'left'
        },
        slotProps: {
            paper: {
                ref: popperContainerRef,
                elevation: 6,
                sx: {
                    borderRadius: apollo_core_default().Spacing.SpacingMicro,
                    margin: `0 ${apollo_core_default().Spacing.SpacingXs + apollo_core_default().Spacing.SpacingBase} 0 ${apollo_core_default().Spacing.SpacingXs}`
                }
            }
        },
        action: popoverActionRef,
        TransitionProps: {
            onEnter: handleTransitionEnter,
            onEntered: handleTransitionEntered
        },
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_react_focus_lock_default(), {
            disabled: !open || !historyOpen,
            returnFocus: false,
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ChatHistoryContainer, {
                isFullScreen: isFullScreen,
                width: Math.min(width - 2 * parseInt(apollo_core_default().Spacing.SpacingBase, 10), popperContainerRef.current?.clientWidth ?? (portalContainer ? width - 2 * parseInt(apollo_core_default().Spacing.SpacingBase, 10) : 1 / 0)),
                fullScreenContainer: fullScreenContainer,
                children: hasHistoryData ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(jsx_runtime_namespaceObject.Fragment, {
                    children: [
                        /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_ap_text_field_index_cjs_namespaceObject.ApTextField, {
                            disabled: !historyOpen,
                            className: "chat-history-search",
                            size: "small",
                            startAdornment: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(Search_default(), {}),
                            placeholder: _({
                                id: 'autopilot-chat.history.search-placeholder'
                            }),
                            value: searchQuery,
                            onChange: handleSearchTextChange
                        }),
                        /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
                            className: "chat-history-content",
                            ref: setScrollContainer,
                            children: renderHistoryContent()
                        })
                    ]
                }) : renderEmptyState(_({
                    id: 'autopilot-chat.history.empty'
                }))
            })
        })
    });
};
const AutopilotChatHistory = /*#__PURE__*/ external_react_default().memo(AutopilotChatHistoryComponent);
exports.AutopilotChatHistory = __webpack_exports__.AutopilotChatHistory;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AutopilotChatHistory"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
