import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import Close from "@mui/icons-material/Close";
import { Box, IconButton, Modal, styled } from "@mui/material";
import apollo_core from "@uipath/apollo-core";
import katex from "katex";
import react from "react";
import { Prism } from "react-syntax-highlighter";
import { oneDark, oneLight } from "react-syntax-highlighter/dist/esm/styles/prism";
import { ApChip } from "../../../../ap-chip/index.js";
import { useChatState } from "../../../providers/chat-state-provider.js";
import { useTheme } from "../../../providers/theme-provider.js";
import { AutopilotChatActionButton } from "../../common/action-button.js";
var code_LANGUAGES = /*#__PURE__*/ function(LANGUAGES) {
    LANGUAGES["HTML"] = "html";
    return LANGUAGES;
}(code_LANGUAGES || {});
const extractTextFromChildren = (children)=>{
    if ('string' == typeof children) return children;
    if ('number' == typeof children) return String(children);
    if (/*#__PURE__*/ react.isValidElement(children)) {
        const element = children;
        return extractTextFromChildren(element.props.children);
    }
    if (Array.isArray(children)) return children.map((child)=>extractTextFromChildren(child)).join('');
    return '';
};
const CodeBlockHeader = styled('div')(()=>({
        display: 'flex',
        width: '100%',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: `${apollo_core.Spacing.SpacingXs} ${apollo_core.Spacing.SpacingBase}`,
        color: 'var(--color-foreground)',
        fontFamily: apollo_core.FontFamily.FontNormal,
        boxSizing: 'border-box'
    }));
const CodeBlockContainer = styled('div')(()=>({
        position: 'relative',
        width: '100%',
        fontFamily: apollo_core.FontFamily.FontNormal,
        background: 'var(--color-background)',
        borderRadius: apollo_core.Border.BorderRadiusL,
        border: "1px solid var(--color-background-gray)",
        paddingBottom: apollo_core.Spacing.SpacingMicro,
        '&:not(pre &)': {
            display: 'inline-block',
            width: 'unset',
            position: 'relative',
            top: '6px',
            borderRadius: 0,
            border: 'none',
            background: 'var(--color-background-disabled)',
            padding: `0 ${apollo_core.Spacing.SpacingMicro}`,
            '& *': {
                padding: '0 !important'
            },
            [`& ${CodeBlockHeader}`]: {
                display: 'none !important'
            }
        }
    }));
const NonCodeContentContainer = styled('div')(()=>({
        color: 'var(--color-foreground)',
        padding: apollo_core.Spacing.SpacingM,
        maxWidth: '100%',
        overflow: 'auto',
        fontFamily: apollo_core.FontFamily.FontNormal
    }));
const SyntaxHighlighterContainer = styled('div')(()=>({
        margin: 0,
        width: '100%',
        borderRadius: apollo_core.Border.BorderRadiusL,
        maxWidth: '100%',
        '& pre': {
            margin: '0 !important',
            borderRadius: `${apollo_core.Border.BorderRadiusL} !important`
        }
    }));
const ContentContainer = styled('div')(()=>({
        display: 'flex',
        flexDirection: 'column',
        width: '100%',
        height: '400px',
        borderRadius: apollo_core.Border.BorderRadiusL,
        overflow: 'auto',
        backgroundColor: 'var(--color-background)',
        boxSizing: 'border-box',
        resize: 'vertical'
    }));
const PreviewIframe = styled('iframe')(()=>({
        width: '100%',
        height: '100%',
        border: 'none',
        backgroundColor: 'var(--color-background)',
        flex: 1
    }));
const CustomModal = styled(Modal)(()=>({
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        '& .MuiBackdrop-root': {
            backgroundColor: 'rgba(0, 0, 0, 0.5)'
        }
    }));
