import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from "react";
import { Bot, ChevronDown, ChevronUp, FileText, Image as ImageIcon, Target, } from "lucide-react";
import { TimeWithTooltip } from "../../TimeWithTooltip";
import { MarkdownDisplay } from "../../../../components/MarkdownDisplay";
import { userMessageMarkdownComponents } from "../../agentMessageMarkdown";
import { Avatar } from "../../../../components/ui/avatar";
import { cn } from "../../../../lib/utils";
import { useEditContext } from "../../../client/editContext";
function normalizeUserName(value) {
    return (value || "").trim().toLowerCase();
}
function isGenericUserName(value) {
    const normalized = normalizeUserName(value);
    return !normalized || normalized === "user";
}
function parseMessageMetadata(metadata) {
    if (!metadata)
        return null;
    if (typeof metadata === "object")
        return metadata;
    try {
        return JSON.parse(metadata);
    }
    catch {
        return null;
    }
}
// Reserved automation prefixes the backend bakes into content. Kept as a
// read-only fallback for legacy messages that predate the structured origin.
const FROM_PATTERN = /^\[From ([^\]]+)\]:\s*([\s\S]*)$/;
const TRIGGER_PATTERN = /^\[Trigger: ([^\]]+)\]:\s*([\s\S]*)$/;
function stripFromPrefix(content) {
    const match = content.match(FROM_PATTERN);
    if (match && match[1]) {
        // "[From user]:" is a self-reference, not an agent — treat as human.
        if (match[1].toLowerCase() === "user")
            return { body: content, isUser: true };
        return { name: match[1], body: match[2] ?? "", isUser: false };
    }
    return { body: content, isUser: false };
}
/**
 * Decides how a user-role message should render. The structured `messageOrigin`
 * (and persisted `metadata.origin`) are authoritative; "user" is terminal so a
 * human who literally types "[From X]:" is never shown as automated. Only when
 * no structured origin exists (legacy messages) do we fall back to parsing the
 * "[From X]:" / "[Trigger: X]:" content prefixes.
 */
