import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useState, useRef, useEffect, useMemo } from "react";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { Plus, MoreVertical } from "lucide-react";
import { cn } from "../../lib/utils";
import { sanitizeSvg } from "../../lib/sanitize";
import { startViewTransition } from "../../lib/viewTransition";
import { getAgentStatusConfig } from "./AgentStatusBadge";
import { CloseButton } from "../../components/ui/close-button";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { getActiveAgents, closeAgent as closeAgentService, } from "../services/agentService";
import { isExecutingAgentStatus, isRunningAgentStatus, needsAgentAttention, parseAgentRunStatusData, parseAgentStatus, shouldIgnoreReplayRunStart, } from "../services/agentStatus";
import { toUserFacingAgentErrorMessage } from "../services/agentErrorMessage";
import { AgentTerminal } from "./AgentTerminal";
import { useEditContext } from "../client/editContext";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
// import { Button } from "../../components/ui/button";
import { loadAiProfiles } from "../services/aiService";
import { ChevronDown, List } from "lucide-react";
import { AgentProfileSelector } from "./AgentProfileSelector";
import { AgentsView } from "../../agents-view/AgentsView";
import { SecretAgentIcon } from "../ui/Icons";
import { Spinner } from "../ui/Spinner";
import { localStorageService } from "../services/localStorageService";
import { LicenseFeatures, useFeature } from "../../licensing";
// function convertAgentMessagesToTerminalMessages(
//   agentMessages: AgentChatMessage[],
// ): Message[] {
//   return agentMessages.map((msg) => ({
//     id: msg.id,
//     content: msg.content,
//     name: msg.name,
//     role: msg.role,
//     tool_calls: msg.functionName
//       ? [
//           {
//             id: msg.toolCallId || msg.id,
//             displayName: msg.functionName,
//             function: {
//               name: msg.functionName,
//               arguments: msg.functionArguments || "",
//             },
//           },
//         ]
//       : [],
//     tool_call_id: msg.toolCallId,
//   }));
// }
const ACTIVE_AGENT_STORAGE_KEY = "editor.activeAgentId";
const TASKBOARD_PROJECT_QUERY_KEY = "tbProjectId";
function AgentStatusIndicator({ status, label, size = "sm", }) {
    if (status === "running") {
        const dotClass = size === "md" ? "h-1.5 w-1.5" : "h-1 w-1";
        return (_jsxs("div", { className: "flex flex-shrink-0 items-center gap-0.5", title: label, "aria-label": label, children: [_jsx("div", { className: cn(dotClass, "bg-highlight-100 animate-bounce rounded-full [animation-delay:-0.3s]") }), _jsx("div", { className: cn(dotClass, "bg-highlight-100 animate-bounce rounded-full [animation-delay:-0.15s]") }), _jsx("div", { className: cn(dotClass, "bg-highlight-100 animate-bounce rounded-full") })] }));
    }
    const statusConfig = getAgentStatusConfig({ status });
    return (_jsx("div", { className: cn(size === "md" ? "h-2 w-2" : "h-1.5 w-1.5", "flex-shrink-0 rounded-full", statusConfig.color, statusConfig.shouldPulse && "animate-pulse"), title: label, "aria-label": label }));
}
const TASKBOARD_TASK_QUERY_KEY = "tbTaskId";
function readTaskboardLinkageFromUrl() {
    if (typeof window === "undefined") {
        return {};
    }
    const params = new URLSearchParams(window.location.search);
    const projectId = params.get(TASKBOARD_PROJECT_QUERY_KEY)?.trim() || "";
    const taskId = params.get(TASKBOARD_TASK_QUERY_KEY)?.trim() || "";
    return {
        projectId: projectId || undefined,
        taskId: taskId || undefined,
    };
}
export const Agents = React.memo(function Agents({ closeButton, }) {
    const [agents, setAgents] = useState([]);
    const [activeAgentId, setActiveAgentId] = useState(""); // "" = show profile selector, null = show overview, string = agent ID
    const activeAgentIdRef = useRef("");
    const singleAgentModeRef = useRef(false);
    const [profileTabDropdownOpen, setProfileTabDropdownOpen] = useState(null);
    const [menuPopoverOpen, setMenuPopoverOpen] = useState(false);
    const [loadingAgents, setLoadingAgents] = useState(false);
    const [inactiveAgents, setInactiveAgents] = useState([]);
    const [initialMetadataMap, setInitialMetadataMap] = useState({});
    const [availableProfiles, setAvailableProfiles] = useState([]);
    const [selectedProfileId, setSelectedProfileId] = useState("");
    const [loadingProfiles, setLoadingProfiles] = useState(false);
    const editContext = useEditContext();
    const canUseAi = useFeature(LicenseFeatures.AI);
    // Group agents by profile for profile-based tabs
    const agentsGroupedByProfile = useMemo(() => {
        const profileMap = new Map();
        agents.forEach((agent) => {
            const profileId = agent.profileId || null;
            const profileKey = profileId || "general";
            const profile = availableProfiles.find((p) => p.id === profileId);
            if (!profileMap.has(profileKey)) {
                profileMap.set(profileKey, {
                    profileId,
                    profileName: agent.profileName || "General",
                    profileSvgIcon: profile?.svgIcon,
                    agents: [],
                });
            }
            else {
                // Update icon if current group doesn't have one but this agent does
                const group = profileMap.get(profileKey);
                if (!group.profileSvgIcon && profile?.svgIcon) {
                    group.profileSvgIcon = profile?.svgIcon;
                }
            }
            profileMap.get(profileKey).agents.push(agent);
        });
        return profileMap;
    }, [agents, availableProfiles]);
    // Calculate inbox count (agents needing attention, excluding currently open agent)
    const inboxCount = useMemo(() => {
        return agents.filter((agent) => needsAgentAttention(agent.status) && agent.id !== activeAgentId).length;
    }, [agents, activeAgentId]);
    // Detect single-agent mode from query parameter once on mount
    useEffect(() => {
        try {
            const params = new URLSearchParams(window.location.search);
            const value = params.get("singleAgent");
            singleAgentModeRef.current =
                value === "true" || params.has("singleAgent");
        }
        catch { }
    }, []);
    // Helper function to get the most recently updated agent
    const getMostRecentAgent = (agentList) => {
        if (agentList.length === 0)
            return null;
        return agentList.reduce((mostRecent, current) => {
            return new Date(current.updatedDate) > new Date(mostRecent.updatedDate)
                ? current
                : mostRecent;
        });
    };
    // Helper function to get highest priority status for a group of agents
    const getHighestPriorityStatus = (agentList) => {
        const statusPriority = {
            waitingForApproval: 5,
            error: 4,
            running: 3,
            idle: 2,
            completed: 1,
            closed: 0,
            new: 0,
        };
        let highestPriority = -1;
        let highestStatus = "idle";
        agentList.forEach((agent) => {
            const statusKey = typeof agent.status === "string" ? agent.status : "idle";
            const priority = statusPriority[statusKey] ?? 0;
            if (priority > highestPriority) {
                highestPriority = priority;
                highestStatus = agent.status;
            }
        });
        return highestStatus;
    };
    // Helper function to set active agent and persist to localStorage.
    // Wrapped in startViewTransition so tab switches cross-fade instead of
    // flashing the empty terminal frame while messages load.
    const setActiveAgentIdWithStorage = (agentId) => {
        activeAgentIdRef.current = agentId;
        startViewTransition(() => {
            setActiveAgentId(agentId);
        });
        if (agentId) {
            localStorageService.setString(ACTIVE_AGENT_STORAGE_KEY, agentId);
        }
        else {
            localStorageService.removeItem(ACTIVE_AGENT_STORAGE_KEY);
        }
    };
    // Open an agent from history (or switch to it if already open)
    const openAgentFromHistory = React.useCallback(async (agent) => {
        if (!canUseAi) {
            return;
        }
        // Check if this agent is already open as a terminal
        // Use functional check pattern to get latest agents state
        let alreadyOpen = false;
        let foundAgentId = null;
        setAgents((currentAgents) => {
            const existingAgent = currentAgents.find((a) => a.id === agent.id);
            if (existingAgent) {
                alreadyOpen = true;
                foundAgentId = existingAgent.id;
                // Switch to existing agent
                setActiveAgentIdWithStorage(existingAgent.id);
            }
            return currentAgents; // No change
        });
        if (alreadyOpen) {
            return;
        }
        // If agent data is incomplete (e.g., only has ID), fetch full details from backend
        let fullAgent = agent;
        if (!agent.name || !agent.userId) {
            try {
                const { getAgent } = await import("../services/agentService");
                const agentDetails = await getAgent(agent.id);
                fullAgent = {
                    id: agentDetails.id,
                    name: agentDetails.name,
                    description: agentDetails.description,
                    userId: agentDetails.userId,
                    updatedDate: agentDetails.updatedDate,
                    status: agentDetails.status,
                    isShared: agentDetails.isShared,
                    ownerName: agentDetails.ownerName,
                    profileId: agentDetails.profileId,
                    profileName: agentDetails.profileName,
                    profileSvgIcon: agentDetails.profileSvgIcon,
                    messageCount: agentDetails.messageCount,
                    totalCost: agentDetails.totalCost,
                    totalTokensUsed: agentDetails.totalTokensUsed,
                    statusMessage: agentDetails.statusMessage,
                    lastMessageDate: agentDetails.lastMessageDate,
                };
            }
            catch (error) {
                console.error("Failed to fetch agent details:", error);
                // Fall back to using whatever data we have
            }
        }
        // Add the closed agent to the active agents list
        const reopenedAgent = {
            ...fullAgent,
            // Keep the original status to allow AgentTerminal to load the full agent data
        };
        setAgents((prev) => [...prev, reopenedAgent]);
        setActiveAgentIdWithStorage(reopenedAgent.id);
    }, [canUseAi]);
    // Load agents from backend on mount
    useEffect(() => {
        if (!canUseAi) {
            setAgents([]);
            setInactiveAgents([]);
            setAvailableProfiles([]);
            setActiveAgentId(null);
            activeAgentIdRef.current = null;
            setSelectedProfileId("");
            setLoadingAgents(false);
            setLoadingProfiles(false);
            localStorageService.removeItem(ACTIVE_AGENT_STORAGE_KEY);
            return;
        }
        loadAgentsFromBackend();
    }, [canUseAi]);
    // When no agents are present (empty state) or when switching to the profile selector,
    // keep selection state consistent without triggering extra fetches.
    useEffect(() => {
        // When showing empty state (no agents) or profile selector is active, force placeholder selection
        if (agents.length === 0 || activeAgentId === "") {
            setSelectedProfileId("");
        }
        else {
            // Otherwise preserve placeholder if not set yet
            setSelectedProfileId((prev) => prev || "");
        }
    }, [activeAgentId, agents.length]);
    // Function to reload profiles
    const reloadProfiles = React.useCallback(async () => {
        if (!canUseAi) {
            setAvailableProfiles([]);
            setLoadingProfiles(false);
            return;
        }
        try {
            setLoadingProfiles(true);
            const profiles = await loadAiProfiles(editContext?.currentItemDescriptor);
            setAvailableProfiles(profiles || []);
        }
        catch (e) {
            console.error("Failed to load AI profiles", e);
        }
        finally {
            setLoadingProfiles(false);
        }
    }, [canUseAi, editContext?.currentItemDescriptor]);
    // Ensure profiles are loaded once for terminals (centralized load)
    // Only load on mount - profiles are cached and will be reloaded via websocket when changed
    useEffect(() => {
        if (!canUseAi) {
            setAvailableProfiles([]);
            setLoadingProfiles(false);
            return;
        }
        let cancelled = false;
        (async () => {
            try {
                setLoadingProfiles(true);
                const profiles = await loadAiProfiles(editContext?.currentItemDescriptor);
                if (cancelled)
                    return;
                setAvailableProfiles(profiles || []);
            }
            catch (e) {
                console.error("Failed to load AI profiles", e);
            }
            finally {
                if (!cancelled)
                    setLoadingProfiles(false);
            }
        })();
        return () => {
            cancelled = true;
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [canUseAi]); // Only run on mount - profiles reload via websocket when changed
    // Listen for agent profile changes via websocket (when profiles are updated in Sitecore)
    useEffect(() => {
        if (!canUseAi || !editContext?.addSocketMessageListener)
            return;
        const removeListener = editContext.addSocketMessageListener((message) => {
            if (message.type === "agent-profiles-changed") {
                reloadProfiles();
            }
        });
        return () => {
            removeListener();
        };
    }, [canUseAi, editContext?.addSocketMessageListener, reloadProfiles]);
    // Listen for external requests to add a new agent (e.g., AI command)
    useEffect(() => {
        if (!canUseAi)
            return;
        const handleAddNewAgent = (ev) => {
            let initialMetadata = undefined;
            try {
                const ce = ev;
                initialMetadata = (ce.detail && ce.detail.metadata);
            }
            catch { }
            addAgent(initialMetadata);
            // Ensure the prompt focuses after the agent tab mounts
            setTimeout(() => {
                try {
                    window.dispatchEvent(new CustomEvent("editor:focusAgentPrompt"));
                }
                catch { }
            }, 60);
        };
        window.addEventListener("editor:addNewAgent", handleAddNewAgent);
        return () => window.removeEventListener("editor:addNewAgent", handleAddNewAgent);
    }, [canUseAi]);
    // Listen for external requests to select an existing open agent without switching views
    useEffect(() => {
        if (!canUseAi)
            return;
        const handleSelectAgent = (ev) => {
            try {
                const ce = ev;
                const agentId = (ce.detail && ce.detail.agentId);
                if (!agentId)
                    return;
                const existingAgent = agents.find((a) => a.id === agentId);
                if (existingAgent) {
                    setActiveAgentIdWithStorage(agentId);
                }
            }
            catch { }
        };
        window.addEventListener("editor:selectAgent", handleSelectAgent);
        return () => window.removeEventListener("editor:selectAgent", handleSelectAgent);
    }, [canUseAi, agents]);
    // Listen for external requests to open an existing agent
    useEffect(() => {
        if (!canUseAi)
            return;
        const handleOpenAgent = (ev) => {
            try {
                const ce = ev;
                const agentId = (ce.detail && ce.detail.agentId);
                if (!agentId)
                    return;
                // Load the agent from history (or switch to it if already open)
                // The openAgentFromHistory function handles both cases internally
                openAgentFromHistory({ id: agentId });
            }
            catch (error) {
                console.error("Error opening agent:", error);
            }
        };
        window.addEventListener("editor:openAgent", handleOpenAgent);
        return () => window.removeEventListener("editor:openAgent", handleOpenAgent);
    }, [canUseAi, openAgentFromHistory]);
    // Listen for external requests to create a new agent with a specific profile
    useEffect(() => {
        if (!canUseAi)
            return;
        const handleCreateAgentWithProfile = (ev) => {
            try {
                const ce = ev;
                const profile = (ce.detail && ce.detail.profile);
                if (!profile)
                    return;
                // Build additionalData with preconfigured todos if available
                const additionalData = {
                    profileId: profile.id,
                    profileName: profile.name,
                };
                // Add preconfigured todos as todoList if the profile has them
                const preconfiguredTodos = profile.preconfiguredTodos;
                if (preconfiguredTodos && preconfiguredTodos.length > 0) {
                    additionalData.todoList = {
                        title: "Preconfigured Tasks",
                        items: preconfiguredTodos.map((todo) => ({
                            id: todo.id || crypto.randomUUID(),
                            title: todo.title,
                            status: "pending",
                            instructions: todo.instructions,
                            agentProfileId: todo.agentProfileId,
                        })),
                    };
                }
                // Create metadata with profile info
                const metadata = {
                    profile: profile.name,
                    additionalData,
                };
                // Create a new agent with the profile
                const newAgent = {
                    status: "new",
                    id: crypto.randomUUID(),
                    name: profile.agentName || profile.displayTitle || profile.name,
                    updatedDate: new Date().toISOString(),
                    userId: "",
                    profileId: profile.id,
                    profileName: profile.name,
                    profileSvgIcon: profile.svgIcon,
                };
                setAgents((prev) => [...prev, newAgent]);
                setActiveAgentIdWithStorage(newAgent.id);
                setInitialMetadataMap((prev) => ({ ...prev, [newAgent.id]: metadata }));
                // Focus the prompt after the agent tab mounts
                setTimeout(() => {
                    try {
                        window.dispatchEvent(new CustomEvent("editor:focusAgentPrompt"));
                    }
                    catch { }
                }, 60);
            }
            catch (error) {
                console.error("Error creating agent with profile:", error);
            }
        };
        window.addEventListener("editor:createAgentWithProfile", handleCreateAgentWithProfile);
        return () => window.removeEventListener("editor:createAgentWithProfile", handleCreateAgentWithProfile);
    }, [canUseAi]);
    // Subscribe to websocket messages for agent events
    useEffect(() => {
        if (!canUseAi || !editContext?.addSocketMessageListener)
            return;
        const unsubscribe = editContext.addSocketMessageListener((message) => {
            // In single-agent mode, ignore events that would add or remove agents,
            // but still allow updates (e.g., name/status) for the current tab.
            if (singleAgentModeRef.current) {
                if (message.type === "agent:run:start" ||
                    message.type === "agent:run:closed") {
                    return;
                }
            }
            if (message.type === "agent:run:start") {
                const payload = message.payload || {};
                const agentId = payload.agentId;
                const agentName = payload.agentName;
                const autoSelect = payload.autoSelect;
                const profileId = payload.profileId;
                const profileName = payload.profileName;
                const timestamp = payload.timestamp;
                if (!agentId || !agentName) {
                    console.warn("Invalid agent:run:start message payload:", message.payload);
                    return;
                }
                setAgents((prevAgents) => {
                    // Check if agent already exists
                    const existingAgentIndex = prevAgents.findIndex((agent) => agent.id === agentId);
                    if (existingAgentIndex !== -1) {
                        // Update existing agent name and profile info
                        const updatedAgents = [...prevAgents];
                        const existingAgent = updatedAgents[existingAgentIndex];
                        if (shouldIgnoreReplayRunStart(existingAgent.status, existingAgent.updatedDate, typeof timestamp === "string" ? timestamp : undefined)) {
                            return prevAgents;
                        }
                        updatedAgents[existingAgentIndex] = {
                            ...existingAgent,
                            name: agentName,
                            status: "running",
                            updatedDate: new Date().toISOString(),
                            ...(profileId && { profileId }),
                            ...(profileName && { profileName }),
                        };
                        return updatedAgents;
                    }
                    else {
                        // Add new agent to the array
                        const newAgent = {
                            id: agentId,
                            name: agentName,
                            status: "running",
                            userId: "", // Will be populated from backend if needed
                            updatedDate: new Date().toISOString(),
                            ...(profileId && { profileId }),
                            ...(profileName && { profileName }),
                        };
                        return [...prevAgents, newAgent];
                    }
                });
                // Auto-switch to the spawned agent if requested
                if (autoSelect === true) {
                    setActiveAgentIdWithStorage(agentId);
                }
            }
            else if (message.type === "agent:info:updated") {
                const payload = message.payload || {};
                const agentId = payload.agentId;
                const agentName = payload.agentName;
                const agentDescription = payload.agentDescription;
                if (!agentId)
                    return;
                // Update the agent name and/or description in the tabs list
                setAgents((prevAgents) => {
                    const existingIndex = prevAgents.findIndex((a) => a.id === agentId);
                    if (existingIndex === -1)
                        return prevAgents;
                    const updatedAgents = [...prevAgents];
                    const existingAgent = updatedAgents[existingIndex];
                    updatedAgents[existingIndex] = {
                        ...existingAgent,
                        ...(agentName !== undefined && { name: agentName }),
                        ...(agentDescription !== undefined && {
                            description: agentDescription,
                        }),
                        updatedDate: new Date().toISOString(),
                    };
                    return updatedAgents;
                });
            }
            else if (message.type === "agent:run:status") {
                // Unified status updates (state only)
                const payload = message.payload || {};
                const agentId = payload.agentId;
                const data = payload.data;
                if (!agentId)
                    return;
                const status = parseAgentRunStatusData(data);
                if (!status)
                    return;
                setAgents((prevAgents) => {
                    const existingIndex = prevAgents.findIndex((a) => a.id === agentId);
                    if (existingIndex !== -1) {
                        const updatedAgents = [...prevAgents];
                        const existingAgent = updatedAgents[existingIndex];
                        updatedAgents[existingIndex] = {
                            ...existingAgent,
                            status,
                            updatedDate: new Date().toISOString(),
                        };
                        return updatedAgents;
                    }
                    return prevAgents;
                });
            }
            else if (message.type === "agent:run:closed") {
                // Remove agent from tabs when closed in another browser instance
                const { agentId } = message.payload || {};
                if (!agentId)
                    return;
                setAgents((prevAgents) => {
                    const filtered = prevAgents.filter((a) => a.id !== agentId);
                    // Find the closed agent to add to history
                    const closedAgent = prevAgents.find((a) => a.id === agentId);
                    if (closedAgent) {
                        // Add to inactive agents list (history) if it doesn't already exist
                        setInactiveAgents((prevInactive) => {
                            const alreadyExists = prevInactive.some((a) => a.id === agentId);
                            if (alreadyExists) {
                                return prevInactive;
                            }
                            return [
                                {
                                    ...closedAgent,
                                    status: "closed",
                                    updatedDate: new Date().toISOString(),
                                },
                                ...prevInactive,
                            ];
                        });
                    }
                    // If we're closing the active agent, switch to the most recent remaining one
                    if (activeAgentIdRef.current === agentId) {
                        if (filtered.length > 0) {
                            const mostRecentAgent = getMostRecentAgent(filtered);
                            setActiveAgentIdWithStorage(mostRecentAgent?.id || null);
                        }
                        else {
                            // No agents left, show profile selector
                            setActiveAgentId("");
                            activeAgentIdRef.current = "";
                            localStorageService.removeItem(ACTIVE_AGENT_STORAGE_KEY);
                        }
                    }
                    // If no agents remain, reset profile selection to placeholder
                    if (filtered.length === 0) {
                        setSelectedProfileId("");
                    }
                    return filtered;
                });
            }
            else if (message.type === "agent:profile:switched") {
                // Handle profile switch initiated by the agent (via switch-profile function)
                const payload = message.payload || {};
                const agentId = payload.agentId;
                const newProfileId = payload.newProfileId;
                const newProfileName = payload.newProfileName;
                if (!agentId || !newProfileId)
                    return;
                // Find the profile's icon from available profiles
                const newProfile = availableProfiles.find((p) => p.id.toLowerCase() === newProfileId?.toLowerCase());
                setAgents((prevAgents) => {
                    const existingIndex = prevAgents.findIndex((a) => a.id === agentId);
                    if (existingIndex === -1)
                        return prevAgents;
                    const updatedAgents = [...prevAgents];
                    const existingAgent = updatedAgents[existingIndex];
                    updatedAgents[existingIndex] = {
                        ...existingAgent,
                        profileId: newProfileId,
                        profileName: newProfileName,
                        profileSvgIcon: newProfile?.svgIcon,
                        updatedDate: new Date().toISOString(),
                    };
                    return updatedAgents;
                });
            }
        });
        return unsubscribe;
    }, [canUseAi, editContext?.addSocketMessageListener, availableProfiles]);
    const loadAgentsFromBackend = async () => {
        try {
            if (!canUseAi) {
                setAgents([]);
                setInactiveAgents([]);
                setLoadingAgents(false);
                return;
            }
            // In single-agent mode, skip loading any pre-existing/open agents or history
            if (singleAgentModeRef.current) {
                setAgents([]);
                setInactiveAgents([]);
                // In single-agent mode, start with profile selector (empty string) instead of overview (null)
                setActiveAgentId("");
                activeAgentIdRef.current = "";
                localStorage.removeItem(ACTIVE_AGENT_STORAGE_KEY);
                setLoadingAgents(false);
                return;
            }
            setLoadingAgents(true);
            // Load active agents (exclude shared agents for the agent panel)
            const activeAgentsResponse = await getActiveAgents({
                limit: 1000,
                includeShared: false, // Agent panel only shows user's own agents
                includeOwned: true,
                excludeClosed: true, // Exclude closed and cancelled agents
            });
            const activeAgentsResult = activeAgentsResponse.agents;
            // Merge the backend agents with any locally added "new" agents that haven't been saved yet
            setAgents((prev) => {
                const newAgents = prev.filter((a) => a.status === "new");
                // Avoid duplicates if any new agents were already saved and returned in activeAgentsResult
                const backendIds = new Set(activeAgentsResult.map((a) => a.id));
                const filteredNewAgents = newAgents.filter((a) => !backendIds.has(a.id));
                return [...activeAgentsResult, ...filteredNewAgents];
            });
            // Try to restore the previously active agent from localStorage if one exists
            let selectedAgentId = null;
            if (activeAgentsResult.length > 0) {
                const storedAgentId = localStorageService.getString(ACTIVE_AGENT_STORAGE_KEY);
                const storedAgent = activeAgentsResult.find((agent) => agent.id === storedAgentId);
                if (storedAgent) {
                    selectedAgentId = storedAgent.id;
                }
                else {
                    // If no stored agent or stored agent not found, select the most recent agent
                    const mostRecentAgent = getMostRecentAgent(activeAgentsResult);
                    selectedAgentId = mostRecentAgent?.id || null;
                }
            }
            // If there are no active agents after load, set to empty string to show profile selector
            if (activeAgentsResult.length === 0) {
                // Only if no new agent was added in the meantime
                setAgents((prev) => {
                    if (prev.length === 0) {
                        setActiveAgentId("");
                        activeAgentIdRef.current = "";
                        localStorage.removeItem(ACTIVE_AGENT_STORAGE_KEY);
                        setSelectedProfileId("");
                    }
                    return prev;
                });
            }
            else {
                // Only restore from backend/storage if no new agent is currently active
                // This prevents overwriting a newly created agent from a comment (especially on mobile)
                const currentActiveId = activeAgentIdRef.current;
                setAgents((prev) => {
                    const isNewAgentActive = prev.some((a) => a.id === currentActiveId && a.status === "new");
                    if (!isNewAgentActive) {
                        setActiveAgentIdWithStorage(selectedAgentId);
                    }
                    return prev;
                });
            }
        }
        catch (error) {
            console.error("Failed to load agents:", error);
        }
        finally {
            setLoadingAgents(false);
        }
    };
    // const loadAgentMessages = async (
    //   agentId: string,
    // ): Promise<AgentChat | null> => {
    //   try {
    //     const result = await getAgent(agentId);
    //     if (result.type === "success" && result.data) {
    //       return result.data;
    //     }
    //   } catch (error) {
    //     console.error(`Failed to load messages for agent ${agentId}:`, error);
    //   }
    //   return null;
    // };
    const addAgent = (metadata) => {
        if (!canUseAi) {
            return;
        }
        const newAgent = {
            status: "new",
            id: crypto.randomUUID(),
            name: `New Agent`,
            updatedDate: new Date().toISOString(),
            userId: "",
            profileId: metadata?.additionalData?.profileId,
            profileName: metadata?.additionalData?.profileName || metadata?.profile,
        };
        setAgents((prev) => [...prev, newAgent]);
        // User-initiated creation should activate the new agent tab
        setActiveAgentIdWithStorage(newAgent.id);
        if (metadata) {
            setInitialMetadataMap((prev) => ({ ...prev, [newAgent.id]: metadata }));
        }
        // Ensure the prompt focuses after the agent tab mounts
        setTimeout(() => {
            try {
                window.dispatchEvent(new CustomEvent("editor:focusAgentPrompt"));
            }
            catch { }
        }, 60);
    };
    const createAgentWithSelectedProfile = (profileId) => {
        const selected = availableProfiles.find((p) => p.id === profileId);
        const taskboardLinkage = readTaskboardLinkageFromUrl();
        // Build additionalData with preconfigured todos if available
        // Backend uses [PreserveNames] so check both camelCase and PascalCase
        const additionalData = selected
            ? {
                profileId: selected.id,
                profileName: selected.name,
                ...(taskboardLinkage.projectId
                    ? { projectId: taskboardLinkage.projectId }
                    : {}),
                ...(taskboardLinkage.taskId
                    ? { taskId: taskboardLinkage.taskId }
                    : {}),
            }
            : {};
        const preconfiguredTodos = selected?.preconfiguredTodos;
        if (preconfiguredTodos && preconfiguredTodos.length > 0) {
            additionalData.todoList = {
                title: "Preconfigured Tasks",
                items: preconfiguredTodos.map((todo) => ({
                    id: todo.id || crypto.randomUUID(),
                    title: todo.title,
                    status: "pending",
                    instructions: todo.instructions,
                    agentProfileId: todo.agentProfileId,
                })),
            };
        }
        const metadata = selected
            ? {
                profile: selected.name,
                additionalData,
            }
            : undefined;
        addAgent(metadata);
    };
    const handleAgentUpdate = React.useCallback((agentId, updates) => {
        setAgents((prev) => prev.map((agent) => agent.id === agentId ? { ...agent, ...updates } : agent));
    }, []);
    const closeAgent = async (agentId) => {
        try {
            // Permanently close the agent in the backend
            await closeAgentService(agentId);
        }
        catch (error) {
            console.error("Failed to close agent:", error);
            // Continue with UI cleanup even if backend call fails
        }
        setAgents((prev) => {
            const filtered = prev.filter((a) => a.id !== agentId);
            // Find the closed agent to add to history
            const closedAgent = prev.find((a) => a.id === agentId);
            if (closedAgent) {
                // Add the closed agent to the inactive agents list (history) if it doesn't already exist
                setInactiveAgents((prevInactive) => {
                    // Check if this agent is already in the history
                    const alreadyExists = prevInactive.some((a) => a.id === agentId);
                    if (alreadyExists) {
                        return prevInactive;
                    }
                    return [
                        {
                            ...closedAgent,
                            status: "closed",
                            updatedDate: new Date().toISOString(),
                        },
                        ...prevInactive,
                    ];
                });
            }
            // If we're closing the active terminal, switch to the most recent remaining one or show profile selector
            if (activeAgentIdRef.current === agentId) {
                if (filtered.length > 0) {
                    const mostRecentAgent = getMostRecentAgent(filtered);
                    setActiveAgentIdWithStorage(mostRecentAgent?.id || null);
                }
                else {
                    // No agents left, show profile selector
                    setActiveAgentId("");
                    activeAgentIdRef.current = "";
                    localStorage.removeItem(ACTIVE_AGENT_STORAGE_KEY);
                }
            }
            // If no agents remain, reset profile selection to placeholder
            if (filtered.length === 0) {
                setSelectedProfileId("");
            }
            return filtered;
        });
    };
    const handleCloseAgent = (agentId, e) => {
        e.stopPropagation();
        // Find the agent to check its status
        const agent = agents.find((a) => a.id === agentId);
        if (!agent) {
            // Agent not found, close anyway
            closeAgent(agentId);
            return;
        }
        const isActivelyRunning = agent.status === "running" || agent.status === "waitingForApproval";
        // If agent is actively running, show confirmation dialog
        if (isActivelyRunning) {
            if (editContext?.confirm) {
                editContext.confirm({
                    header: "Abort Agent",
                    message: "This agent is currently running. Are you sure you want to abort it?",
                    acceptLabel: "Abort Agent",
                    accept: () => {
                        closeAgent(agentId);
                    },
                    showCancel: true,
                });
            }
        }
        else {
            // Agent is not actively running, close immediately
            closeAgent(agentId);
        }
    };
    const handleCloseProfileAgents = async (profileAgents, profileName, e) => {
        e.stopPropagation();
        const agentCount = profileAgents.length;
        const hasActiveAgents = profileAgents.some((agent) => isExecutingAgentStatus(agent.status));
        if (editContext?.confirm) {
            editContext.confirm({
                header: `Close ${agentCount} Agent${agentCount > 1 ? "s" : ""}`,
                message: hasActiveAgents
                    ? `This will close all ${agentCount} ${profileName} agent${agentCount > 1 ? "s" : ""}, including ${profileAgents.filter((a) => isRunningAgentStatus(a.status)).length} running agent(s). Are you sure?`
                    : `Are you sure you want to close all ${agentCount} ${profileName} agent${agentCount > 1 ? "s" : ""}?`,
                acceptLabel: `Close ${agentCount > 1 ? "All" : "Agent"}`,
                accept: async () => {
                    // Close all agents in this profile
                    const closePromises = profileAgents.map((agent) => closeAgentService(agent.id).catch((error) => {
                        console.error(`Failed to close agent ${agent.id}:`, error);
                    }));
                    await Promise.all(closePromises);
                    // Update UI state
                    setAgents((prev) => {
                        const agentIds = new Set(profileAgents.map((a) => a.id));
                        const filtered = prev.filter((a) => !agentIds.has(a.id));
                        // Add closed agents to history
                        const closedAgents = profileAgents.map((agent) => ({
                            ...agent,
                            status: "closed",
                            updatedDate: new Date().toISOString(),
                        }));
                        setInactiveAgents((prevInactive) => {
                            const newAgents = closedAgents.filter((closedAgent) => !prevInactive.some((a) => a.id === closedAgent.id));
                            return [...newAgents, ...prevInactive];
                        });
                        // If we're closing the active agent, switch to most recent remaining or show profile selector
                        if (activeAgentIdRef.current &&
                            agentIds.has(activeAgentIdRef.current)) {
                            if (filtered.length > 0) {
                                const mostRecentAgent = getMostRecentAgent(filtered);
                                setActiveAgentIdWithStorage(mostRecentAgent?.id || null);
                            }
                            else {
                                // No agents left, show profile selector
                                setActiveAgentId("");
                                activeAgentIdRef.current = "";
                                localStorageService.removeItem(ACTIVE_AGENT_STORAGE_KEY);
                            }
                        }
                        // Reset profile selection if no agents remain
                        if (filtered.length === 0) {
                            setSelectedProfileId("");
                        }
                        return filtered;
                    });
                },
                showCancel: true,
            });
        }
    };
    const closeOtherAgents = async () => {
        if (!activeAgentIdRef.current)
            return;
        // Get agents to close (all except active)
        const agentsToClose = agents.filter((a) => a.id !== activeAgentIdRef.current);
        // Permanently close each agent in the backend
        const closePromises = agentsToClose.map(async (agent) => {
            try {
                await closeAgentService(agent.id);
            }
            catch (error) {
                console.error(`Failed to close agent ${agent.id}:`, error);
            }
        });
        // Wait for all close operations to complete
        await Promise.all(closePromises);
        // Add closed agents to history (deduplicate to prevent duplicates)
        if (agentsToClose.length > 0) {
            const closedAgents = agentsToClose.map((agent) => ({
                ...agent,
                status: "closed",
                updatedDate: new Date().toISOString(),
            }));
            setInactiveAgents((prevInactive) => {
                // Filter out agents that already exist in history
                const newAgents = closedAgents.filter((closedAgent) => !prevInactive.some((a) => a.id === closedAgent.id));
                return [...newAgents, ...prevInactive];
            });
        }
        setAgents((prev) => {
            return prev.filter((a) => a.id === activeAgentIdRef.current);
        });
        setMenuPopoverOpen(false);
    };
    const getTabsMenuItems = () => {
        return [
            {
                id: "close-other",
                label: "Close Other",
                command: async () => {
                    await closeOtherAgents();
                },
                disabled: agents.length <= 1,
            },
        ];
    };
    if (!canUseAi) {
        return (_jsx("div", { className: "text-neutral-grey-50 flex h-full items-center justify-center p-4 text-center text-sm", children: "AI features are unavailable with the current license." }));
    }
    if (loadingAgents) {
        return (_jsxs("div", { className: "flex h-full items-center justify-center gap-2", children: [_jsx(Spinner, { size: "sm" }), _jsx("div", { className: "text-neutral-grey-50 text-xs", children: "Loading agents..." })] }));
    }
    // Empty state when no agents are open
    if (!loadingAgents && agents.length === 0) {
        const showingOverview = activeAgentId === null;
        return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsxs("div", { className: "border-border-default flex items-center border-b bg-[color-mix(in_srgb,var(--color-neutral-grey-5)_45%,var(--color-white))]", children: [_jsx("div", { className: "flex-1" }), _jsxs("div", { className: "flex items-center gap-2", children: [showingOverview ? (
                                /* Show Overview as an active tab when displaying overview - clickable to toggle back */
                                _jsx("div", { className: "flex items-center px-1", children: _jsxs("div", { onClick: (e) => {
                                            console.log("[Agents Empty State] Overview tab clicked, toggling back to profile selector", e);
                                            setActiveAgentId("");
                                            activeAgentIdRef.current = "";
                                            localStorageService.removeItem(ACTIVE_AGENT_STORAGE_KEY);
                                        }, className: cn("border-border-default flex h-8 min-w-0 cursor-pointer items-center gap-2 border-r px-2 text-xs", "hover:bg-neutral-grey-5 border-b-white bg-white"), children: [_jsxs("div", { className: "relative", children: [_jsx(List, { className: "text-neutral-grey-50 size-4 flex-shrink-0", strokeWidth: 1 }), inboxCount > 0 && (_jsx("span", { className: "bg-feedback-orange absolute -top-1.5 -right-1.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full px-1 text-[9px] font-bold text-white", children: inboxCount > 9 ? "9+" : inboxCount }))] }), _jsx("span", { className: "truncate font-medium", children: "Overview" })] }) })) : (
                                /* Show Overview as a button when displaying profile selector */
                                _jsx("div", { className: "flex items-center px-1", children: _jsx(SimpleIconButton, { onClick: (e) => {
                                            console.log("[Agents Empty State] Overview button clicked", e);
                                            setActiveAgentIdWithStorage(null);
                                        }, icon: _jsxs("div", { className: "relative", children: [_jsx(List, { className: "size-4", strokeWidth: 1 }), inboxCount > 0 && (_jsx("span", { className: "bg-feedback-orange absolute -top-1.5 -right-1.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full px-1 text-[9px] font-bold text-white", children: inboxCount > 9 ? "9+" : inboxCount }))] }), label: `Agent Overview${inboxCount > 0 ? ` (${inboxCount} need attention)` : ""}`, className: "text-neutral-grey-50 hover:text-neutral-grey-100 h-8" }) })), _jsxs(Popover, { open: menuPopoverOpen, onOpenChange: (open) => {
                                        console.log("[Agents Empty State] Menu popover onOpenChange:", open);
                                        setMenuPopoverOpen(open);
                                    }, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(SimpleIconButton, { onClick: (e) => {
                                                    setMenuPopoverOpen(!menuPopoverOpen);
                                                }, icon: _jsx(MoreVertical, { className: "size-4", strokeWidth: 1 }), label: "Menu", className: "text-neutral-grey-50 hover:text-neutral-grey-100", showTooltip: false }) }), _jsx(PopoverContent, { className: "w-48 p-0", align: "end", children: _jsx("div", { className: "py-1", children: getTabsMenuItems().map((item) => item.separator ? (_jsx("div", { className: "bg-border-default my-1 h-px" }, item.id)) : (_jsx("button", { onClick: async (e) => {
                                                        if (item.command)
                                                            await item.command(e);
                                                        setMenuPopoverOpen(false);
                                                    }, disabled: !!item.disabled, className: "hover:bg-neutral-grey-5 disabled:text-neutral-grey-50 w-full px-3 py-2 text-left text-xs disabled:cursor-not-allowed", children: item.label }, item.id))) }) })] }), closeButton && (_jsx("div", { className: "flex items-center", children: closeButton }))] })] }), showingOverview ? (_jsx("div", { className: "relative flex-1", children: _jsx("div", { className: "absolute inset-0", children: _jsx(AgentsView, {}) }) })) : (_jsx("div", { className: "flex flex-1 items-start justify-center overflow-y-auto p-3", children: _jsx("div", { className: "w-full max-w-5xl", children: _jsx(AgentProfileSelector, { profiles: availableProfiles, onSelectProfile: createAgentWithSelectedProfile, loading: loadingProfiles }) }) }))] }));
    }
    return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsxs("div", { className: "border-border-default flex items-center border-b bg-[color-mix(in_srgb,var(--color-neutral-grey-5)_45%,var(--color-white))]", children: [_jsxs("div", { className: "flex min-w-0 flex-1 overflow-hidden", children: [activeAgentId === "" && agents.length > 0 && (_jsxs("div", { className: cn("border-border-default flex min-w-0 cursor-default items-center gap-2 overflow-hidden border-r p-2 text-xs", "border-b-white bg-white"), children: [_jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-2 overflow-hidden", children: [_jsx("div", { className: "flex-shrink-0", children: _jsx(Plus, { size: 18, strokeWidth: 1, className: "text-neutral-grey-50" }) }), _jsx("span", { className: "text-neutral-grey-100 min-w-0 truncate font-medium", children: "New Agent" })] }), _jsx(CloseButton, { onClick: (e) => {
                                            e.stopPropagation();
                                            // Switch back to the most recent agent if we cancel "New Agent"
                                            const mostRecent = getMostRecentAgent(agents);
                                            setActiveAgentIdWithStorage(mostRecent?.id || null);
                                        }, label: "Cancel", className: "flex-shrink-0 opacity-60 hover:opacity-100", showTooltip: false })] })), Array.from(agentsGroupedByProfile.values()).map((profileGroup) => {
                                const profileKey = profileGroup.profileId || "general";
                                const activeAgent = profileGroup.agents.find((a) => a.id === activeAgentId);
                                const isActive = !!activeAgent;
                                const agentCount = profileGroup.agents.length;
                                const singleAgent = agentCount === 1 ? profileGroup.agents[0] : null;
                                const highestStatus = getHighestPriorityStatus(profileGroup.agents);
                                const statusConfig = getAgentStatusConfig({
                                    status: highestStatus,
                                });
                                const singleAgentErrorMessage = toUserFacingAgentErrorMessage(singleAgent?.statusMessage) ||
                                    singleAgent?.statusMessage;
                                const activeAgentErrorMessage = toUserFacingAgentErrorMessage(activeAgent?.statusMessage) ||
                                    activeAgent?.statusMessage;
                                // Use agent name if: single agent OR active agent from this profile
                                const displayName = activeAgent
                                    ? activeAgent.name
                                    : singleAgent
                                        ? singleAgent.name
                                        : profileGroup.profileName;
                                // Always use profile group icon since all agents in the group share the same profile
                                const displayIcon = profileGroup.profileSvgIcon;
                                // For data-agent-id: prioritize singleAgent, then activeAgent
                                // This ensures a single agent always has its ID on the tab
                                const tabAgentId = singleAgent?.id || activeAgent?.id || "";
                                return (_jsx("div", { className: "min-w-0 shrink", "data-active": isActive ? "true" : "false", "data-agent-id": tabAgentId, children: _jsxs(Popover, { open: profileTabDropdownOpen === profileKey, onOpenChange: (open) => {
                                            setProfileTabDropdownOpen(open ? profileKey : null);
                                            if (open) {
                                                setMenuPopoverOpen(false);
                                            }
                                        }, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs("div", { className: cn("border-border-default flex min-w-0 cursor-pointer items-center gap-2 overflow-hidden border-r p-2 text-xs", isActive
                                                        ? "border-b-white bg-white"
                                                        : "hover:bg-neutral-grey-5"), onClick: () => {
                                                        if (singleAgent) {
                                                            // Single agent: switch directly
                                                            setActiveAgentIdWithStorage(singleAgent.id);
                                                        }
                                                        // Multiple agents: popover will open via PopoverTrigger
                                                    }, children: [_jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-2 overflow-hidden", children: [_jsx("div", { className: "flex-shrink-0", children: displayIcon ? (_jsx("div", { className: "text-neutral-grey-50 flex h-[18px] w-[18px] items-center justify-center [&>svg]:h-full [&>svg]:w-full", dangerouslySetInnerHTML: {
                                                                            __html: sanitizeSvg(displayIcon),
                                                                        } })) : (_jsx(SecretAgentIcon, { size: 18, strokeWidth: 1, className: "text-neutral-grey-50" })) }), _jsx("span", { className: "min-w-0 flex-1 truncate font-medium", children: displayName }), agentCount > 1 && (_jsx("div", { className: "bg-neutral-grey-10 badge-pad-sm text-neutral-grey-100 flex-shrink-0 rounded-full text-[10px] leading-none font-medium", children: agentCount })), _jsxs(Tooltip, { delayDuration: 1000, children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("div", { className: "flex flex-shrink-0 items-center", title: statusConfig.label, children: _jsx(AgentStatusIndicator, { status: highestStatus, label: statusConfig.label }) }) }), _jsx(TooltipContent, { children: _jsxs("div", { children: [_jsx("div", { children: statusConfig.label }), singleAgent?.status === "error" ? (singleAgentErrorMessage ? (_jsx("div", { className: "text-feedback-red mt-1 text-xs", children: singleAgentErrorMessage })) : null) : activeAgent?.status === "error" ? (activeAgentErrorMessage ? (_jsx("div", { className: "text-feedback-red mt-1 text-xs", children: activeAgentErrorMessage })) : null) : null] }) })] }), agentCount > 1 && (_jsx(ChevronDown, { className: "text-neutral-grey-50 size-3 flex-shrink-0", strokeWidth: 1 }))] }), _jsx(CloseButton, { onClick: (e) => singleAgent
                                                                ? handleCloseAgent(singleAgent.id, e)
                                                                : handleCloseProfileAgents(profileGroup.agents, profileGroup.profileName, e), label: agentCount > 1
                                                                ? `Close all ${agentCount} agents`
                                                                : "Close", className: "flex-shrink-0 opacity-60 hover:opacity-100", showTooltip: false })] }) }), agentCount > 1 && (_jsxs(PopoverContent, { className: "w-80 p-0", align: "start", children: [_jsxs("div", { className: "border-border-default text-neutral-grey-50 border-b px-3 py-2 text-xs font-medium", children: [profileGroup.profileName, " Agents"] }), _jsx("div", { className: "max-h-64 overflow-y-auto", children: profileGroup.agents.map((agent) => {
                                                            const agentStatusConfig = getAgentStatusConfig(agent);
                                                            const agentErrorMessage = toUserFacingAgentErrorMessage(agent.statusMessage) || agent.statusMessage;
                                                            return (_jsx("div", { "data-agent-id": agent.id, className: cn("border-border-default hover:bg-neutral-grey-5 cursor-pointer border-b px-3 py-2", activeAgentId === agent.id &&
                                                                    "bg-highlight-10/50"), onClick: () => {
                                                                    setActiveAgentIdWithStorage(agent.id);
                                                                    setProfileTabDropdownOpen(null);
                                                                }, children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(AgentStatusIndicator, { status: agent.status, label: agentStatusConfig.label, size: "md" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-neutral-grey-100 truncate text-xs font-medium", children: agent.name }), _jsx("div", { className: "text-neutral-grey-50 font-mono text-[9px]", children: agent.id }), agent.status === "error" ? (agentErrorMessage ? (_jsx("div", { className: "text-feedback-red truncate text-[11px] leading-tight", children: agentErrorMessage })) : (agent.description && (_jsx("div", { className: "text-neutral-grey-50 truncate text-[11px] leading-tight", children: agent.description })))) : (agent.description && (_jsx("div", { className: "text-neutral-grey-50 truncate text-[11px] leading-tight", children: agent.description })))] }), _jsx(CloseButton, { onClick: (e) => handleCloseAgent(agent.id, e), label: "Close", className: "opacity-60 hover:opacity-100" })] }) }, agent.id));
                                                        }) })] }))] }) }, profileKey));
                            })] }), activeAgentId !== null && (_jsx("div", { className: "flex items-center px-1", children: _jsx(SimpleIconButton, { onClick: () => setActiveAgentIdWithStorage(null), icon: _jsxs("div", { className: "relative", children: [_jsx(List, { className: "size-4", strokeWidth: 1 }), inboxCount > 0 && (_jsx("span", { className: "bg-feedback-orange absolute -top-1.5 -right-1.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full px-1 text-[9px] font-bold text-white", children: inboxCount > 9 ? "9+" : inboxCount }))] }), label: `Agent Overview${inboxCount > 0 ? ` (${inboxCount} need attention)` : ""}`, className: "text-neutral-grey-50 hover:text-neutral-grey-100" }) })), activeAgentId === null && (_jsx("div", { className: "flex items-center px-1", children: _jsxs("div", { className: cn("border-border-default flex min-w-0 cursor-default items-center gap-2 border-r p-2 text-xs", "border-b-white bg-white"), children: [_jsxs("div", { className: "relative", children: [_jsx(List, { className: "text-neutral-grey-50 size-4 flex-shrink-0", strokeWidth: 1 }), inboxCount > 0 && (_jsx("span", { className: "bg-feedback-orange absolute -top-1.5 -right-1.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full px-1 text-[9px] font-bold text-white", children: inboxCount > 9 ? "9+" : inboxCount }))] }), _jsx("span", { className: "truncate font-medium", children: "Overview" })] }) })), agents.length > 0 && (_jsx("div", { className: "flex items-center px-1", children: _jsxs(Popover, { open: menuPopoverOpen, onOpenChange: (open) => {
                                setMenuPopoverOpen(open);
                                if (open) {
                                    setProfileTabDropdownOpen(null);
                                }
                            }, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(SimpleIconButton, { onClick: (e) => {
                                            setMenuPopoverOpen(!menuPopoverOpen);
                                            if (!menuPopoverOpen) {
                                                setProfileTabDropdownOpen(null);
                                            }
                                        }, icon: _jsx(MoreVertical, { className: "size-4", strokeWidth: 1 }), label: "Menu", className: "text-neutral-grey-50 hover:text-neutral-grey-100", showTooltip: false }) }), _jsx(PopoverContent, { className: "w-48 p-0", align: "end", children: _jsx("div", { className: "py-1", children: getTabsMenuItems().map((item) => item.separator ? (_jsx("div", { className: "bg-border-default my-1 h-px" }, item.id)) : (_jsx("button", { onClick: async (e) => {
                                                if (item.command)
                                                    await item.command(e);
                                                setMenuPopoverOpen(false);
                                            }, disabled: !!item.disabled, className: "hover:bg-neutral-grey-5 disabled:text-neutral-grey-50 w-full px-3 py-2 text-left text-xs disabled:cursor-not-allowed", children: item.label }, item.id))) }) })] }) })), _jsx("div", { className: "flex items-center px-1", children: _jsx(SimpleIconButton, { onClick: () => {
                                setActiveAgentId("");
                                activeAgentIdRef.current = "";
                                localStorage.removeItem(ACTIVE_AGENT_STORAGE_KEY);
                            }, icon: _jsx(Plus, { className: "size-4", strokeWidth: 1 }), label: agents.length === 0 ? "Create Agent" : "Add Agent", className: cn("text-neutral-grey-50 hover:text-neutral-grey-100", activeAgentId === "" && "bg-highlight-10 text-highlight-100"), showTooltip: false, "data-testid": "add-agent-button" }) }), closeButton && (_jsx("div", { className: "flex items-center px-2", children: closeButton }))] }), _jsx("div", { className: "relative flex-1", children: (() => {
                    const shouldKeepMounted = (agent) => {
                        const parsedStatus = parseAgentStatus(agent.status);
                        return (agent.id === activeAgentId ||
                            isExecutingAgentStatus(parsedStatus) ||
                            parsedStatus === "waitingForInput" ||
                            parsedStatus === "costLimitReached");
                    };
                    const mountedAgents = agents.filter(shouldKeepMounted);
                    return (_jsxs(_Fragment, { children: [mountedAgents.map((agent) => {
                                const isSelected = agent.id === activeAgentId;
                                const parsedStatus = parseAgentStatus(agent.status);
                                const keepStreaming = isSelected ||
                                    isExecutingAgentStatus(parsedStatus) ||
                                    parsedStatus === "waitingForInput" ||
                                    parsedStatus === "costLimitReached";
                                return (_jsx("div", { className: cn("absolute inset-0", !isSelected && "hidden"), style: isSelected
                                        ? { viewTransitionName: "agents-tab-pane" }
                                        : undefined, children: _jsx(AgentTerminal, { agentStub: agent, initialMetadata: initialMetadataMap[agent.id], profiles: availableProfiles, onReloadProfiles: reloadProfiles, isActive: isSelected, isVisible: keepStreaming, isFocused: isSelected, onAgentUpdate: (updates) => handleAgentUpdate(agent.id, updates) }) }, agent.id));
                            }), activeAgentId === null ? (
                            // Show AgentsView when no agent is selected
                            _jsx("div", { className: "absolute inset-0", children: _jsx(AgentsView, {}) })) : activeAgentId === "" ? (
                            // Show Profile Selector when activeAgentId is ""
                            _jsx("div", { className: "absolute inset-0 flex items-start justify-center overflow-y-auto p-2", children: _jsx("div", { className: "w-full max-w-5xl", children: _jsx(AgentProfileSelector, { profiles: availableProfiles, onSelectProfile: createAgentWithSelectedProfile, loading: loadingProfiles }) }) })) : null] }));
                })() })] }));
});
//# sourceMappingURL=Agents.js.map