const ModalContainer = styled(Box)(()=>({
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        width: '95vw',
        height: '90vh',
        maxWidth: '1400px',
        maxHeight: '900px',
        backgroundColor: 'var(--color-background-raised)',
        borderRadius: apollo_core.Border.BorderRadiusS,
        padding: apollo_core.Spacing.SpacingL,
        boxShadow: '0px 5px 5px -3px rgba(0, 0, 0, 0.20), 0px 8px 10px 1px rgba(0, 0, 0, 0.14), 0px 3px 14px 2px rgba(0, 0, 0, 0.12)',
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
        outline: 'none',
        '&:focus-visible, &:focus': {
            outline: 'none'
        }
    }));
const ModalContent = styled(Box)(()=>({
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden'
    }));
const CloseButton = styled(IconButton)(()=>({
        position: 'absolute',
        top: apollo_core.Spacing.SpacingXs,
        right: apollo_core.Spacing.SpacingS,
        zIndex: 1,
        backgroundColor: 'var(--color-background-raised)',
        '&:hover': {
            backgroundColor: 'var(--color-background-hover)'
        }
    }));
const Code = /*#__PURE__*/ react.memo(({ inline, className, children, isStreaming, ...props })=>{
    const { _ } = useLingui();
    const { disabledFeatures, spacing, portalContainer } = useChatState();
    const { isDark } = useTheme();
    const match = /language-(\w+)/.exec(className || '');
    const codeContent = extractTextFromChildren(children).replace(/\n$/, '');
    const language = match?.[1] || '';
    const isPreviewable = language === code_LANGUAGES.HTML && !disabledFeatures.htmlPreview;
    const [showPreview, setShowPreview] = react.useState(isPreviewable && !isStreaming);
    const [isModalOpen, setIsModalOpen] = react.useState(false);
    const codeFontStyles = {
        fontSize: spacing.compactMode ? apollo_core.FontFamily.FontMonoSSize : apollo_core.FontFamily.FontMonoMSize,
        fontFamily: spacing.compactMode ? apollo_core.FontFamily.FontMonoSFamily : apollo_core.FontFamily.FontMonoMFamily,
        lineHeight: spacing.compactMode ? apollo_core.FontFamily.FontMonoSLineHeight : apollo_core.FontFamily.FontMonoMLineHeight,
        height: spacing.compactMode ? apollo_core.FontFamily.FontMonoSLineHeight : apollo_core.FontFamily.FontMonoMLineHeight,
        fontWeight: spacing.compactMode ? apollo_core.FontFamily.FontMonoSWeight : apollo_core.FontFamily.FontMonoMWeight
    };
    const isInline = inline || !className && 'string' == typeof children && !children.includes('\n');
    if (isInline) return /*#__PURE__*/ jsx("code", {
        style: {
            color: 'var(--color-foreground)',
            padding: `0 ${apollo_core.Padding.PadS}`,
            background: 'var(--color-background-disabled)',
            borderRadius: apollo_core.Border.BorderRadiusM,
            display: 'inline-block',
            width: 'fit-content',
            ...codeFontStyles
        },
        ...props,
        children: children
    });
    if (match?.[1] === 'math') try {
        const html = katex.renderToString(String(children).replace(/\n$/, ''), {
            output: 'mathml',
            trust: false,
            strict: true,
            throwOnError: false
        });
        return /*#__PURE__*/ jsx("div", {
            dangerouslySetInnerHTML: {
                __html: html
            }
        });
    } catch (e) {
        return /*#__PURE__*/ jsx("pre", {
            style: {
                color: 'var(--color-foreground)'
            },
            children: String(children)
        });
    }
    const previewContent = /*#__PURE__*/ jsx(PreviewIframe, {
        sandbox: "allow-scripts",
        srcDoc: codeContent,
        title: "HTML Preview"
    });
    const markdownContent = language ? /*#__PURE__*/ jsx(SyntaxHighlighterContainer, {
        children: /*#__PURE__*/ jsx(Prism, {
            language: language,
            style: isDark ? oneDark : oneLight,
            customStyle: {
                margin: 0,
                fontSize: spacing.compactMode ? apollo_core.FontFamily.FontMonoSSize : apollo_core.FontFamily.FontMonoMSize,
                fontFamily: spacing.compactMode ? apollo_core.FontFamily.FontMonoSFamily : apollo_core.FontFamily.FontMonoMFamily,
                padding: apollo_core.Spacing.SpacingBase,
                whiteSpace: 'pre-wrap',
                wordWrap: 'break-word',
                overflowWrap: 'break-word'
            },
            wrapLongLines: true,
            lineProps: {
                style: {
                    wordWrap: 'break-word',
                    whiteSpace: 'pre-wrap'
                }
            },
            children: codeContent
        })
    }) : /*#__PURE__*/ jsx(NonCodeContentContainer, {
        children: children
    });
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            /*#__PURE__*/ jsxs(CodeBlockContainer, {
                children: [
                    /*#__PURE__*/ jsxs(CodeBlockHeader, {
                        children: [
                            /*#__PURE__*/ jsx(ApChip, {
                                label: language || _({
                                    id: 'autopilot-chat.message.code-block-language'
                                })
                            }),
                            /*#__PURE__*/ jsxs("div", {
                                style: {
                                    display: 'flex',
                                    gap: apollo_core.Spacing.SpacingMicro
                                },
                                children: [
                                    isPreviewable && /*#__PURE__*/ jsx(AutopilotChatActionButton, {
                                        iconName: showPreview ? 'code' : 'visibility',
                                        tooltip: showPreview ? _({
                                            id: 'autopilot-chat.message.code-block-code'
                                        }) : _({
                                            id: 'autopilot-chat.message.code-block-preview'
                                        }),
                                        onClick: ()=>{
                                            setShowPreview(!showPreview);
                                        }
                                    }),
                                    /*#__PURE__*/ jsx(AutopilotChatActionButton, {
                                        iconName: "open_in_full",
                                        tooltip: _({
                                            id: 'autopilot-chat.message.expand'
                                        }),
                                        onClick: ()=>{
                                            setIsModalOpen(true);
                                        }
                                    }),
                                    /*#__PURE__*/ jsx(AutopilotChatActionButton, {
                                        iconName: "content_copy",
                                        tooltip: _({
                                            id: 'autopilot-chat.message.code-block-copy'
                                        }),
                                        onClick: ()=>{
                                            navigator.clipboard.writeText(codeContent);
                                        },
                                        "data-testid": "autopilot-chat-code-copy"
                                    })
                                ]
                            })
                        ]
                    }),
                    isPreviewable ? /*#__PURE__*/ jsx(ContentContainer, {
                        children: showPreview ? previewContent : markdownContent
                    }) : markdownContent
                ]
            }),
            /*#__PURE__*/ jsx(CustomModal, {
                open: isModalOpen,
                onClose: ()=>setIsModalOpen(false),
                container: portalContainer,
                keepMounted: true,
                children: /*#__PURE__*/ jsxs(ModalContainer, {
                    children: [
                        /*#__PURE__*/ jsx(CloseButton, {
                            size: "small",
                            onClick: ()=>setIsModalOpen(false),
                            "aria-label": _({
                                id: 'autopilot-chat.message.close'
                            }),
                            children: /*#__PURE__*/ jsx(Close, {
                                sx: {
                                    width: apollo_core.Spacing.SpacingBase,
                                    height: apollo_core.Spacing.SpacingBase
                                }
                            })
                        }),
                        /*#__PURE__*/ jsx(ModalContent, {
                            children: /*#__PURE__*/ jsx("div", {
                                style: {
                                    flex: 1,
                                    overflow: isPreviewable && showPreview ? 'hidden' : 'auto',
                                    minHeight: 0,
                                    marginTop: apollo_core.Spacing.SpacingXs
                                },
                                children: isPreviewable && showPreview ? previewContent : markdownContent
                            })
                        })
                    ]
                })
            })
        ]
    });
});
export { Code };
