var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
// ============================================================================
// Chatbot Main - Message
// ============================================================================
import { forwardRef, useEffect, useState } from 'react';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Avatar, ContentVariants, Label, Timestamp, Truncate } from '@patternfly/react-core';
import MessageLoading from './MessageLoading';
import CodeBlockMessage from './CodeBlockMessage/CodeBlockMessage';
import TextMessage from './TextMessage/TextMessage';
import FileDetailsLabel from '../FileDetailsLabel/FileDetailsLabel';
import ResponseActions from '../ResponseActions/ResponseActions';
import SourcesCard from '../SourcesCard';
import ListItemMessage from './ListMessage/ListItemMessage';
import UnorderedListMessage from './ListMessage/UnorderedListMessage';
import OrderedListMessage from './ListMessage/OrderedListMessage';
import QuickStartTile from './QuickStarts/QuickStartTile';
import QuickResponse from './QuickResponse/QuickResponse';
import UserFeedback from './UserFeedback/UserFeedback';
import UserFeedbackComplete from './UserFeedback/UserFeedbackComplete';
import TableMessage from './TableMessage/TableMessage';
import TrMessage from './TableMessage/TrMessage';
import TdMessage from './TableMessage/TdMessage';
import TbodyMessage from './TableMessage/TbodyMessage';
import TheadMessage from './TableMessage/TheadMessage';
import ThMessage from './TableMessage/ThMessage';
import ImageMessage from './ImageMessage/ImageMessage';
import rehypeUnwrapImages from 'rehype-unwrap-images';
import rehypeExternalLinks from 'rehype-external-links';
import rehypeSanitize from 'rehype-sanitize';
import rehypeHighlight from 'rehype-highlight';
// see the full list of styles here: https://highlightjs.org/examples
import 'highlight.js/styles/vs2015.css';
import LinkMessage from './LinkMessage/LinkMessage';
import ErrorMessage from './ErrorMessage/ErrorMessage';
import MessageInput from './MessageInput';
import { rehypeMoveImagesOutOfParagraphs } from './Plugins/rehypeMoveImagesOutOfParagraphs';
import ToolResponse from '../ToolResponse';
import DeepThinking from '../DeepThinking';
import SuperscriptMessage from './SuperscriptMessage/SuperscriptMessage';
import ToolCall from '../ToolCall';
export const MessageBase = (_a) => {
    var { role, content, extraContent, name, avatar, timestamp, isLoading, actions, persistActionSelection, sources, botWord = 'AI', loadingWord = 'Loading message', codeBlockProps, quickResponses, quickResponseContainerProps = { numLabels: 5 }, attachments, hasRoundAvatar = true, avatarProps, quickStarts, userFeedbackForm, userFeedbackComplete, isLiveRegion = true, innerRef, tableProps, openLinkInNewTab = true, additionalRehypePlugins = [], additionalRemarkPlugins = [], linkProps, error, isEditable, editPlaceholder = 'Edit prompt message...', updateWord = 'Update', cancelWord = 'Cancel', onEditUpdate, onEditCancel, inputRef, editFormProps, isCompact, isMarkdownDisabled, reactMarkdownProps, toolResponse, deepThinking, remarkGfmProps, toolCall, hasNoImagesInUserMessages = true, isPrimary } = _a, props = __rest(_a, ["role", "content", "extraContent", "name", "avatar", "timestamp", "isLoading", "actions", "persistActionSelection", "sources", "botWord", "loadingWord", "codeBlockProps", "quickResponses", "quickResponseContainerProps", "attachments", "hasRoundAvatar", "avatarProps", "quickStarts", "userFeedbackForm", "userFeedbackComplete", "isLiveRegion", "innerRef", "tableProps", "openLinkInNewTab", "additionalRehypePlugins", "additionalRemarkPlugins", "linkProps", "error", "isEditable", "editPlaceholder", "updateWord", "cancelWord", "onEditUpdate", "onEditCancel", "inputRef", "editFormProps", "isCompact", "isMarkdownDisabled", "reactMarkdownProps", "toolResponse", "deepThinking", "remarkGfmProps", "toolCall", "hasNoImagesInUserMessages", "isPrimary"]);
    const [messageText, setMessageText] = useState(content);
    useEffect(() => {
        setMessageText(content);
    }, [content]);
    const { beforeMainContent, afterMainContent, endContent } = extraContent || {};
    let rehypePlugins = [rehypeUnwrapImages, rehypeMoveImagesOutOfParagraphs, rehypeHighlight];
    if (openLinkInNewTab) {
        rehypePlugins = rehypePlugins.concat([[rehypeExternalLinks, { target: '_blank' }, rehypeSanitize]]);
    }
    if (additionalRehypePlugins) {
        rehypePlugins.push(...additionalRehypePlugins);
    }
    let avatarClassName;
    if (avatarProps && 'className' in avatarProps) {
        const { className } = avatarProps, rest = __rest(avatarProps, ["className"]);
        avatarClassName = className;
        avatarProps = Object.assign({}, rest);
    }
    // Keep timestamps consistent between Timestamp component and aria-label
    const date = new Date();
    const dateString = timestamp !== null && timestamp !== void 0 ? timestamp : `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
    const disallowedElements = role === 'user' && hasNoImagesInUserMessages ? ['img'] : [];
    if (reactMarkdownProps && reactMarkdownProps.disallowedElements) {
        disallowedElements.push(...reactMarkdownProps.disallowedElements);
    }
    const handleMarkdown = () => {
        if (isMarkdownDisabled) {
            return (_jsx(TextMessage, Object.assign({ component: ContentVariants.p }, props, { children: messageText })));
        }
        return (_jsx(Markdown, Object.assign({ components: {
                section: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx("section", Object.assign({}, rest, { className: `pf-chatbot__message-text ${rest === null || rest === void 0 ? void 0 : rest.className}` }));
                },
                p: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TextMessage, Object.assign({ component: ContentVariants.p }, rest, { isPrimary: isPrimary }));
                },
                code: (_a) => {
                    var { children } = _a, props = __rest(_a, ["children"]);
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, codeProps = __rest(props, ["node"]);
                    return (_jsx(CodeBlockMessage, Object.assign({}, codeProps, codeBlockProps, { isPrimary: isPrimary, children: children })));
                },
                h1: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TextMessage, Object.assign({ component: ContentVariants.h1 }, rest));
                },
                h2: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TextMessage, Object.assign({ component: ContentVariants.h2 }, rest));
                },
                h3: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TextMessage, Object.assign({ component: ContentVariants.h3 }, rest));
                },
                h4: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TextMessage, Object.assign({ component: ContentVariants.h4 }, rest));
                },
                h5: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TextMessage, Object.assign({ component: ContentVariants.h5 }, rest));
                },
                h6: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TextMessage, Object.assign({ component: ContentVariants.h6 }, rest));
                },
                blockquote: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TextMessage, Object.assign({ component: ContentVariants.blockquote }, rest));
                },
                ul: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(UnorderedListMessage, Object.assign({}, rest));
                },
                ol: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(OrderedListMessage, Object.assign({}, rest));
                },
                li: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(ListItemMessage, Object.assign({}, rest));
                },
                // table requires node attribute for calculating headers for mobile breakpoint
                table: (props) => _jsx(TableMessage, Object.assign({}, props, tableProps, { isPrimary: isPrimary })),
                tbody: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TbodyMessage, Object.assign({}, rest));
                },
                thead: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TheadMessage, Object.assign({}, rest));
                },
                tr: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(TrMessage, Object.assign({}, rest));
                },
                td: (props) => {
                    // Conflicts with Td type
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node, width } = props, rest = __rest(props, ["node", "width"]);
                    return _jsx(TdMessage, Object.assign({}, rest));
                },
                th: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(ThMessage, Object.assign({}, rest));
                },
                img: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(ImageMessage, Object.assign({}, rest));
                },
                a: (props) => {
                    // node is just the details of the document structure - not needed
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return (
                    // some a types conflict with ButtonProps, but it's ok because we are using an a tag
                    // there are too many to handle manually
                    _jsx(LinkMessage, Object.assign({}, rest, linkProps, { children: props.children })));
                },
                // used for footnotes
                sup: (props) => {
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    const { node } = props, rest = __rest(props, ["node"]);
                    return _jsx(SuperscriptMessage, Object.assign({}, rest));
                }
            }, remarkPlugins: [[remarkGfm, Object.assign({}, remarkGfmProps)], ...additionalRemarkPlugins], rehypePlugins: rehypePlugins }, reactMarkdownProps, { remarkRehypeOptions: Object.assign({ 
                // removes sr-only class from footnote labels applied by default
                footnoteLabelProperties: { className: [''] } }, reactMarkdownProps === null || reactMarkdownProps === void 0 ? void 0 : reactMarkdownProps.remarkRehypeOptions), disallowedElements: disallowedElements, children: messageText })));
    };
    const renderMessage = () => {
        if (isLoading) {
            return _jsx(MessageLoading, { loadingWord: loadingWord, isPrimary: isPrimary });
        }
        if (isEditable) {
            return (_jsxs(_Fragment, { children: [beforeMainContent && _jsx(_Fragment, { children: beforeMainContent }), _jsx(MessageInput, Object.assign({ content: messageText, editPlaceholder: editPlaceholder, updateWord: updateWord, cancelWord: cancelWord, onEditUpdate: (event, value) => {
                            onEditUpdate && onEditUpdate(event);
                            setMessageText(value);
                        }, onEditCancel: onEditCancel, inputRef: inputRef }, editFormProps))] }));
        }
        return (_jsxs(_Fragment, { children: [beforeMainContent && _jsx(_Fragment, { children: beforeMainContent }), error ? _jsx(ErrorMessage, Object.assign({}, error)) : handleMarkdown()] }));
    };
    return (_jsxs("section", Object.assign({ "aria-label": `Message from ${role} - ${dateString}`, className: `pf-chatbot__message pf-chatbot__message--${role}`, "aria-live": isLiveRegion ? 'polite' : undefined, "aria-atomic": isLiveRegion ? false : undefined, ref: innerRef }, props, { children: [avatar && (_jsx(Avatar, Object.assign({ className: `pf-chatbot__message-avatar ${hasRoundAvatar ? 'pf-chatbot__message-avatar--round' : ''} ${avatarClassName ? avatarClassName : ''}`, src: avatar, alt: "" }, avatarProps))), _jsxs("div", { className: "pf-chatbot__message-contents", children: [_jsxs("div", { className: "pf-chatbot__message-meta", children: [name && (_jsx("span", { className: "pf-chatbot__message-name", children: _jsx(Truncate, { content: name }) })), role === 'bot' && (_jsx(Label, { variant: "outline", isCompact: true, children: botWord })), _jsx(Timestamp, { date: date, children: timestamp })] }), _jsxs("div", { className: "pf-chatbot__message-response", children: [_jsxs("div", { className: "pf-chatbot__message-and-actions", children: [renderMessage(), afterMainContent && _jsx(_Fragment, { children: afterMainContent }), toolResponse && _jsx(ToolResponse, Object.assign({}, toolResponse)), deepThinking && _jsx(DeepThinking, Object.assign({}, deepThinking)), toolCall && _jsx(ToolCall, Object.assign({}, toolCall)), !isLoading && sources && _jsx(SourcesCard, Object.assign({}, sources, { isCompact: isCompact })), quickStarts && quickStarts.quickStart && (_jsx(QuickStartTile, { quickStart: quickStarts.quickStart, onSelectQuickStart: quickStarts.onSelectQuickStart, minuteWord: quickStarts.minuteWord, minuteWordPlural: quickStarts.minuteWordPlural, prerequisiteWord: quickStarts.prerequisiteWord, prerequisiteWordPlural: quickStarts.prerequisiteWordPlural, quickStartButtonAriaLabel: quickStarts.quickStartButtonAriaLabel, isCompact: isCompact })), !isLoading && !isEditable && actions && (_jsx(ResponseActions, { actions: actions, persistActionSelection: persistActionSelection })), userFeedbackForm && _jsx(UserFeedback, Object.assign({}, userFeedbackForm, { timestamp: dateString, isCompact: isCompact })), userFeedbackComplete && (_jsx(UserFeedbackComplete, Object.assign({}, userFeedbackComplete, { timestamp: dateString, isCompact: isCompact }))), !isLoading && quickResponses && (_jsx(QuickResponse, { quickResponses: quickResponses, quickResponseContainerProps: quickResponseContainerProps, isCompact: isCompact }))] }), attachments && (_jsx("div", { className: "pf-chatbot__message-attachments-container", children: attachments.map((attachment) => {
                                    var _a;
                                    return (_jsx("div", { className: "pf-chatbot__message-attachment", children: _jsx(FileDetailsLabel, { fileName: attachment.name, fileId: attachment.id, onClose: attachment.onClose, onClick: attachment.onClick, isLoading: attachment.isLoading, closeButtonAriaLabel: attachment.closeButtonAriaLabel, languageTestId: attachment.languageTestId, spinnerTestId: attachment.spinnerTestId, variant: isPrimary ? 'outline' : undefined }) }, (_a = attachment.id) !== null && _a !== void 0 ? _a : attachment.name));
                                }) })), !isLoading && endContent && _jsx(_Fragment, { children: endContent })] })] })] })));
};
const Message = forwardRef((props, ref) => (_jsx(MessageBase, Object.assign({ innerRef: ref }, props))));
export default Message;
