import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useMemo, useCallback } from "react";
import { sanitizeSvg } from "../lib/sanitize";
import { getAgentsGrouped, getClosedAgentsByProfile, cancelAgent, closeAgent, deleteAgent, } from "../editor/services/agentService";
import { isRunningAgentStatus, parseAgentRunStatusData, shouldIgnoreReplayRunStart, } from "../editor/services/agentStatus";
import { cn } from "../lib/utils";
import { RefreshCw, List, Layers, Square } from "lucide-react";
import { SimpleIconButton } from "../editor/ui/SimpleIconButton";
import { FilterInput } from "../components/FilterInput";
import { PageHeader } from "../components/PageHeader";
import { useEditContext } from "../editor/client/editContext";
import { AgentCard } from "./AgentCard";
import { ProfileAgentsGroup } from "./ProfileAgentsGroup";
import { Checkbox } from "../components/ui/checkbox";
import { SimpleTabs } from "../editor/ui/SimpleTabs";
import { AgentsInbox, agentNeedsAttention } from "./AgentsInbox";
import { CreateAgentView } from "./CreateAgentView";
import { SecretAgentIcon } from "../editor/ui/Icons";
import { Spinner } from "../editor/ui/Spinner";
/**
 * Agents overview view with tab-based navigation:
 * - Inbox: Agents requiring user attention
 * - All Agents: Active and closed agents with search/filter
 * - Create New: Profile selection to start a new agent
 */
