import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useRef } from "react";
import { formatTime } from "../utils";
import { useEditContext } from "../client/editContext";
import { MessageSquare, ChevronUp, ChevronDown } from "lucide-react";
export function WebSocketMessages() {
    const editContext = useEditContext();
    const [expandedMessages, setExpandedMessages] = useState(new Set());
    const [autoScroll, setAutoScroll] = useState(true);
    const messagesEndRef = useRef(null);
    const containerRef = useRef(null);
    // Get messages from central store
    const messages = editContext?.webSocketMessages || [];
    // Auto-scroll to bottom when new messages arrive
    useEffect(() => {
        if (autoScroll && messagesEndRef.current) {
            messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
        }
    }, [messages, autoScroll]);
    const toggleExpanded = (messageId) => {
        setExpandedMessages((prev) => {
            const newSet = new Set(prev);
            if (newSet.has(messageId)) {
                newSet.delete(messageId);
            }
            else {
                newSet.add(messageId);
            }
            return newSet;
        });
    };
    const formatTimestamp = (isoString) => {
        const date = new Date(isoString);
        const base = formatTime(date);
        return base + "." + date.getMilliseconds().toString().padStart(3, "0");
    };
    const getMessageTypeColor = (type) => {
        const colors = {
            "active-sessions": "bg-blue-100 text-blue-800",
            "item-deleted": "bg-red-100 text-red-800",
            "item-changed": "bg-yellow-100 text-yellow-800",
            "item-version-added": "bg-green-100 text-green-800",
            "load-item": "bg-teal-100 text-teal-800",
            "edit-operation": "bg-purple-100 text-purple-800",
            "executing-field-action": "bg-orange-100 text-orange-800",
            "comment-updated": "bg-cyan-100 text-cyan-800",
            "comment-deleted": "bg-red-100 text-red-800",
            "suggested-edit-updated": "bg-indigo-100 text-indigo-800",
            "suggested-edit-deleted": "bg-red-100 text-red-800",
            "update-quota": "bg-gray-100 text-gray-800",
            "agent:run:closed": "bg-red-100 text-red-800",
            "agent:run:start": "bg-green-100 text-green-800",
            "agent:name:updated": "bg-blue-100 text-blue-800",
        };
        return colors[type] || "bg-gray-100 text-gray-800";
    };
    const clearMessages = () => {
        editContext?.clearWebSocketMessages();
    };
    const handleScroll = () => {
        if (!containerRef.current)
            return;
        const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
        const isAtBottom = scrollHeight - scrollTop <= clientHeight + 10;
        setAutoScroll(isAtBottom);
    };
    return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-gray-200 p-4", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(MessageSquare, { className: "h-5 w-5" }), _jsx("span", { className: "rounded bg-gray-100 px-2 py-1 text-sm text-gray-800", children: messages.length })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsxs("label", { className: "flex items-center gap-1 text-sm", children: [_jsx("input", { type: "checkbox", checked: autoScroll, onChange: (e) => setAutoScroll(e.target.checked), className: "rounded" }), "Auto-scroll"] }), _jsx("button", { onClick: clearMessages, className: "rounded bg-red-500 px-3 py-1 text-sm text-white hover:bg-red-600", children: "Clear" })] })] }), _jsxs("div", { ref: containerRef, className: "flex-1 space-y-2 overflow-y-auto p-4", onScroll: handleScroll, children: [messages.length === 0 ? (_jsx("div", { className: "py-8 text-center text-gray-500", children: "No WebSocket messages received yet" })) : (messages.map((message) => (_jsxs("div", { className: "rounded-lg border border-gray-200", children: [_jsxs("div", { className: "flex cursor-pointer items-center justify-between p-3 hover:bg-gray-50", onClick: () => toggleExpanded(message.id), children: [_jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-3", children: [_jsx("span", { className: "font-mono text-xs text-gray-500", children: formatTimestamp(message.timestamp) }), _jsxs("span", { className: `rounded px-2 py-1 text-xs font-medium ${getMessageTypeColor(message.type)}`, children: [message.direction === "outgoing" ? "sent " : "", message.type] }), message.seq != null && (_jsxs("span", { className: "rounded bg-gray-100 px-2 py-1 font-mono text-xs text-gray-600", children: ["seq ", message.seq] })), message.agentId && (_jsx("span", { className: "rounded bg-gray-100 px-2 py-1 font-mono text-xs text-gray-600", children: message.agentId })), _jsxs("span", { className: "truncate text-sm text-gray-600", children: [message.detail ||
                                                        (typeof message.payload === "object"
                                                            ? Object.keys(message.payload).join(", ")
                                                            : String(message.payload)), message.payloadBytes != null
                                                        ? ` (${message.payloadBytes} bytes)`
                                                        : ""] })] }), expandedMessages.has(message.id) ? (_jsx(ChevronUp, { className: "h-4 w-4 text-gray-400" })) : (_jsx(ChevronDown, { className: "h-4 w-4 text-gray-400" }))] }), expandedMessages.has(message.id) && (_jsx("div", { className: "border-t border-gray-200 bg-gray-50 p-3", children: _jsx("pre", { className: "overflow-x-auto font-mono text-xs wrap-break-word whitespace-pre-wrap", children: message.rawMessage }) }))] }, message.id)))), _jsx("div", { ref: messagesEndRef })] })] }));
}
//# sourceMappingURL=WebSocketMessages.js.map