import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useMemo } from "react";
import { ChevronDown, ChevronUp, GitBranch } from "lucide-react";
import { TimeWithTooltip } from "../../TimeWithTooltip";
import { cn } from "../../../../lib/utils";
export function SpawnedAgentsPanel({ agentMetadata, headerless, }) {
    const [isExpanded, setIsExpanded] = useState(true);
    // Extract child agents from metadata
    const childAgents = useMemo(() => {
        if (!agentMetadata)
            return [];
        try {
            const childAgents = agentMetadata?.childAgents;
            if (!Array.isArray(childAgents) || childAgents.length === 0) {
                return [];
            }
            // Normalize to a consistent format, filtering out invalid entries
            return childAgents
                .filter((agent) => agent != null && typeof agent === "object")
                .map((agent) => ({
                id: String(agent.agentId || ""),
                name: String(agent.name || "Unknown Agent"),
                profileName: String(agent.profileName || ""),
                status: String(agent.status || "unknown"),
                spawnedAt: String(agent.spawnedAt || ""),
                task: String(agent.task || ""),
            }))
                .filter((agent) => agent.id); // Only include agents with valid IDs
        }
        catch (e) {
            console.error("📋 Error extracting spawned agents from metadata:", e);
            return [];
        }
    }, [agentMetadata]);
    if (childAgents.length === 0)
        return null;
    // Helper to get status color based on status string
    const getStatusColor = (status) => {
        const normalizedStatus = status.toLowerCase();
        if (normalizedStatus === "running")
            return "bg-highlight-100";
        if (normalizedStatus === "waitingforapproval" ||
            normalizedStatus === "waiting for approval")
            return "bg-feedback-orange";
        if (normalizedStatus === "completed")
            return "bg-feedback-green";
        if (normalizedStatus === "error")
            return "bg-feedback-red";
        if (normalizedStatus === "closed")
            return "bg-neutral-grey-50";
        if (normalizedStatus === "idle")
            return "bg-neutral-grey-10";
        if (normalizedStatus === "costlimitreached" ||
            normalizedStatus === "cost limit reached")
            return "bg-feedback-orange";
        return "bg-neutral-grey-50";
    };
    // Helper to get status label
    const getStatusLabel = (status) => {
        const normalizedStatus = status.toLowerCase();
        if (normalizedStatus === "running")
            return "Running";
        if (normalizedStatus === "waitingforapproval" ||
            normalizedStatus === "waiting for approval")
            return "Waiting for Approval";
        if (normalizedStatus === "completed")
            return "Completed";
        if (normalizedStatus === "error")
            return "Error";
        if (normalizedStatus === "closed")
            return "Closed";
        if (normalizedStatus === "idle")
            return "Idle";
        if (normalizedStatus === "costlimitreached" ||
            normalizedStatus === "cost limit reached")
            return "Cost Limit Reached";
        return status || "Unknown";
    };
    const handleAgentClick = (agentId) => {
        if (!agentId)
            return;
        // Dispatch event to switch to the spawned agent
        window.dispatchEvent(new CustomEvent("editor:openAgent", {
            detail: { agentId },
        }));
    };
    const bodyContent = (_jsx("div", { className: "max-h-64 overflow-y-auto px-4 pt-2 pb-3", children: _jsx("div", { className: "space-y-1.5", children: childAgents.map((agent, idx) => (_jsx("div", { className: "hover:bg-neutral-grey-5 cursor-pointer rounded bg-white p-2 text-[11px] transition-colors", onClick: () => handleAgentClick(agent.id), children: _jsxs("div", { className: "flex items-start gap-2", children: [_jsx("div", { className: "flex-shrink-0 pt-0.5", children: _jsx("div", { className: cn("h-2 w-2 rounded-full", getStatusColor(agent.status), agent.status.toLowerCase() === "running" && "animate-pulse"), title: getStatusLabel(agent.status) }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "text-neutral-grey-100 font-medium", children: agent.name }), agent.profileName && (_jsxs("span", { className: "text-neutral-grey-50 text-[10px]", children: ["(", agent.profileName, ")"] }))] }), agent.task && (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 line-clamp-1 text-[10px]", children: agent.task })), agent.spawnedAt &&
                                    (() => {
                                        try {
                                            const spawnedDate = new Date(agent.spawnedAt);
                                            if (!isNaN(spawnedDate.getTime())) {
                                                return (_jsxs("div", { className: "text-neutral-grey-50 mt-0.5 text-[10px]", children: ["Spawned ", _jsx(TimeWithTooltip, { date: spawnedDate })] }));
                                            }
                                        }
                                        catch (e) {
                                            // Invalid date, skip rendering timestamp
                                        }
                                        return null;
                                    })()] })] }) }, agent.id || `spawned-${idx}`))) }) }));
    if (headerless) {
        return _jsx("div", { className: "bg-neutral-grey-5", children: bodyContent });
    }
    return (_jsxs("div", { className: "border-border-default bg-neutral-grey-5 border-t", children: [_jsxs("button", { onClick: () => setIsExpanded(!isExpanded), className: "hover:bg-neutral-grey-5 flex w-full cursor-pointer items-center justify-between px-4 py-2 text-left transition-colors", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(GitBranch, { className: "text-neutral-grey-50 h-4 w-4", strokeWidth: 1 }), _jsx("span", { className: "text-neutral-grey-100 text-xs font-normal", children: "Spawned Agents" }), _jsx("span", { className: "text-neutral-grey-50 text-xs", children: childAgents.length })] }), isExpanded ? (_jsx(ChevronUp, { className: "text-neutral-grey-50 h-4 w-4", strokeWidth: 1 })) : (_jsx(ChevronDown, { className: "text-neutral-grey-50 h-4 w-4", strokeWidth: 1 }))] }), isExpanded && bodyContent] }));
}
//# sourceMappingURL=SpawnedAgentsPanel.js.map