const SECTION_TO_INDEX = {
    inbox: 0,
    all: 1,
    create: 2,
};
const SECTION_LABELS = {
    inbox: "Inbox",
    all: "All Agents",
    create: "Create New",
};
export function AgentsView({ onSelectAgent, selectedAgentId, compact = false, activeSection: controlledSection, onInboxCountChange, } = {}) {
    const getAgentSortDate = useCallback((agent) => agent.lastMessageDate || agent.updatedDate, []);
    const sortAgentsByRecentActivity = useCallback((agents) => [...agents].sort((a, b) => new Date(getAgentSortDate(b)).getTime() -
        new Date(getAgentSortDate(a)).getTime()), [getAgentSortDate]);
    const sortProfileGroupsAgents = useCallback((groups) => groups.map((group) => ({
        ...group,
        agents: sortAgentsByRecentActivity(group.agents),
    })), [sortAgentsByRecentActivity]);
    const editContext = useEditContext();
    const [internalTabIndex, setInternalTabIndex] = useState(1);
    const activeTabIndex = controlledSection !== undefined
        ? SECTION_TO_INDEX[controlledSection]
        : internalTabIndex;
    const setActiveTabIndex = (index) => {
        if (controlledSection === undefined)
            setInternalTabIndex(index);
    };
    const [activeAgents, setActiveAgents] = useState([]);
    const [profileGroups, setProfileGroups] = useState([]);
    const [expandedProfiles, setExpandedProfiles] = useState(new Set());
    const [loadingMoreForProfile, setLoadingMoreForProfile] = useState(null);
    const [loading, setLoading] = useState(true);
    const [initialLoad, setInitialLoad] = useState(true);
    const [error, setError] = useState(null);
    const [refreshing, setRefreshing] = useState(false);
    const [stoppingAgentIds, setStoppingAgentIds] = useState(new Set());
    const [searchTerm, setSearchTerm] = useState("");
    const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");
    const [showOnlyMyAgents, setShowOnlyMyAgents] = useState(false);
    const [historyViewMode, setHistoryViewMode] = useState("grouped");
    // Debounce search term
    useEffect(() => {
        const timer = setTimeout(() => {
            setDebouncedSearchTerm(searchTerm);
        }, 400);
        return () => clearTimeout(timer);
    }, [searchTerm]);
    const loadAgents = useCallback(async () => {
        try {
            setLoading(true);
            setError(null);
            const response = await getAgentsGrouped(debouncedSearchTerm || undefined, !showOnlyMyAgents, // includeShared
            true);
            setActiveAgents(sortAgentsByRecentActivity(response.activeAgents));
            setProfileGroups(sortProfileGroupsAgents(response.closedAgentsByProfile));
        }
        catch (err) {
            console.error("Failed to load agents:", err);
            setError(err?.message || "Failed to load agents. Please try again later.");
        }
        finally {
            setLoading(false);
            setRefreshing(false);
            setInitialLoad(false);
        }
    }, [
        debouncedSearchTerm,
        showOnlyMyAgents,
        sortAgentsByRecentActivity,
        sortProfileGroupsAgents,
    ]);
    // Initial load and reload when filters change
    useEffect(() => {
        loadAgents();
    }, [loadAgents]);
    // Subscribe to websocket messages for real-time agent updates
    useEffect(() => {
        if (!editContext?.addSocketMessageListener)
            return;
        const unsubscribe = editContext.addSocketMessageListener((message) => {
            if (message.type === "agent:run:start") {
                const { agentId, agentName, timestamp } = message.payload;
                if (!agentId || !agentName) {
                    console.warn("Invalid agent:run:start message payload:", message.payload);
                    return;
                }
                // Update or add agent in active agents list
                setActiveAgents((prevAgents) => {
                    const existingAgentIndex = prevAgents.findIndex((agent) => agent.id === agentId);
                    if (existingAgentIndex !== -1) {
                        // Update existing agent
                        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(),
                        };
                        return updatedAgents;
                    }
                    else {
                        // Agent not found - reload to get full details
                        loadAgents();
                        return prevAgents;
                    }
                });
            }
            else if (message.type === "agent:info:updated") {
                const { agentId, agentName, agentDescription } = message.payload || {};
                if (!agentId)
                    return;
                // Update agent in active agents list
                setActiveAgents((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:closed") {
                // Reload agents when one is closed - it should move to closed section
                loadAgents();
            }
            else if (message.type === "agent:run:status") {
                const { agentId, data } = message.payload || {};
                if (!agentId || !data)
                    return;
                const mappedStatus = parseAgentRunStatusData(data);
                if (!mappedStatus)
                    return;
                setActiveAgents((prevAgents) => {
                    const existingIndex = prevAgents.findIndex((a) => a.id === agentId);
                    if (existingIndex === -1)
                        return prevAgents;
                    const updatedAgents = [...prevAgents];
                    const existingAgent = updatedAgents[existingIndex];
                    updatedAgents[existingIndex] = {
                        ...existingAgent,
                        status: mappedStatus,
                        statusMessage: data.statusMessage || existingAgent.statusMessage,
                        updatedDate: new Date().toISOString(),
                    };
                    return updatedAgents;
                });
            }
            else if (message.type === "agent:run:complete" ||
                message.type === "agent:run:error") {
                // Reload to update status when agent completes or errors
                loadAgents();
            }
        });
        return unsubscribe;
    }, [editContext?.addSocketMessageListener, loadAgents]);
    // Calculate inbox count from active agents
    const inboxCount = useMemo(() => {
        return activeAgents.filter(agentNeedsAttention).length;
    }, [activeAgents]);
    // Report inbox count to parent for sidebar badge
    useEffect(() => {
        onInboxCountChange?.(inboxCount);
    }, [inboxCount, onInboxCountChange]);
    // Sort active agents by most recent activity (newest first)
    const sortedActiveAgents = useMemo(() => {
        return sortAgentsByRecentActivity(activeAgents);
    }, [activeAgents, sortAgentsByRecentActivity]);
    // Calculate running agents (agents that are currently executing)
    // Excludes agents waiting for tool call approval - they're shown in inbox
    const runningAgents = useMemo(() => {
        return sortedActiveAgents.filter((agent) => isRunningAgentStatus(agent.status));
    }, [sortedActiveAgents]);
    const handleRefresh = async () => {
        setRefreshing(true);
        await loadAgents();
    };
    const handleStopAgent = useCallback(async (agentId, agentName) => {
        setStoppingAgentIds((prev) => {
            const next = new Set(prev);
            next.add(agentId);
            return next;
        });
        try {
            await cancelAgent(agentId);
            setActiveAgents((prevAgents) => prevAgents.map((agent) => agent.id === agentId
                ? {
                    ...agent,
                    status: "idle",
                    updatedDate: new Date().toISOString(),
                }
                : agent));
            await loadAgents();
        }
        catch (err) {
            console.error("Failed to stop agent:", err);
            editContext?.showToast(`Failed to stop ${agentName}: ${err?.message || "Unknown error"}`);
        }
        finally {
            setStoppingAgentIds((prev) => {
                const next = new Set(prev);
                next.delete(agentId);
                return next;
            });
        }
    }, [activeAgents, editContext, loadAgents, runningAgents]);
    const handleStopAllRunning = useCallback(async () => {
        if (runningAgents.length === 0)
            return;
        const runningIds = runningAgents.map((agent) => agent.id);
        const runningNames = new Map(runningAgents.map((agent) => [agent.id, agent.name]));
        setStoppingAgentIds((prev) => {
            const next = new Set(prev);
            runningIds.forEach((id) => next.add(id));
            return next;
        });
        try {
            const results = await Promise.allSettled(runningIds.map((agentId) => cancelAgent(agentId)));
            const failedIds = results
                .map((result, index) => ({ result, agentId: runningIds[index] }))
                .filter((entry) => entry.result.status === "rejected")
                .map((entry) => entry.agentId);
            if (failedIds.length < runningIds.length) {
                const stoppedIds = new Set(runningIds.filter((id) => !failedIds.includes(id)));
                setActiveAgents((prevAgents) => prevAgents.map((agent) => stoppedIds.has(agent.id)
                    ? {
                        ...agent,
                        status: "idle",
                        updatedDate: new Date().toISOString(),
                    }
                    : agent));
            }
            if (failedIds.length > 0) {
                const failedNames = failedIds
                    .map((id) => runningNames.get(id) || id)
                    .join(", ");
                editContext?.showToast(`Failed to stop: ${failedNames}`);
            }
            await loadAgents();
        }
        catch (err) {
            console.error("Failed to stop running agents:", err);
            editContext?.showToast(`Failed to stop running agents: ${err?.message || "Unknown error"}`);
        }
        finally {
            setStoppingAgentIds((prev) => {
                const next = new Set(prev);
                runningIds.forEach((id) => next.delete(id));
                return next;
            });
        }
    }, [editContext, loadAgents, runningAgents]);
    const handleToggleProfile = (profileId) => {
        const key = profileId || "null";
        setExpandedProfiles((prev) => {
            const newSet = new Set(prev);
            if (newSet.has(key)) {
                newSet.delete(key);
            }
            else {
                newSet.add(key);
            }
            return newSet;
        });
    };
    const handleLoadMoreForProfile = async (profileId) => {
        if (!profileId || loadingMoreForProfile)
            return;
        try {
            setLoadingMoreForProfile(profileId);
            // Find the current profile group
            const profileGroup = profileGroups.find((g) => g.profileId === profileId);
            if (!profileGroup)
                return;
            const currentCount = profileGroup.agents.length;
            // Load more agents for this profile
            const response = await getClosedAgentsByProfile(profileId, currentCount, 10, debouncedSearchTerm || undefined);
            // Update the profile group with new agents
            setProfileGroups((prevGroups) => prevGroups.map((group) => {
                if (group.profileId === profileId) {
                    return {
                        ...group,
                        agents: sortAgentsByRecentActivity([
                            ...group.agents,
                            ...response.agents,
                        ]),
                    };
                }
                return group;
            }));
        }
        catch (err) {
            console.error("Failed to load more agents:", err);
            editContext?.showToast(`Failed to load more agents: ${err?.message || "Unknown error"}`);
        }
        finally {
            setLoadingMoreForProfile(null);
        }
    };
    const handleOpenAgent = (agent) => {
        // If onSelectAgent callback is provided, use it directly
        if (onSelectAgent) {
            onSelectAgent(agent);
            return;
        }
        // Ensure agents panel is visible, but don't switch views
        editContext?.setShowAgentsPanel?.(true);
        // Delay briefly for any UI updates, then dispatch event to open existing agent
        setTimeout(() => {
            window.dispatchEvent(new CustomEvent("editor:openAgent", {
                detail: { agentId: agent.id },
            }));
        }, 100);
    };
    const handleCloseAgent = async (agentId, agentName) => {
        // Find the agent to check its status
        const agent = activeAgents.find((a) => a.id === agentId);
        const isRunning = isRunningAgentStatus(agent?.status);
        const doClose = async () => {
            try {
                await closeAgent(agentId);
                // Reload to move agent from active to closed section
                loadAgents();
            }
            catch (err) {
                console.error("Failed to close agent:", err);
                editContext?.showToast(`Failed to close agent: ${err?.message || "Unknown error"}`);
            }
        };
        // Only confirm if agent is running
        if (isRunning) {
            editContext?.confirm({
                header: "Close Agent",
                message: `Are you sure you want to close "${agentName}"? This will stop its execution.`,
                acceptLabel: "Close Agent",
                accept: doClose,
                showCancel: true,
            });
        }
        else {
            // Close immediately without confirmation
            await doClose();
        }
    };
    const handleCloseAllInbox = () => {
        const inboxAgents = activeAgents.filter(agentNeedsAttention);
        if (inboxAgents.length === 0)
            return;
        const runningAgents = inboxAgents.filter((a) => isRunningAgentStatus(a.status));
        const doCloseAll = async () => {
            try {
                await Promise.all(inboxAgents.map((agent) => closeAgent(agent.id)));
                loadAgents();
            }
            catch (err) {
                console.error("Failed to close all agents:", err);
                editContext?.showToast(`Failed to close some agents: ${err?.message || "Unknown error"}`);
            }
        };
        // Confirm if any agents are running
        if (runningAgents.length > 0) {
            editContext?.confirm({
                header: "Close All Agents",
                message: `Are you sure you want to close all ${inboxAgents.length} agents in your inbox? ${runningAgents.length} running agent${runningAgents.length !== 1 ? "s" : ""} will be stopped.`,
                acceptLabel: "Close All",
                accept: doCloseAll,
                showCancel: true,
            });
        }
        else {
            doCloseAll();
        }
    };
    const handleDeleteAgent = async (agentId, agentName, event) => {
        event.stopPropagation();
        editContext?.confirm({
            header: "Delete Agent",
            message: `Are you sure you want to permanently delete "${agentName}"?`,
            acceptLabel: "Delete Agent",
            accept: async () => {
                try {
                    await deleteAgent(agentId);
                    // Remove from both active and closed lists
                    setActiveAgents((prev) => prev.filter((a) => a.id !== agentId));
                    setProfileGroups((prevGroups) => prevGroups.map((group) => ({
                        ...group,
                        agents: group.agents.filter((a) => a.id !== agentId),
                        totalClosedCount: Math.max(0, group.totalClosedCount - 1),
                    })));
                }
                catch (err) {
                    console.error("Failed to delete agent:", err);
                    editContext?.showToast(`Failed to delete agent: ${err?.message || "Unknown error"}`);
                }
            },
            showCancel: true,
        });
    };
    const handleAgentClick = (agent) => {
        // If onSelectAgent callback is provided, use it directly
        if (onSelectAgent) {
            onSelectAgent(agent);
            return;
        }
        // Otherwise, dispatch event for the agents panel
        window.dispatchEvent(new CustomEvent("editor:selectAgent", {
            detail: { agentId: agent.id },
        }));
    };
    const handleCreateAgent = (profile) => {
        const agentDisplayName = profile.agentName || profile.displayTitle || profile.name;
        const agentId = crypto.randomUUID();
        const newAgent = {
            status: "new",
            id: agentId,
            name: agentDisplayName,
            updatedDate: new Date().toISOString(),
            userId: "",
            profileId: profile.id,
            profileName: profile.name,
            profileSvgIcon: profile.svgIcon,
        };
        // If onSelectAgent callback is provided (workspace mode), use it directly
        if (onSelectAgent) {
            onSelectAgent(newAgent);
            return;
        }
        // Otherwise, open the agents panel with the new agent via event
        editContext?.setShowAgentsPanel?.(true);
        setTimeout(() => {
            window.dispatchEvent(new CustomEvent("editor:createAgentWithProfile", {
                detail: { agent: newAgent, profile },
            }));
        }, 100);
    };
    const formatDateTime = (dateString) => {
        try {
            const date = new Date(dateString);
            return date.toLocaleString();
        }
        catch {
            return dateString;
        }
    };
    const totalActiveCount = activeAgents.length;
    const totalClosedCount = profileGroups.reduce((sum, group) => sum + group.totalClosedCount, 0);
    const isStoppingAllRunning = runningAgents.length > 0 &&
        runningAgents.every((agent) => stoppingAgentIds.has(agent.id));
    // Flatten all closed agents from all profile groups and sort by date (newest first)
    const flatClosedAgents = useMemo(() => {
        const allAgents = [];
        profileGroups.forEach((group) => {
            allAgents.push(...group.agents);
        });
        // Sort by lastMessageDate if available, otherwise by updatedDate (newest first)
        return allAgents.sort((a, b) => new Date(getAgentSortDate(b)).getTime() -
            new Date(getAgentSortDate(a)).getTime());
    }, [profileGroups, getAgentSortDate]);
    const currentSection = controlledSection ??
        (activeTabIndex === 0 ? "inbox" : activeTabIndex === 1 ? "all" : "create");
    const pageHeaderDescription = useMemo(() => {
        if (selectedAgentId) {
            const fromActive = activeAgents.find((agent) => agent.id === selectedAgentId);
            if (fromActive?.name)
                return fromActive.name;
            for (const group of profileGroups) {
                const agent = group.agents.find((agent) => agent.id === selectedAgentId);
                if (agent?.name)
                    return agent.name;
            }
        }
        return SECTION_LABELS[currentSection];
    }, [selectedAgentId, activeAgents, profileGroups, currentSection]);
    // Show full-screen loading only on initial load (skip for "create" – that view loads its own data)
    if (initialLoad && loading && currentSection !== "create") {
        return (_jsxs("div", { className: "flex h-full items-center justify-center gap-2", children: [_jsx(Spinner, { size: "sm" }), _jsx("div", { className: "text-sm text-gray-500", children: "Loading agents..." })] }));
    }
    return (_jsxs("div", { className: "absolute inset-0 flex flex-col bg-[#fcfcfc]", children: [!compact && (_jsx(PageHeader, { icon: _jsx(SecretAgentIcon, { size: 28, strokeWidth: 1.5 }), title: "AI Agents", description: pageHeaderDescription, variant: "compact" })), runningAgents.length > 0 && (_jsxs("div", { className: "shrink-0 border-b border-gray-100 bg-white px-4 pt-3 pb-2", children: [_jsxs("div", { className: "mb-2 flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-2 text-emerald-600", children: [_jsx(Spinner, { size: "xs" }), _jsxs("span", { className: "text-xs font-semibold tracking-wide text-emerald-700", children: [runningAgents.length, " running"] })] }), _jsxs("button", { onClick: () => void handleStopAllRunning(), disabled: isStoppingAllRunning, className: "flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-[11px] font-medium text-gray-500 transition-colors hover:bg-red-50 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-60", children: [isStoppingAllRunning ? (_jsx(Spinner, { size: "sm" })) : (_jsx(Square, { className: "size-3 fill-current", strokeWidth: 2 })), _jsx("span", { children: "Stop All" })] })] }), _jsx("div", { className: "max-h-[200px] overflow-y-auto", children: _jsx("div", { className: "flex flex-col gap-px", children: runningAgents.map((agent) => {
                                const isSelected = selectedAgentId === agent.id;
                                const isStopping = stoppingAgentIds.has(agent.id);
                                return (_jsxs("div", { className: cn("group flex items-center gap-2 rounded-md px-2 py-1.5 transition-colors", isSelected
                                        ? "bg-emerald-100/80 text-emerald-800"
                                        : "text-gray-700 hover:bg-gray-50"), children: [_jsxs("button", { onClick: () => handleAgentClick(agent), className: "flex min-w-0 flex-1 items-center gap-2 text-xs", children: [agent.profileSvgIcon ? (_jsx("div", { className: "h-4 w-4 shrink-0 opacity-60 [&>svg]:h-full [&>svg]:w-full", dangerouslySetInnerHTML: {
                                                        __html: sanitizeSvg(agent.profileSvgIcon),
                                                    } })) : (_jsx(SecretAgentIcon, { size: 14, strokeWidth: 1.5, className: "shrink-0 opacity-60" })), _jsx("span", { className: "flex-1 truncate text-left font-medium", children: agent.name })] }), _jsx("button", { onClick: (event) => {
                                                event.stopPropagation();
                                                void handleStopAgent(agent.id, agent.name);
                                            }, disabled: isStopping, title: "Stop agent", className: "flex shrink-0 items-center justify-center rounded p-1 text-gray-400 opacity-0 transition-all group-hover:opacity-100 hover:bg-red-50 hover:text-red-500 disabled:cursor-not-allowed disabled:opacity-60", children: isStopping ? (_jsx(Spinner, { size: "sm" })) : (_jsx(Square, { className: "size-3 fill-current", strokeWidth: 2 })) })] }, agent.id));
                            }) }) })] })), controlledSection === undefined && (_jsx("div", { className: "shrink-0 border-b border-gray-100 bg-white px-6 shadow-[0_1px_2px_rgba(0,0,0,0.03)]", children: _jsx(SimpleTabs, { tabs: [
                        {
                            id: "inbox",
                            label: inboxCount > 0 ? `Inbox (${inboxCount})` : "Inbox",
                            content: null,
                            testId: "agents-tab-inbox",
                        },
                        {
                            id: "all",
                            label: "All Agents",
                            content: null,
                            testId: "agents-tab-all",
                        },
                        {
                            id: "create",
                            label: "Create New",
                            content: null,
                            testId: "agents-tab-create",
                        },
                    ], activeTab: activeTabIndex, setActiveTab: setActiveTabIndex, hideContent: true, variant: "elegant", className: "gap-6" }) })), _jsxs("div", { className: "relative flex-1 overflow-hidden", children: [activeTabIndex === 0 && (_jsx("div", { className: "absolute inset-0 overflow-y-auto", children: _jsx(AgentsInbox, { agents: activeAgents, onOpenAgent: handleOpenAgent, onDismissAgent: handleCloseAgent, onCloseAll: handleCloseAllInbox, formatDateTime: formatDateTime, loading: loading && initialLoad, selectedAgentId: selectedAgentId }) })), activeTabIndex === 1 && (_jsxs("div", { className: "absolute inset-0 flex flex-col", children: [_jsxs("div", { className: "shrink-0 border-b border-gray-100 bg-white p-6", children: [_jsxs("div", { className: "mb-4 flex items-center justify-between", children: [_jsxs("div", { children: [_jsx("h2", { className: "text-lg font-semibold tracking-tight text-gray-900", children: "Agent History" }), _jsxs("p", { className: "text-[13px] text-gray-500", children: [totalActiveCount, " active, ", totalClosedCount, " closed agents"] })] }), _jsx(SimpleIconButton, { onClick: handleRefresh, icon: _jsx(RefreshCw, { className: cn("size-4 text-gray-400", refreshing && "animate-spin"), strokeWidth: 2 }), label: "Refresh list", disabled: refreshing, className: "h-9 w-9 rounded-full bg-gray-50 shadow-sm transition-colors hover:bg-gray-100" })] }), _jsxs("div", { className: "flex flex-col gap-4 sm:flex-row sm:items-center", children: [_jsx("div", { className: "flex-1", children: _jsx(FilterInput, { value: searchTerm, onChange: setSearchTerm, placeholder: "Search by name, description, or agent ID (GUID)...", loading: loading && !initialLoad, size: "md", className: "border-gray-100 shadow-sm focus-within:border-gray-300" }) }), _jsxs("div", { className: "flex items-center gap-2", children: [profileGroups.length > 0 && (_jsxs("div", { className: "flex items-center gap-1 rounded-lg border border-gray-100 bg-gray-50/50 p-1", children: [_jsxs("button", { onClick: () => setHistoryViewMode("grouped"), className: cn("flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-[12px] font-medium transition-colors", historyViewMode === "grouped"
                                                                    ? "bg-white text-gray-900 shadow-sm"
                                                                    : "text-gray-600 hover:text-gray-900"), title: "Grouped by profile", children: [_jsx(Layers, { className: "size-3.5", strokeWidth: 2 }), _jsx("span", { children: "Grouped" })] }), _jsxs("button", { onClick: () => setHistoryViewMode("flat"), className: cn("flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-[12px] font-medium transition-colors", historyViewMode === "flat"
                                                                    ? "bg-white text-gray-900 shadow-sm"
                                                                    : "text-gray-600 hover:text-gray-900"), title: "Flat list (newest first)", children: [_jsx(List, { className: "size-3.5", strokeWidth: 2 }), _jsx("span", { children: "Flat" })] })] })), _jsxs("label", { className: "flex cursor-pointer items-center gap-2.5 rounded-lg border border-gray-100 bg-gray-50/50 px-3 py-2 text-sm transition-colors hover:bg-gray-100", children: [_jsx(Checkbox, { checked: showOnlyMyAgents, onCheckedChange: (checked) => setShowOnlyMyAgents(checked === true), className: "border-gray-300 data-[state=checked]:border-black data-[state=checked]:bg-black" }), _jsx("span", { className: "text-[13px] font-medium text-gray-700 select-none", children: "My agents only" })] })] })] })] }), _jsxs("div", { className: "relative flex-1 overflow-y-auto", children: [loading && !initialLoad && (_jsx("div", { className: "absolute top-2 left-1/2 z-10 -translate-x-1/2 rounded-md bg-white px-3 py-1.5 shadow-md", children: _jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-600", children: [_jsx(RefreshCw, { className: "size-3 animate-spin", strokeWidth: 1 }), _jsx("span", { children: "Loading..." })] }) })), error ? (_jsx("div", { className: "flex h-full items-center justify-center", children: _jsxs("div", { className: "max-w-md text-center", children: [_jsx("div", { className: "mb-4 text-sm text-red-600", children: error }), _jsx("button", { onClick: handleRefresh, className: "rounded bg-blue-500 px-4 py-2 text-xs text-white hover:bg-blue-600", children: "Retry" })] }) })) : totalActiveCount === 0 &&
                                        totalClosedCount === 0 &&
                                        !loading ? (_jsx("div", { className: "flex h-full items-center justify-center text-sm text-gray-500", children: searchTerm.trim()
                                            ? "No agents match your search"
                                            : "No agents found" })) : (_jsxs("div", { className: cn("space-y-4 p-4", loading && "opacity-60"), children: [activeAgents.length > 0 && (_jsxs("div", { className: "space-y-2", children: [_jsx("h3", { className: "text-sm font-semibold text-gray-700", children: "Active Agents" }), sortedActiveAgents.map((agent) => (_jsx(AgentCard, { agent: agent, onClick: handleAgentClick, onResume: handleOpenAgent, onClose: handleCloseAgent, onDelete: handleDeleteAgent, formatDateTime: formatDateTime, selected: selectedAgentId === agent.id }, agent.id)))] })), profileGroups.length > 0 && (_jsxs("div", { className: "space-y-2", children: [_jsx("h3", { className: "text-sm font-semibold text-gray-700", children: "History" }), historyViewMode === "grouped" ? (
                                                    // Grouped by profile view
                                                    profileGroups.map((profileGroup) => {
                                                        const profileKey = profileGroup.profileId || "null";
                                                        const isExpanded = expandedProfiles.has(profileKey);
                                                        const isLoadingMore = loadingMoreForProfile === profileGroup.profileId;
                                                        const hasMore = profileGroup.agents.length <
                                                            profileGroup.totalClosedCount;
                                                        return (_jsx(ProfileAgentsGroup, { profileGroup: profileGroup, isExpanded: isExpanded, isLoadingMore: isLoadingMore, hasMore: hasMore, onToggle: () => handleToggleProfile(profileGroup.profileId), onLoadMore: () => handleLoadMoreForProfile(profileGroup.profileId), onAgentClick: handleAgentClick, onResumeAgent: handleOpenAgent, onCloseAgent: handleCloseAgent, onDeleteAgent: handleDeleteAgent, formatDateTime: formatDateTime, selectedAgentId: selectedAgentId }, profileKey));
                                                    })) : (
                                                    // Flat list view (newest first)
                                                    _jsx("div", { className: "space-y-3", children: flatClosedAgents.map((agent) => (_jsx(AgentCard, { agent: agent, onClick: handleAgentClick, onResume: handleOpenAgent, onClose: handleCloseAgent, onDelete: handleDeleteAgent, formatDateTime: formatDateTime, selected: selectedAgentId === agent.id }, agent.id))) }))] }))] }))] })] })), activeTabIndex === 2 && (_jsx("div", { className: "absolute inset-0 overflow-y-auto bg-white p-2", children: _jsx(CreateAgentView, { onCreateAgent: handleCreateAgent }) }))] })] }));
}
//# sourceMappingURL=AgentsView.js.map