import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { memo, useState, useCallback, useMemo } from 'react';
import { Sparkles, GitBranch, Copy, Check, Shield, CheckCheck, } from 'lucide-react';
import { MessagePartItem } from './MessagePartItem';
import { useMessageQueuePosition } from '../../hooks/useQueueState';
import { BranchModal } from '../branch/BranchModal';
import { ProviderLogo } from '../common/ProviderLogo';
import { useToolApprovalStore } from '../../stores/toolApprovalStore';
import { apiClient } from '../../lib/api-client';
const loadingMessages = [
    'Generating...',
    'Cooking up something...',
    'Thinking...',
    'Processing...',
    'Working on it...',
    'Crafting response...',
    'Brewing magic...',
    'Computing...',
];
function getLoadingMessage(messageId) {
    const hash = messageId
        .split('')
        .reduce((acc, char) => acc + char.charCodeAt(0), 0);
    return loadingMessages[hash % loadingMessages.length];
}
export const AssistantMessageGroup = memo(function AssistantMessageGroup({ sessionId, message, showHeader, hasNextAssistantMessage, onBranchCreated, compact, showBranchButton = true, onNavigateToSession, onRetry, }) {
    const { isQueued } = useMessageQueuePosition(sessionId, message.id);
    const [isHovered, setIsHovered] = useState(false);
    const [showBranchModal, setShowBranchModal] = useState(false);
    const [copied, setCopied] = useState(false);
    // Tool approval handling
    const { pendingApprovals, removePendingApproval } = useToolApprovalStore();
    const handleApprove = useCallback(async (callId) => {
        if (!sessionId)
            return;
        try {
            await apiClient.approveToolCall(sessionId, callId, true);
            removePendingApproval(callId);
        }
        catch (error) {
            console.error('Failed to approve tool call:', error);
        }
    }, [sessionId, removePendingApproval]);
    const handleReject = useCallback(async (callId) => {
        if (!sessionId)
            return;
        try {
            await apiClient.approveToolCall(sessionId, callId, false);
            removePendingApproval(callId);
        }
        catch (error) {
            console.error('Failed to reject tool call:', error);
        }
    }, [sessionId, removePendingApproval]);
    // Handle approving all pending approvals for this message
    const messagePendingApprovals = useMemo(() => {
        return pendingApprovals.filter((a) => a.messageId === message.id);
    }, [pendingApprovals, message.id]);
    const handleApproveAll = useCallback(async () => {
        if (!sessionId)
            return;
        try {
            await Promise.all(messagePendingApprovals.map((a) => apiClient.approveToolCall(sessionId, a.callId, true)));
            for (const a of messagePendingApprovals) {
                removePendingApproval(a.callId);
            }
        }
        catch (error) {
            console.error('Failed to approve all tool calls:', error);
        }
    }, [sessionId, messagePendingApprovals, removePendingApproval]);
    // Sort parts by index to maintain correct order when tool results come in
    const parts = useMemo(() => {
        const rawParts = message.parts || [];
        return [...rawParts].sort((a, b) => {
            const indexDiff = (a.index ?? 0) - (b.index ?? 0);
            if (indexDiff !== 0)
                return indexDiff;
            // Secondary sort by startedAt for parts with same index
            return (a.startedAt ?? 0) - (b.startedAt ?? 0);
        });
    }, [message.parts]);
    const hasFinish = parts.some((part) => part.toolName === 'finish');
    const latestProgressUpdateIndex = parts.reduce((lastIndex, part, index) => part.type === 'tool_result' && part.toolName === 'progress_update'
        ? index
        : lastIndex, -1);
    const latestProgressUpdatePart = latestProgressUpdateIndex >= 0 ? parts[latestProgressUpdateIndex] : null;
    const hasVisibleNonProgressParts = parts.some((part) => !(part.type === 'tool_result' && part.toolName === 'progress_update'));
    const firstVisiblePartIndex = parts.findIndex((part) => !(part.type === 'tool_result' && part.toolName === 'progress_update'));
    const shouldShowProgressUpdate = message.status === 'pending' &&
        !hasFinish &&
        Boolean(latestProgressUpdatePart);
    const shouldShowLoadingFallback = message.status === 'pending' &&
        !hasFinish &&
        !latestProgressUpdatePart &&
        !isQueued;
    const formatTime = (ts) => {
        if (!ts)
            return '';
        const date = new Date(ts);
        return date.toLocaleTimeString([], {
            hour: '2-digit',
            minute: '2-digit',
        });
    };
    const isComplete = message.status === 'complete';
    const handleCopy = useCallback(() => {
        const textParts = parts
            .filter((p) => p.type === 'text')
            .map((p) => {
            try {
                const parsed = JSON.parse(p.content || '{}');
                return parsed?.text || '';
            }
            catch {
                return p.content || '';
            }
        })
            .join('\n');
        navigator.clipboard.writeText(textParts);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    }, [parts]);
    const handleBranchClick = useCallback(() => {
        setShowBranchModal(true);
    }, []);
    if (isQueued) {
        return null;
    }
    return (
    // biome-ignore lint/a11y/noStaticElementInteractions: hover state for showing actions
    _jsxs("div", { className: "relative group", onMouseEnter: () => setIsHovered(true), onMouseLeave: () => setIsHovered(false), children: [showHeader && (_jsxs("div", { className: "pb-2 flex items-center justify-between", children: [_jsxs("div", { className: "inline-flex items-center bg-violet-500/10 border border-violet-500/30 dark:bg-violet-500/5 dark:border-violet-500/20 rounded-full pr-3 md:pr-4 flex-shrink min-w-0", children: [_jsx("div", { className: "flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-violet-500/50 bg-violet-500/20 dark:bg-violet-500/10", children: _jsx(Sparkles, { className: "h-3.5 w-3.5 text-violet-700 dark:text-violet-300" }) }), _jsxs("div", { className: "flex items-center gap-x-1.5 md:gap-x-2 text-xs md:text-sm text-muted-foreground pl-2 md:pl-3 min-w-0", children: [message.agent && !compact && (_jsx("span", { className: "font-medium text-violet-700 dark:text-violet-300 whitespace-nowrap", children: message.agent })), message.provider && (_jsxs(_Fragment, { children: [!compact && message.agent && (_jsx("span", { className: "text-muted-foreground/50", children: "\u00B7" })), _jsx(ProviderLogo, { provider: message.provider, size: 14, className: "opacity-70" })] })), message.model && (_jsxs(_Fragment, { children: [_jsx("span", { className: "hidden md:inline text-muted-foreground/50", children: "\u00B7" }), _jsx("span", { className: `hidden md:inline text-muted-foreground ${compact ? 'truncate max-w-[120px]' : ''}`, title: message.model, children: message.model })] })), message.createdAt && (_jsxs(_Fragment, { children: [_jsx("span", { className: "text-muted-foreground/50", children: "\u00B7" }), _jsx("span", { className: "text-muted-foreground whitespace-nowrap", children: formatTime(message.createdAt) })] }))] })] }), isHovered && isComplete && sessionId && showBranchButton && (_jsx("button", { type: "button", onClick: handleBranchClick, className: "ml-4 p-1.5 text-muted-foreground hover:text-primary transition-colors flex-shrink-0", title: "Branch from this message", children: _jsx(GitBranch, { className: "h-4 w-4" }) }))] })), _jsxs("div", { className: "relative ml-1", children: [parts.map((part, index) => {
                        const isLastPart = index === parts.length - 1;
                        // Find pending approval for this part's tool call
                        const pendingApproval = part.type === 'tool_call' && part.toolCallId
                            ? (pendingApprovals.find((a) => a.callId === part.toolCallId) ??
                                null)
                            : null;
                        const isFinishTool = part.type === 'tool_result' && part.toolName === 'finish';
                        const showLine = (!isLastPart || hasNextAssistantMessage) && !isFinishTool;
                        const isLastToolCall = part.type === 'tool_call' && isLastPart;
                        const isProgressUpdate = part.type === 'tool_result' &&
                            part.toolName === 'progress_update';
                        if (isProgressUpdate) {
                            return null;
                        }
                        return (_jsx(MessagePartItem, { part: part, showLine: showLine, isFirstPart: index === firstVisiblePartIndex && !showHeader, isLastToolCall: isLastToolCall, onNavigateToSession: onNavigateToSession, compact: compact, pendingApproval: pendingApproval, onApprove: handleApprove, onReject: handleReject, sessionId: sessionId, onRetry: onRetry }, part.id));
                    }), messagePendingApprovals.length > 1 && (_jsxs("div", { className: "flex items-center gap-3 py-2 px-3 my-2 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg", children: [_jsx(Shield, { className: "h-4 w-4 text-amber-600 dark:text-amber-400 flex-shrink-0" }), _jsxs("span", { className: "text-sm text-amber-800 dark:text-amber-200 flex-1", children: [messagePendingApprovals.length, " tools waiting for approval"] }), _jsxs("button", { type: "button", onClick: handleApproveAll, title: "Approve All (A)", className: "flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded bg-amber-600 text-white hover:bg-amber-700 transition-colors", children: [_jsx(CheckCheck, { className: "w-3.5 h-3.5" }), "Approve All", _jsx("kbd", { className: "ml-1 text-[10px] opacity-70", children: "A" })] })] })), shouldShowProgressUpdate && latestProgressUpdatePart && (_jsx(MessagePartItem, { part: latestProgressUpdatePart, showLine: hasNextAssistantMessage, isFirstPart: !hasVisibleNonProgressParts && !showHeader, isLastProgressUpdate: true, compact: compact }, latestProgressUpdatePart.id)), shouldShowLoadingFallback && (_jsxs("div", { className: "flex gap-3 pb-2 relative", children: [_jsx("div", { className: "flex-shrink-0 w-6 flex items-start justify-center relative pt-0.5", children: _jsx("div", { className: "flex h-5 w-5 shrink-0 items-center justify-center rounded-full relative bg-card text-violet-700 dark:bg-background dark:text-violet-300", children: _jsx(Sparkles, { className: "h-4 w-4" }) }) }), _jsx("div", { className: "flex-1 pt-0.5", children: _jsx("div", { className: "text-base text-foreground animate-pulse", children: getLoadingMessage(message.id) }) })] }))] }), isComplete && sessionId && (_jsx("div", { className: "grid ml-7 transition-[grid-template-rows] duration-200 ease-out", style: { gridTemplateRows: isHovered ? '1fr' : '0fr' }, children: _jsx("div", { className: "overflow-hidden", children: _jsxs("div", { className: "flex gap-2 mt-2", children: [showBranchButton && (_jsxs("button", { type: "button", onClick: handleBranchClick, className: "flex items-center gap-1.5 px-2 py-1 text-xs text-muted-foreground hover:text-foreground hover:bg-muted/50 rounded transition-colors", children: [_jsx(GitBranch, { className: "h-3 w-3" }), "Branch"] })), _jsx("button", { type: "button", onClick: handleCopy, className: "flex items-center gap-1.5 px-2 py-1 text-xs text-muted-foreground hover:text-foreground hover:bg-muted/50 rounded transition-colors", children: copied ? (_jsxs(_Fragment, { children: [_jsx(Check, { className: "h-3 w-3 text-green-500" }), "Copied"] })) : (_jsxs(_Fragment, { children: [_jsx(Copy, { className: "h-3 w-3" }), "Copy"] })) })] }) }) })), showBranchModal && sessionId && (_jsx(BranchModal, { isOpen: showBranchModal, onClose: () => setShowBranchModal(false), sessionId: sessionId, message: message, onBranchCreated: onBranchCreated }))] }));
}, (prevProps, nextProps) => {
    const prevParts = prevProps.message.parts || [];
    const nextParts = nextProps.message.parts || [];
    if (prevParts.length !== nextParts.length) {
        return false;
    }
    for (let i = 0; i < prevParts.length; i++) {
        const prevPart = prevParts[i];
        const nextPart = nextParts[i];
        if (prevPart.id !== nextPart.id ||
            prevPart.content !== nextPart.content ||
            prevPart.contentJson !== nextPart.contentJson ||
            prevPart.ephemeral !== nextPart.ephemeral ||
            prevPart.completedAt !== nextPart.completedAt) {
            return false;
        }
    }
    return (prevProps.message.id === nextProps.message.id &&
        prevProps.message.status === nextProps.message.status &&
        prevProps.message.completedAt === nextProps.message.completedAt &&
        prevProps.showHeader === nextProps.showHeader &&
        prevProps.hasNextAssistantMessage === nextProps.hasNextAssistantMessage &&
        prevProps.isLastMessage === nextProps.isLastMessage &&
        prevProps.sessionId === nextProps.sessionId &&
        prevProps.compact === nextProps.compact &&
        prevProps.onNavigateToSession === nextProps.onNavigateToSession);
});
//# sourceMappingURL=AssistantMessageGroup.js.map