function resolveMessageOrigin(message, metadata) {
    const fields = message;
    const content = message.content || "";
    const structuredType = fields.messageOrigin ?? metadata?.origin?.type;
    if (structuredType === "trigger") {
        const triggerMatch = content.match(TRIGGER_PATTERN);
        return {
            kind: "trigger",
            triggerName: (fields.triggerName ??
                metadata?.origin?.triggerName ??
                triggerMatch?.[1] ??
                "").trim(),
            displayContent: triggerMatch?.[2] ?? content,
        };
    }
    if (structuredType === "user") {
        return { kind: "user", displayContent: content };
    }
    if (structuredType === "agent") {
        const stripped = stripFromPrefix(content);
        return {
            kind: "agent",
            sourceAgentName: fields.sourceAgentName ??
                metadata?.origin?.sourceAgentName ??
                stripped.name ??
                metadata?.sourceAgentName,
            displayContent: stripped.body,
        };
    }
    // Legacy fallback: no structured origin — parse content prefixes.
    const triggerMatch = content.match(TRIGGER_PATTERN);
    if (triggerMatch && triggerMatch[1]) {
        return {
            kind: "trigger",
            triggerName: triggerMatch[1].trim(),
            displayContent: triggerMatch[2] ?? "",
        };
    }
    const stripped = stripFromPrefix(content);
    if (!stripped.isUser && stripped.name) {
        return {
            kind: "agent",
            sourceAgentName: stripped.name,
            displayContent: stripped.body,
        };
    }
    const legacySourceAgentName = metadata?.sourceAgentName ?? fields.sourceAgentName ?? fields.sourceAgent?.name;
    if (legacySourceAgentName) {
        return {
            kind: "agent",
            sourceAgentName: legacySourceAgentName,
            displayContent: content,
        };
    }
    return { kind: "user", displayContent: content };
}
function isAttachmentLike(value) {
    return (!!value &&
        typeof value === "object" &&
        typeof value.fileName === "string" &&
        value.fileName.trim().length > 0);
}
function normalizeAttachments(values) {
    if (!Array.isArray(values))
        return [];
    return values.filter(isAttachmentLike).map((attachment) => ({
        ...attachment,
        fileName: attachment.fileName.trim(),
        contentType: attachment.contentType || attachment.fileType,
    }));
}
function getMessageAttachments(message) {
    const directAttachments = normalizeAttachments(message.attachments);
    const metadata = parseMessageMetadata(message.metadata);
    const metadataAttachments = normalizeAttachments(metadata?.attachments);
    const metadataUploadedDocuments = normalizeAttachments(metadata?.uploadedDocuments);
    const answerUploadedDocuments = Array.isArray(metadata?.answers)
        ? metadata.answers.flatMap((answer) => normalizeAttachments(answer && typeof answer === "object"
            ? answer.uploadedDocuments
            : undefined))
        : [];
    const attachments = [
        ...directAttachments,
        ...metadataAttachments,
        ...metadataUploadedDocuments,
        ...answerUploadedDocuments,
    ];
    const seen = new Set();
    return attachments.filter((attachment) => {
        const key = (attachment.id ||
            attachment.attachmentId ||
            `${attachment.fileName}:${attachment.fileSize ?? ""}`).toLowerCase();
        if (seen.has(key))
            return false;
        seen.add(key);
        return true;
    });
}
function formatFileSize(bytes) {
    if (typeof bytes !== "number" || !Number.isFinite(bytes) || bytes <= 0) {
        return "";
    }
    if (bytes < 1024)
        return `${bytes} B`;
    const units = ["KB", "MB", "GB"];
    let value = bytes / 1024;
    let unitIndex = 0;
    while (value >= 1024 && unitIndex < units.length - 1) {
        value /= 1024;
        unitIndex += 1;
    }
    return `${value >= 10 ? value.toFixed(0) : value.toFixed(1)} ${units[unitIndex]}`;
}
function getAttachmentHref(attachment) {
    if (attachment.url)
        return attachment.url;
    if (attachment.id) {
        return `/parhelia/agent/downloadDocument?documentId=${encodeURIComponent(attachment.id)}`;
    }
    if (attachment.attachmentId) {
        return `/parhelia/tasks/downloadAttachment?attachmentId=${encodeURIComponent(attachment.attachmentId)}`;
    }
    return null;
}
function isImageAttachment(attachment) {
    const contentType = attachment.contentType?.toLowerCase();
    if (contentType?.startsWith("image/"))
        return true;
    return /\.(avif|bmp|gif|jpe?g|png|svg|webp)$/i.test(attachment.fileName);
}
function ImageAttachmentThumbnail({ attachment, href, fileSize, title, }) {
    const [hasImageError, setHasImageError] = useState(false);
    return (_jsxs("a", { href: href, download: attachment.fileName, className: "border-border-default hover:bg-neutral-grey-5 inline-flex max-w-full items-center gap-2 rounded-md border bg-white p-1.5 pr-2 text-[12px] text-neutral-grey-100 shadow-sm", title: title, "data-testid": "user-message-image-attachment", children: [_jsx("span", { className: "border-border-default bg-neutral-grey-5 flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded border", children: hasImageError ? (_jsx(ImageIcon, { className: "text-neutral-grey-50 h-5 w-5", strokeWidth: 1.5 })) : (_jsx("img", { src: href, alt: attachment.fileName, loading: "lazy", className: "h-full w-full object-cover", onError: () => setHasImageError(true) })) }), _jsxs("span", { className: "min-w-0", children: [_jsx("span", { className: "block max-w-[220px] truncate leading-tight font-medium", children: attachment.fileName }), _jsx("span", { className: "text-neutral-grey-50 block text-[11px] leading-tight", children: fileSize || "Image" })] })] }));
}
function MessageAttachments({ attachments, }) {
    if (attachments.length === 0)
        return null;
    return (_jsx("div", { className: "mt-2 flex flex-wrap gap-1.5", "data-testid": "user-message-attachments", children: attachments.map((attachment, index) => {
            const fileSize = formatFileSize(attachment.fileSize);
            const href = getAttachmentHref(attachment);
            const title = fileSize
                ? `${attachment.fileName} (${fileSize})`
                : attachment.fileName;
            if (href && isImageAttachment(attachment)) {
                return (_jsx(ImageAttachmentThumbnail, { attachment: attachment, href: href, fileSize: fileSize, title: title }, `${attachment.id || attachment.attachmentId || attachment.fileName}-${index}`));
            }
            const icon = (_jsx(FileText, { className: "text-neutral-grey-50 h-3.5 w-3.5 shrink-0" }));
            const content = (_jsxs(_Fragment, { children: [icon, _jsx("span", { className: "max-w-[220px] truncate", children: attachment.fileName }), fileSize && (_jsx("span", { className: "text-neutral-grey-50 shrink-0", children: fileSize }))] }));
            const className = "border-border-default bg-white badge-pad text-2xs text-neutral-grey-100 inline-flex max-w-full items-center gap-1.5 rounded-badge border";
            return href ? (_jsx("a", { href: href, download: attachment.fileName, className: `${className} hover:bg-neutral-grey-5`, title: title, children: content }, `${attachment.id || attachment.attachmentId || attachment.fileName}-${index}`)) : (_jsx("span", { className: className, title: title, children: content }, `${attachment.fileName}-${index}`));
        }) }));
}
export const UserMessage = ({ message, isFirstUserMessage = false, followsUserMessage = false, }) => {
    const editContext = useEditContext();
    const attachments = getMessageAttachments(message);
    const [isTriggerExpanded, setIsTriggerExpanded] = useState(false);
    const metadata = parseMessageMetadata(message.metadata);
    const origin = resolveMessageOrigin(message, metadata);
    // --- Trigger prompts: compact collapsible banner ------------------------
    if (origin.kind === "trigger") {
        const triggerName = origin.triggerName;
        const triggerContent = origin.displayContent;
        return (_jsx("div", { className: "px-4 py-2", children: _jsxs("div", { className: "text-[11px]", children: [_jsxs("button", { type: "button", onClick: () => setIsTriggerExpanded((expanded) => !expanded), className: "text-highlight-100 hover:bg-theme-hover border-component-suggestions badge-pad flex w-full items-center gap-2 rounded-md border-l-2 text-left transition-colors", "data-testid": "trigger-message-toggle", "data-expanded": isTriggerExpanded ? "true" : "false", children: [_jsx(Target, { className: "h-3.5 w-3.5 shrink-0", strokeWidth: 1.5 }), _jsxs("span", { className: "truncate font-medium", children: ["Trigger: ", triggerName] }), message.createdDate && (_jsx(TimeWithTooltip, { date: new Date(message.createdDate), className: "text-neutral-grey-50 ml-1 shrink-0 text-[10px]" })), _jsx("span", { className: "ml-auto shrink-0", children: isTriggerExpanded ? (_jsx(ChevronUp, { className: "h-3.5 w-3.5" })) : (_jsx(ChevronDown, { className: "h-3.5 w-3.5" })) })] }), isTriggerExpanded && (_jsx("div", { className: "border-component-suggestions text-neutral-grey-50 mt-1 border-l-2 pl-[1.35rem] text-[11px]", children: _jsx(MarkdownDisplay, { source: triggerContent, components: userMessageMarkdownComponents }) }))] }) }));
    }
    // --- Automated (agent / system) prompts: distinct "not a person" banner --
    if (origin.kind === "agent") {
        return (_jsx("div", { className: "px-4 py-2", "data-testid": "automated-user-message", children: _jsxs("div", { className: cn("border-feedback-blue bg-feedback-blue-light/80", "flex gap-2 rounded-md border px-3 py-2"), children: [_jsx(Bot, { className: "text-feedback-blue mt-0.5 h-3.5 w-3.5 shrink-0", strokeWidth: 1.5 }), _jsxs("div", { className: "min-w-0 flex-1 select-text", children: [_jsxs("div", { className: "mb-1 flex items-center gap-2 text-[11px]", children: [_jsxs("span", { className: "text-feedback-blue font-medium", children: ["Automated", origin.sourceAgentName
                                                ? ` · from ${origin.sourceAgentName}`
                                                : ""] }), message.createdDate && (_jsx(TimeWithTooltip, { date: new Date(message.createdDate), className: "text-feedback-blue/80 shrink-0 text-[10px]", testId: "automated-message-timestamp", timestampAttr: message.createdDate }))] }), _jsx("div", { className: "prose text-neutral-grey-100 max-w-none text-[12px] select-text", children: _jsx(MarkdownDisplay, { source: origin.displayContent, components: userMessageMarkdownComponents }) }), _jsx(MessageAttachments, { attachments: attachments })] })] }) }));
    }
    // --- Human user message: grey bubble ------------------------------------
    const displayContent = origin.displayContent;
    const currentUser = editContext?.user;
    const messageUserName = message.name;
    const isCurrentUserMessage = isGenericUserName(messageUserName) ||
        normalizeUserName(messageUserName) === normalizeUserName(currentUser?.name);
    const authorSession = editContext?.activeSessions.find((session) => normalizeUserName(session.user.name) ===
        normalizeUserName(messageUserName));
    const authorName = authorSession?.user.fullName ||
        authorSession?.user.name ||
        (!isGenericUserName(messageUserName) ? messageUserName : undefined);
    const displayName = isCurrentUserMessage ? "You" : authorName || "Another user";
    const currentSession = editContext?.activeSessions.find((session) => session.sessionId === editContext.sessionId);
    const currentUserName = currentUser?.fullName || currentUser?.name || "You";
    const avatarName = authorName || currentUserName;
    const avatarSrc = isCurrentUserMessage
        ? (currentSession?.user.avatarUrl ?? currentUser?.avatarUrl)
        : authorSession?.user.avatarUrl;
    const avatarFallbackColor = isCurrentUserMessage
        ? currentSession?.color
        : authorSession?.color;
    return (_jsxs("div", { className: `bg-neutral-grey-5 mx-4 flex gap-3 rounded-[12px] px-4 py-3 ${isFirstUserMessage ? "mt-3" : followsUserMessage ? "mt-2" : ""}`, children: [_jsx("div", { className: "shrink-0", children: _jsx(Avatar, { src: avatarSrc, name: avatarName, fallbackColor: avatarFallbackColor, title: avatarName, size: "sm", className: "size-6 text-[10px]" }) }), _jsxs("div", { className: "min-w-0 flex-1 select-text", children: [_jsxs("div", { className: "mb-1 flex items-center gap-2", children: [_jsx("span", { className: "text-neutral-grey-100 text-[12px] font-medium", children: displayName }), message.createdDate && (_jsx(TimeWithTooltip, { date: new Date(message.createdDate), className: "text-neutral-grey-50 text-[12px]", testId: "user-message-timestamp", timestampAttr: message.createdDate }))] }), _jsx("div", { className: "prose prose text-neutral-grey-100 max-w-none text-[12px] select-text", children: _jsx(MarkdownDisplay, { source: displayContent, components: userMessageMarkdownComponents }) }), _jsx(MessageAttachments, { attachments: attachments })] })] }));
};
//# sourceMappingURL=UserMessage.js.map