"use strict";
var __webpack_require__ = {};
(()=>{
    __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__, {
    useAutopilotChatResourcePicker: ()=>useAutopilotChatResourcePicker,
    isResourceSelector: ()=>isResourceSelector,
    AutopilotChatResourcePickerProvider: ()=>AutopilotChatResourcePickerProvider
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const react_namespaceObject = require("@lingui/react");
const external_react_namespaceObject = require("react");
const use_resource_picker_state_cjs_namespaceObject = require("../hooks/use-resource-picker-state.cjs");
const index_cjs_namespaceObject = require("../service/index.cjs");
const external_resource_data_provider_cjs_namespaceObject = require("./resource-data-provider.cjs");
function isResourceSelector(item) {
    return 'hasNestedResources' in item && true === item.hasNestedResources;
}
const PICKER_VERTICAL_OFFSET = 8;
const AutopilotChatResourcePickerContext = /*#__PURE__*/ (0, external_react_namespaceObject.createContext)(null);
function AutopilotChatResourcePickerProvider({ children, onResourceSelect, onDrillDown, onClose }) {
    const { hasResources, topLevelResources, paginatedResources, getNestedResources, globalSearch, onResourceSelected } = (0, external_resource_data_provider_cjs_namespaceObject.useResourceData)();
    const { _ } = (0, react_namespaceObject.useLingui)();
    const [state, dispatch] = (0, use_resource_picker_state_cjs_namespaceObject.useResourcePickerState)();
    const { anchorPosition, query, drillDown, loading, loadingMore, searchInProgress, error, searchResults, searchDone, previousDisplayCount } = state;
    const mentionRangeRef = (0, external_react_namespaceObject.useRef)(null);
    const drillDownActiveRef = (0, external_react_namespaceObject.useRef)(false);
    const isOpen = null !== anchorPosition;
    const isOpenRef = (0, external_react_namespaceObject.useRef)(isOpen);
    (0, external_react_namespaceObject.useLayoutEffect)(()=>{
        isOpenRef.current = isOpen;
    }, [
        isOpen
    ]);
    const searchQuery = (0, external_react_namespaceObject.useMemo)(()=>query.trim().toLowerCase(), [
        query
    ]);
    const errorMessages = (0, external_react_namespaceObject.useMemo)(()=>({
            load: _({
                id: 'autopilot-chat.resource-picker.error'
            }),
            loadMore: _({
                id: 'autopilot-chat.resource-picker.load-more-error'
            }),
            search: _({
                id: 'autopilot-chat.resource-picker.search-error'
            })
        }), [
        _
    ]);
    const open = (0, external_react_namespaceObject.useCallback)((range, coords)=>{
        if (!hasResources) return;
        mentionRangeRef.current = range;
        dispatch({
            type: 'OPEN',
            coords: {
                top: coords.top - PICKER_VERTICAL_OFFSET,
                left: coords.left
            }
        });
    }, [
        hasResources,
        dispatch
    ]);
    const close = (0, external_react_namespaceObject.useCallback)(()=>{
        if (!isOpenRef.current) return;
        isOpenRef.current = false;
        onClose?.();
        drillDownActiveRef.current = false;
        mentionRangeRef.current = null;
        dispatch({
            type: 'CLOSE'
        });
    }, [
        dispatch,
        onClose
    ]);
    const handleMentionEnd = (0, external_react_namespaceObject.useCallback)(()=>{
        if (drillDownActiveRef.current) {
            drillDownActiveRef.current = false;
            return;
        }
        close();
    }, [
        close
    ]);
    const setQuery = (0, external_react_namespaceObject.useCallback)((newQuery, range)=>{
        if (!hasResources) return;
        mentionRangeRef.current = range;
        dispatch({
            type: 'SET_QUERY',
            query: newQuery
        });
    }, [
        hasResources,
        dispatch
    ]);
    const loadNestedResources = (0, external_react_namespaceObject.useCallback)(async (category)=>{
        dispatch({
            type: 'LOAD_START'
        });
        try {
            const result = await getNestedResources(category.id);
            dispatch({
                type: 'DRILL_DOWN_SUCCESS',
                category,
                resources: result.items,
                done: result.done ?? true
            });
        } catch  {
            dispatch({
                type: 'LOAD_ERROR',
                error: errorMessages.load
            });
        }
    }, [
        getNestedResources,
        errorMessages.load,
        dispatch
    ]);
    const handleItemClick = (0, external_react_namespaceObject.useCallback)((item)=>{
        if (isResourceSelector(item)) {
            drillDownActiveRef.current = true;
            onDrillDown?.();
            dispatch({
                type: 'SET_QUERY',
                query: ''
            });
            loadNestedResources(item);
            return;
        }
        onResourceSelected(item);
        onResourceSelect(item, mentionRangeRef.current ?? void 0);
        close();
    }, [
        loadNestedResources,
        onResourceSelect,
        onResourceSelected,
        onDrillDown,
        close,
        dispatch
    ]);
    const goBackOrClose = (0, external_react_namespaceObject.useCallback)(()=>{
        if (drillDown) {
            drillDownActiveRef.current = false;
            dispatch({
                type: 'GO_BACK'
            });
            return;
        }
        close();
    }, [
        drillDown,
        close,
        dispatch
    ]);
    const loadMore = (0, external_react_namespaceObject.useCallback)(async ()=>{
        if (!paginatedResources || loadingMore) return;
        const isSearch = !!searchQuery;
        if (isSearch && searchDone) return;
        if (!isSearch && (!drillDown || drillDown.done)) return;
        dispatch({
            type: 'LOAD_MORE_START'
        });
        try {
            const result = isSearch ? drillDown ? await getNestedResources(drillDown.category.id, {
                searchText: searchQuery,
                skip: searchResults.length
            }) : await globalSearch({
                searchText: searchQuery,
                skip: searchResults.length
            }) : await getNestedResources(drillDown.category.id, {
                skip: drillDown.resources.length
            });
            dispatch({
                type: 'LOAD_MORE_SUCCESS',
                target: isSearch ? 'search' : 'drillDown',
                items: result.items,
                done: result.done ?? true
            });
        } catch  {
            dispatch({
                type: 'LOAD_ERROR',
                error: errorMessages.loadMore
            });
        }
    }, [
        paginatedResources,
        loadingMore,
        searchQuery,
        searchDone,
        drillDown,
        searchResults.length,
        getNestedResources,
        globalSearch,
        errorMessages.loadMore,
        dispatch
    ]);
    const performPaginatedSearch = (0, external_react_namespaceObject.useCallback)(async ()=>{
        try {
            const result = drillDown ? await getNestedResources(drillDown.category.id, {
                searchText: searchQuery
            }) : await globalSearch({
                searchText: searchQuery
            });
            dispatch({
                type: 'SEARCH_SUCCESS',
                results: result.items,
                done: result.done ?? true
            });
        } catch  {
            dispatch({
                type: 'LOAD_ERROR',
                error: errorMessages.search
            });
        }
    }, [
        drillDown,
        searchQuery,
        getNestedResources,
        globalSearch,
        errorMessages.search,
        dispatch
    ]);
    const performLocalSearch = (0, external_react_namespaceObject.useCallback)(async ()=>{
        if (drillDown) {
            const filtered = drillDown.resources.filter((item)=>item.displayName.toLowerCase().includes(searchQuery));
            dispatch({
                type: 'SEARCH_SUCCESS',
                results: filtered,
                done: true
            });
            return;
        }
        const results = [];
        for (const topLevel of topLevelResources){
            if (topLevel.displayName.toLowerCase().includes(searchQuery)) results.push(topLevel);
            if (topLevel.hasNestedResources) try {
                const result = await getNestedResources(topLevel.id);
                for (const item of result.items)if (item.displayName.toLowerCase().includes(searchQuery)) results.push(item);
            } catch  {}
        }
        dispatch({
            type: 'SEARCH_SUCCESS',
            results,
            done: true
        });
    }, [
        drillDown,
        searchQuery,
        topLevelResources,
        getNestedResources,
        dispatch
    ]);
    const retryLoad = (0, external_react_namespaceObject.useCallback)(()=>{
        if (searchQuery) {
            dispatch({
                type: 'SEARCH_START'
            });
            paginatedResources ? performPaginatedSearch() : performLocalSearch();
        } else if (drillDown) loadNestedResources(drillDown.category);
    }, [
        searchQuery,
        drillDown,
        paginatedResources,
        dispatch,
        loadNestedResources,
        performPaginatedSearch,
        performLocalSearch
    ]);
    const displayedItems = (0, external_react_namespaceObject.useMemo)(()=>{
        if (searchQuery) return searchResults;
        if (drillDown) return drillDown.resources;
        return topLevelResources;
    }, [
        searchQuery,
        searchResults,
        drillDown,
        topLevelResources
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (!isOpen) return;
        if (!searchQuery) return void dispatch({
            type: 'CLEAR_SEARCH'
        });
        dispatch({
            type: 'SEARCH_START'
        });
        const debounceTimer = setTimeout(paginatedResources ? performPaginatedSearch : performLocalSearch, index_cjs_namespaceObject.CHAT_RESOURCE_PICKER_SEARCH_DEBOUNCE_MS);
        return ()=>clearTimeout(debounceTimer);
    }, [
        isOpen,
        searchQuery,
        paginatedResources,
        performPaginatedSearch,
        performLocalSearch,
        dispatch
    ]);
    const hasMore = (0, external_react_namespaceObject.useMemo)(()=>{
        if (!paginatedResources) return false;
        if (searchQuery) return !searchDone;
        if (drillDown) return !drillDown.done;
        return false;
    }, [
        paginatedResources,
        searchQuery,
        searchDone,
        drillDown
    ]);
    const contextValue = (0, external_react_namespaceObject.useMemo)(()=>({
            isOpen,
            isOpenRef,
            anchorPosition,
            query,
            displayedItems,
            drillDown,
            loading,
            loadingMore,
            searchInProgress,
            hasMore,
            error,
            previousDisplayCount,
            open,
            close,
            handleMentionEnd,
            setQuery,
            handleItemClick,
            goBackOrClose,
            retryLoad,
            loadMore
        }), [
        isOpen,
        anchorPosition,
        query,
        displayedItems,
        drillDown,
        loading,
        loadingMore,
        searchInProgress,
        hasMore,
        error,
        previousDisplayCount,
        open,
        close,
        handleMentionEnd,
        setQuery,
        handleItemClick,
        goBackOrClose,
        retryLoad,
        loadMore
    ]);
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(AutopilotChatResourcePickerContext.Provider, {
        value: contextValue,
        children: children
    });
}
function useAutopilotChatResourcePicker() {
    const context = (0, external_react_namespaceObject.useContext)(AutopilotChatResourcePickerContext);
    if (!context) throw new Error('useAutopilotChatResourcePicker must be used within an AutopilotChatResourcePickerProvider');
    return context;
}
exports.AutopilotChatResourcePickerProvider = __webpack_exports__.AutopilotChatResourcePickerProvider;
exports.isResourceSelector = __webpack_exports__.isResourceSelector;
exports.useAutopilotChatResourcePicker = __webpack_exports__.useAutopilotChatResourcePicker;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AutopilotChatResourcePickerProvider",
    "isResourceSelector",
    "useAutopilotChatResourcePicker"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
