"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__, {
    Citation: ()=>Citation
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const react_namespaceObject = require("@lingui/react");
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_index_cjs_namespaceObject = require("../../../../index.cjs");
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const index_cjs_namespaceObject = require("../../../../ap-typography/index.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 external_service_index_cjs_namespaceObject = require("../../../service/index.cjs");
const tooltip_cjs_namespaceObject = require("../../common/tooltip.cjs");
const getNearestStartMarker = (id, container, endEl)=>{
    const candidates = Array.from(container.querySelectorAll(`.${external_service_index_cjs_namespaceObject.CHAT_CITATION_START}[data-citation-ids~="${id}"]`));
    if (0 === candidates.length) return null;
    let nearest = null;
    for (const marker of candidates){
        const rel = marker.compareDocumentPosition(endEl);
        const isBefore = !!(rel & Node.DOCUMENT_POSITION_FOLLOWING) || !!(rel & Node.DOCUMENT_POSITION_CONTAINS);
        if (isBefore) nearest = marker;
    }
    return nearest;
};
const highlightRange = (startMarker, endEl, container, color)=>{
    const highlightedElements = [];
    const wrappedTextSpans = [];
    const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
    while(walker.nextNode())if (walker.currentNode === startMarker) break;
    while(walker.nextNode()){
        const node = walker.currentNode;
        if (node === endEl) break;
        if (node.nodeType === Node.ELEMENT_NODE) {
            const el = node;
            if (el === startMarker) continue;
            if (el.closest('[data-citation-sup="true"]')) continue;
            el.style.transition = 'background-color 0.2s';
            el.style.backgroundColor = color;
            highlightedElements.push(el);
        } else if (node.nodeType === Node.TEXT_NODE) {
            const text = node;
            if (text.textContent && text.textContent.trim().length > 0 && text.parentElement && !text.parentElement.closest('[data-citation-sup="true"]')) {
                const span = document.createElement('span');
                span.style.backgroundColor = color;
                text.parentElement.insertBefore(span, text);
                span.appendChild(text);
                wrappedTextSpans.push(span);
            }
        }
    }
    return {
        highlightedElements,
        wrappedTextSpans
    };
};
const clearHighlightRange = (state)=>{
    if (!state) return;
    state.highlightedElements.forEach((el)=>{
        el.style.backgroundColor = '';
        el.style.transition = '';
    });
    state.wrappedTextSpans.forEach((span)=>{
        const parent = span.parentNode;
        while(span.firstChild)parent?.insertBefore(span.firstChild, span);
        parent?.removeChild(span);
    });
};
const Citation = /*#__PURE__*/ external_react_default().memo(({ id, title, url, page_number, download_url, messageId })=>{
    const { _ } = (0, react_namespaceObject.useLingui)();
    const pageText = page_number ? ` (${_({
        id: 'autopilot-chat.message.page-number',
        values: {
            page_number: page_number
        }
    })})` : '';
    const chatService = (0, chat_service_provider_cjs_namespaceObject.useChatService)();
    const { spacing } = (0, chat_state_provider_cjs_namespaceObject.useChatState)();
    const ref = external_react_default().useRef(null);
    const [open, setOpen] = external_react_default().useState(false);
    const highlightStateRef = external_react_default().useRef(void 0);
    const finalUrl = url || `${download_url}${page_number ? `#page=${page_number}` : ''}`;
    const handleOpen = external_react_default().useCallback(()=>{
        setOpen(true);
        if (id && ref.current) {
            const container = ref.current.closest(`[id="${messageId}"]`);
            const startMarker = getNearestStartMarker(id, container, ref.current);
            if (startMarker) highlightStateRef.current = highlightRange(startMarker, ref.current, container, 'var(--color-background-highlight)');
        }
    }, [
        id,
        messageId
    ]);
    const handleClose = external_react_default().useCallback(()=>{
        setOpen(false);
        clearHighlightRange(highlightStateRef.current);
        highlightStateRef.current = void 0;
    }, []);
    const handleClick = external_react_default().useCallback(()=>{
        if (!chatService) return;
        const source = url ? {
            id,
            title,
            url
        } : {
            id,
            title,
            download_url: download_url,
            page_number: page_number
        };
        chatService.getPreHook(external_service_index_cjs_namespaceObject.AutopilotChatPreHookAction.CitationClick)({
            citation: source
        }).then((proceed)=>{
            if (!proceed || !finalUrl) return;
            window.open(finalUrl, '_blank', 'noopener,noreferrer');
        });
    }, [
        chatService,
        id,
        title,
        url,
        download_url,
        page_number,
        finalUrl
    ]);
    const handleKeyDown = external_react_default().useCallback((event)=>{
        if ('Enter' === event.key || ' ' === event.key) {
            event.preventDefault();
            handleClick();
        }
    }, [
        handleClick
    ]);
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(tooltip_cjs_namespaceObject.AutopilotChatTooltip, {
        open: open,
        placement: "bottom-end",
        onOpen: handleOpen,
        onClose: handleClose,
        title: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(material_namespaceObject.Box, {
            sx: {
                display: 'flex',
                alignItems: 'center',
                gap: apollo_core_default().Spacing.SpacingS,
                cursor: finalUrl ? 'pointer' : 'default',
                padding: `${apollo_core_default().Spacing.SpacingXs} ${apollo_core_default().Spacing.SpacingS}`
            },
            onClick: handleClick,
            children: [
                /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_index_cjs_namespaceObject.ApIcon, {
                    variant: url ? 'custom' : 'outlined',
                    name: url ? 'website' : 'file_open',
                    size: apollo_core_default().Icon.IconXs,
                    color: 'var(--color-primary)'
                }),
                /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(index_cjs_namespaceObject.ApTypography, {
                    color: "inherit",
                    style: {
                        fontWeight: 500
                    },
                    variant: apollo_core_namespaceObject.FontVariantToken.fontSizeMBold,
                    children: [
                        title,
                        pageText
                    ]
                })
            ]
        }),
        slotProps: {
            popper: {
                modifiers: [
                    {
                        name: 'preventOverflow',
                        enabled: true,
                        options: {
                            boundary: 'clippingParents',
                            rootBoundary: 'viewport',
                            padding: apollo_core_default().Spacing.SpacingXs,
                            altAxis: true
                        }
                    },
                    {
                        name: 'flip',
                        enabled: true,
                        options: {
                            fallbackPlacements: [
                                'bottom',
                                'left',
                                'right'
                            ],
                            padding: apollo_core_default().Spacing.SpacingS
                        }
                    }
                ]
            },
            tooltip: {
                sx: {
                    backgroundColor: 'var(--color-background-raised)',
                    color: 'var(--color-foreground)',
                    boxShadow: apollo_core_default().Shadow.ShadowDp6
                }
            }
        },
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(material_namespaceObject.Box, {
            component: "sup",
            ref: ref,
            sx: {
                background: 'var(--color-background-disabled)',
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                padding: `0 ${apollo_core_default().Spacing.SpacingMicro}`,
                marginLeft: apollo_core_default().Spacing.SpacingMicro,
                borderRadius: apollo_core_default().Border.BorderRadiusM,
                marginTop: `-${apollo_core_default().Spacing.SpacingMicro}`,
                outline: 'none',
                '&:focus-visible': {
                    outline: "1px solid var(--color-focus-indicator)"
                }
            },
            "data-citation-sup": "true",
            tabIndex: 0,
            role: "button",
            "aria-label": _({
                id: 'autopilot-chat.message.citation-aria-label',
                values: {
                    id: id,
                    title: title,
                    pageText: pageText
                }
            }),
            onClick: handleClick,
            onKeyDown: handleKeyDown,
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(index_cjs_namespaceObject.ApTypography, {
                color: 'var(--color-foreground)',
                variant: spacing.markdownTokens.citation,
                children: id
            })
        })
    });
});
exports.Citation = __webpack_exports__.Citation;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "Citation"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
