import { jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import { Box } from "@mui/material";
import apollo_core, { FontVariantToken } from "@uipath/apollo-core";
import { ApIcon } from "../../../../index.js";
import react from "react";
import { ApTypography } from "../../../../ap-typography/index.js";
import { useChatService } from "../../../providers/chat-service.provider.js";
import { useChatState } from "../../../providers/chat-state-provider.js";
import { AutopilotChatPreHookAction, CHAT_CITATION_START } from "../../../service/index.js";
import { AutopilotChatTooltip } from "../../common/tooltip.js";
const getNearestStartMarker = (id, container, endEl)=>{
    const candidates = Array.from(container.querySelectorAll(`.${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__*/ react.memo(({ id, title, url, page_number, download_url, messageId })=>{
    const { _ } = useLingui();
    const pageText = page_number ? ` (${_({
        id: 'autopilot-chat.message.page-number',
        values: {
            page_number: page_number
        }
    })})` : '';
    const chatService = useChatService();
    const { spacing } = useChatState();
    const ref = react.useRef(null);
    const [open, setOpen] = react.useState(false);
    const highlightStateRef = react.useRef(void 0);
    const finalUrl = url || `${download_url}${page_number ? `#page=${page_number}` : ''}`;
    const handleOpen = react.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 = react.useCallback(()=>{
        setOpen(false);
        clearHighlightRange(highlightStateRef.current);
        highlightStateRef.current = void 0;
    }, []);
    const handleClick = react.useCallback(()=>{
        if (!chatService) return;
        const source = url ? {
            id,
            title,
            url
        } : {
            id,
            title,
            download_url: download_url,
            page_number: page_number
        };
        chatService.getPreHook(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 = react.useCallback((event)=>{
        if ('Enter' === event.key || ' ' === event.key) {
            event.preventDefault();
            handleClick();
        }
    }, [
        handleClick
    ]);
    return /*#__PURE__*/ jsx(AutopilotChatTooltip, {
        open: open,
        placement: "bottom-end",
        onOpen: handleOpen,
        onClose: handleClose,
        title: /*#__PURE__*/ jsxs(Box, {
            sx: {
                display: 'flex',
                alignItems: 'center',
                gap: apollo_core.Spacing.SpacingS,
                cursor: finalUrl ? 'pointer' : 'default',
                padding: `${apollo_core.Spacing.SpacingXs} ${apollo_core.Spacing.SpacingS}`
            },
            onClick: handleClick,
            children: [
                /*#__PURE__*/ jsx(ApIcon, {
                    variant: url ? 'custom' : 'outlined',
                    name: url ? 'website' : 'file_open',
                    size: apollo_core.Icon.IconXs,
                    color: 'var(--color-primary)'
                }),
                /*#__PURE__*/ jsxs(ApTypography, {
                    color: "inherit",
                    style: {
                        fontWeight: 500
                    },
                    variant: FontVariantToken.fontSizeMBold,
                    children: [
                        title,
                        pageText
                    ]
                })
            ]
        }),
        slotProps: {
            popper: {
                modifiers: [
                    {
                        name: 'preventOverflow',
                        enabled: true,
                        options: {
                            boundary: 'clippingParents',
                            rootBoundary: 'viewport',
                            padding: apollo_core.Spacing.SpacingXs,
                            altAxis: true
                        }
                    },
                    {
                        name: 'flip',
                        enabled: true,
                        options: {
                            fallbackPlacements: [
                                'bottom',
                                'left',
                                'right'
                            ],
                            padding: apollo_core.Spacing.SpacingS
                        }
                    }
                ]
            },
            tooltip: {
                sx: {
                    backgroundColor: 'var(--color-background-raised)',
                    color: 'var(--color-foreground)',
                    boxShadow: apollo_core.Shadow.ShadowDp6
                }
            }
        },
        children: /*#__PURE__*/ jsx(Box, {
            component: "sup",
            ref: ref,
            sx: {
                background: 'var(--color-background-disabled)',
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                padding: `0 ${apollo_core.Spacing.SpacingMicro}`,
                marginLeft: apollo_core.Spacing.SpacingMicro,
                borderRadius: apollo_core.Border.BorderRadiusM,
                marginTop: `-${apollo_core.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__*/ jsx(ApTypography, {
                color: 'var(--color-foreground)',
                variant: spacing.markdownTokens.citation,
                children: id
            })
        })
    });
});
export { Citation };
