import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useMemo, useRef, useCallback, } from "react";
import { AgentsView } from "./AgentsView";
import { AgentsSidebar, ACTIVE_AGENT_PREFIX } from "./AgentsSidebar";
import { AgentTerminal } from "../editor/ai/AgentTerminal";
import { SingleEditView } from "../editor/views/SingleEditView";
import { EditorSlotContextProvider } from "../editor/views/editorSlotContext";
import { useEditContext } from "../editor/client/editContext";
import { getAgent, getAgentsGrouped, } from "../editor/services/agentService";
import { parseAgentRunStatusData } from "../editor/services/agentStatus";
import { loadAiProfiles } from "../editor/services/aiService";
import { SecretAgentIcon } from "../editor/ui/Icons";
import { Spinner } from "../editor/ui/Spinner";
import { PageHeader } from "../components/PageHeader";
import { SimpleTabs } from "../editor/ui/SimpleTabs";
import { Splitter } from "../editor/ui/Splitter";
import { Menu } from "lucide-react";
import { cn } from "../lib/utils";
import { startViewTransition } from "../lib/viewTransition";
/**
 * AgentsWorkspaceView - Desktop: Splitter (AgentsView | AgentTerminal | SingleEditView).
 * Mobile: Sidebar + content (Agents group with Inbox/All/Create + active agents; content switches by selection).
 */
export function AgentsWorkspaceView() {
    const editContext = useEditContext();
    const shouldAutoShowMobileEditorRef = useRef(typeof window !== "undefined" &&
        window.matchMedia("(max-width: 767px)").matches);
    const [activeAgents, setActiveAgents] = useState([]);
    const [selectedAgentId, setSelectedAgentId] = useState(null);
    const [profiles, setProfiles] = useState([]);
    const [loadingAgent, setLoadingAgent] = useState(false);
    const [activeSidebarKey, setActiveSidebarKey] = useState("inbox");
    const [activeAgentTab, setActiveAgentTab] = useState("chat");
    const [inboxCount, setInboxCount] = useState(0);
    const isInitialUrlLoad = useRef(true);
    const skipNextUrlUpdate = useRef(false);
    const selectedAgentIdRef = useRef(null);
    useEffect(() => {
        selectedAgentIdRef.current = selectedAgentId;
    }, [selectedAgentId]);
    const selectedAgent = selectedAgentId != null
        ? (activeAgents.find((agent) => agent.id === selectedAgentId) ?? null)
        : null;
    useEffect(() => {
        editContext?.setSelectedAgentsWorkspaceAgentId(selectedAgentId);
    }, [editContext, selectedAgentId]);
    useEffect(() => {
        return () => {
            editContext?.setSelectedAgentsWorkspaceAgentId(null);
        };
    }, [editContext]);
    const getIsDesktop = () => typeof window !== "undefined" &&
        window.matchMedia("(min-width: 768px)").matches;
    const [isDesktop, setIsDesktop] = useState(() => getIsDesktop());
    const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
    useEffect(() => {
        if (typeof window === "undefined")
            return;
        const mq = window.matchMedia("(min-width: 768px)");
        const update = () => setIsDesktop(mq.matches);
        update();
        mq.addEventListener("change", update);
        return () => mq.removeEventListener("change", update);
    }, []);
    const addOrUpdateActiveAgent = useCallback((agent) => {
        startViewTransition(() => {
            setActiveAgents((prev) => {
                const idx = prev.findIndex((a) => a.id === agent.id);
                if (idx >= 0) {
                    const next = [...prev];
                    next[idx] = agent;
                    return next;
                }
                return [agent, ...prev];
            });
            setSelectedAgentId(agent.id);
            setActiveSidebarKey(`${ACTIVE_AGENT_PREFIX}${agent.id}`);
            setActiveAgentTab("chat");
        });
    }, []);
    const handleSelectAgent = useCallback(async (agent) => {
        addOrUpdateActiveAgent(agent);
        if (agent.status === "new")
            return;
        if (!agent.userId) {
            setLoadingAgent(true);
            try {
                const agentDetails = await getAgent(agent.id);
                const 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,
                    parentAgentId: agentDetails.parentAgentId,
                };
                addOrUpdateActiveAgent(fullAgent);
            }
            catch (error) {
                console.error("Failed to fetch agent details:", error);
            }
            finally {
                setLoadingAgent(false);
            }
        }
    }, [addOrUpdateActiveAgent]);
    const getAgentsListContent = useCallback((compact, section) => (_jsx(AgentsView, { onSelectAgent: handleSelectAgent, selectedAgentId: selectedAgentId ?? undefined, compact: compact, activeSection: section, onInboxCountChange: setInboxCount })), [handleSelectAgent, selectedAgentId]);
    useEffect(() => {
        let cancelled = false;
        (async () => {
            try {
                const response = await getAgentsGrouped(undefined, true, true);
                if (cancelled)
                    return;
                const fromApi = response.activeAgents ?? [];
                setActiveAgents((prev) => {
                    const sid = selectedAgentIdRef.current;
                    if (!sid || fromApi.some((a) => a.id === sid))
                        return fromApi;
                    const existing = prev.find((a) => a.id === sid);
                    if (existing)
                        return [existing, ...fromApi];
                    return fromApi;
                });
            }
            catch (error) {
                console.error("Failed to load active agents for sidebar:", error);
            }
        })();
        return () => {
            cancelled = true;
        };
    }, []);
    useEffect(() => {
        if (!isInitialUrlLoad.current)
            return;
        isInitialUrlLoad.current = false;
        try {
            const params = new URLSearchParams(window.location.search);
            const agentIdFromUrl = params.get("agentId");
            if (agentIdFromUrl) {
                skipNextUrlUpdate.current = true;
                handleSelectAgent({ id: agentIdFromUrl });
            }
        }
        catch (error) {
            console.error("Error reading agentId from URL:", error);
        }
    }, [handleSelectAgent]);
    useEffect(() => {
        if (skipNextUrlUpdate.current) {
            skipNextUrlUpdate.current = false;
            return;
        }
        try {
            const url = new URL(window.location.href);
            if (selectedAgentId) {
                url.searchParams.set("agentId", selectedAgentId);
            }
            else {
                url.searchParams.delete("agentId");
            }
            window.history.replaceState({}, "", url.toString());
        }
        catch (error) {
            console.error("Error updating URL with agentId:", error);
        }
    }, [selectedAgentId]);
    useEffect(() => {
        const handlePopState = () => {
            try {
                const params = new URLSearchParams(window.location.search);
                const agentIdFromUrl = params.get("agentId");
                if (agentIdFromUrl && agentIdFromUrl !== selectedAgentId) {
                    skipNextUrlUpdate.current = true;
                    handleSelectAgent({ id: agentIdFromUrl });
                }
                else if (!agentIdFromUrl && selectedAgentId) {
                    skipNextUrlUpdate.current = true;
                    setSelectedAgentId(null);
                    setActiveSidebarKey("inbox");
                }
            }
            catch (error) {
                console.error("Error handling popstate:", error);
            }
        };
        window.addEventListener("popstate", handlePopState);
        return () => window.removeEventListener("popstate", handlePopState);
    }, [handleSelectAgent, selectedAgentId]);
    // Load AI profiles on mount (like master) so AgentTerminal has profiles from the start
    useEffect(() => {
        let cancelled = false;
        (async () => {
            try {
                const loadedProfiles = await loadAiProfiles(editContext?.currentItemDescriptor);
                if (!cancelled) {
                    setProfiles(loadedProfiles || []);
                }
            }
            catch (e) {
                console.error("Failed to load AI profiles", e);
            }
        })();
        return () => {
            cancelled = true;
        };
    }, [editContext?.currentItemDescriptor]);
    useEffect(() => {
        if (!editContext?.addSocketMessageListener)
            return;
        const removeListener = editContext.addSocketMessageListener((message) => {
            if (message.type === "agent-profiles-changed") {
                loadAiProfiles(editContext?.currentItemDescriptor).then((p) => setProfiles(p || []));
            }
        });
        return () => removeListener();
    }, [
        editContext?.addSocketMessageListener,
        editContext?.currentItemDescriptor,
    ]);
    useEffect(() => {
        const handleOpenAgent = (ev) => {
            try {
                const ce = ev;
                const agentId = ce.detail?.agentId;
                if (!agentId)
                    return;
                handleSelectAgent({ id: agentId });
            }
            catch (error) {
                console.error("Error opening agent:", error);
            }
        };
        const handleSelectAgentEvent = (ev) => {
            try {
                const ce = ev;
                const agentId = ce.detail?.agentId;
                if (!agentId)
                    return;
                handleSelectAgent({ id: agentId });
            }
            catch (error) {
                console.error("Error selecting agent:", error);
            }
        };
        window.addEventListener("editor:openAgent", handleOpenAgent);
        window.addEventListener("editor:selectAgent", handleSelectAgentEvent);
        return () => {
            window.removeEventListener("editor:openAgent", handleOpenAgent);
            window.removeEventListener("editor:selectAgent", handleSelectAgentEvent);
        };
    }, [handleSelectAgent]);
    useEffect(() => {
        if (!editContext?.addSocketMessageListener)
            return;
        const unsubscribe = editContext.addSocketMessageListener((message) => {
            const payload = message.payload || {};
            const agentId = payload.agentId;
            if (message.type === "agent:run:status" &&
                agentId &&
                payload.data?.state) {
                const newStatus = parseAgentRunStatusData(payload.data);
                if (newStatus) {
                    setActiveAgents((prev) => prev.map((a) => a.id === agentId
                        ? { ...a, status: newStatus }
                        : a));
                }
            }
            else if (message.type === "agent:info:updated" && agentId) {
                const agentName = payload.agentName;
                const agentDescription = payload.agentDescription;
                setActiveAgents((prev) => prev.map((a) => a.id === agentId
                    ? {
                        ...a,
                        ...(agentName !== undefined && { name: agentName }),
                        ...(agentDescription !== undefined && {
                            description: agentDescription,
                        }),
                    }
                    : a));
            }
            else if (message.type === "agent:run:closed" && agentId) {
                setActiveAgents((prev) => prev.filter((a) => a.id !== agentId));
                setSelectedAgentId((prev) => (prev === agentId ? null : prev));
                setActiveSidebarKey((prev) => prev === `${ACTIVE_AGENT_PREFIX}${agentId}` ? "inbox" : prev);
            }
        });
        return unsubscribe;
    }, [editContext?.addSocketMessageListener]);
    // When selected agent was removed from activeAgents, switch to first remaining or inbox
    useEffect(() => {
        if (selectedAgentId == null)
            return;
        const stillActive = activeAgents.some((a) => a.id === selectedAgentId);
        if (!stillActive && activeAgents.length > 0) {
            const first = activeAgents[0];
            if (first) {
                setSelectedAgentId(first.id);
                setActiveSidebarKey(`${ACTIVE_AGENT_PREFIX}${first.id}`);
            }
        }
        else if (!stillActive) {
            setSelectedAgentId(null);
            setActiveSidebarKey("inbox");
        }
    }, [activeAgents, selectedAgentId]);
    const showEditorPanel = editContext?.showAgentsWorkspaceEditor ?? false;
    useEffect(() => {
        if (!editContext?.isMobile)
            return;
        if (!shouldAutoShowMobileEditorRef.current)
            return;
        if (!showEditorPanel) {
            editContext.setShowAgentsWorkspaceEditor(true);
        }
        shouldAutoShowMobileEditorRef.current = false;
    }, [editContext?.isMobile, showEditorPanel, editContext]);
    const mainNavItems = useMemo(() => [
        {
            id: "inbox",
            label: inboxCount > 0 ? `Inbox (${inboxCount})` : "Inbox",
        },
        { id: "all", label: "All Agents" },
        { id: "create", label: "Create New" },
    ], [inboxCount]);
    const sortedActiveAgents = useMemo(() => {
        return [...activeAgents].sort((a, b) => {
            const dateA = a.lastMessageDate || a.updatedDate;
            const dateB = b.lastMessageDate || b.updatedDate;
            return new Date(dateB).getTime() - new Date(dateA).getTime();
        });
    }, [activeAgents]);
    const handleCloseActiveAgent = (agentId, e) => {
        e.stopPropagation();
        setActiveAgents((prev) => prev.filter((a) => a.id !== agentId));
        if (selectedAgentId === agentId) {
            setSelectedAgentId(null);
            setActiveSidebarKey("inbox");
        }
    };
    const handleSidebarNavClick = (id) => {
        startViewTransition(() => {
            if (id.startsWith(ACTIVE_AGENT_PREFIX)) {
                setSelectedAgentId(id.slice(ACTIVE_AGENT_PREFIX.length));
            }
            else {
                setSelectedAgentId(null);
            }
            setActiveSidebarKey(id);
        });
        if (!getIsDesktop()) {
            setMobileSidebarOpen(false);
        }
    };
    const sectionFromSidebarKey = (key) => {
        if (key === "inbox" || key === "all" || key === "create")
            return key;
        return undefined;
    };
    const activeSection = sectionFromSidebarKey(activeSidebarKey);
    const isActiveAgentView = activeSidebarKey.startsWith(ACTIVE_AGENT_PREFIX);
    const pageHeaderDescription = useMemo(() => {
        if (activeSidebarKey.startsWith(ACTIVE_AGENT_PREFIX)) {
            const agentId = activeSidebarKey.slice(ACTIVE_AGENT_PREFIX.length);
            const agent = activeAgents.find((a) => a.id === agentId);
            return agent?.name ?? undefined;
        }
        const item = mainNavItems.find((i) => i.id === activeSidebarKey);
        return item?.label ?? undefined;
    }, [activeSidebarKey, activeAgents, mainNavItems]);
    const slotContext = editContext?.getActiveSlotContext();
    const agentTerminalContent = useMemo(() => {
        if (loadingAgent) {
            return (_jsxs("div", { className: "flex h-full items-center justify-center gap-2", style: { viewTransitionName: "agents-chat-pane" }, children: [_jsx(Spinner, { size: "sm" }), _jsx("span", { className: "text-sm text-gray-500", children: "Loading agent..." })] }));
        }
        if (selectedAgent) {
            return (_jsx("div", { className: "flex h-full min-h-0 flex-col", style: { viewTransitionName: "agents-chat-pane" }, children: _jsx(AgentTerminal, { agentStub: selectedAgent, profiles: profiles, isActive: true, compact: false, hideContext: false, hideBottomControls: false, hideGreeting: true }, selectedAgent.id) }));
        }
        return (_jsxs("div", { className: "flex h-full flex-col items-center justify-center gap-4 p-8 text-center", style: { viewTransitionName: "agents-chat-pane" }, children: [_jsx(SecretAgentIcon, { size: 64, strokeWidth: 0.5, className: "text-gray-300" }), _jsxs("div", { children: [_jsx("h3", { className: "text-lg font-medium text-gray-700", children: "No Agent Selected" }), _jsx("p", { className: "mt-1 text-sm text-gray-500", children: "Select an agent from the list to view its conversation" })] })] }));
    }, [loadingAgent, selectedAgent, profiles]);
    const itemPreviewContent = useMemo(() => {
        if (!slotContext) {
            return (_jsxs("div", { className: "flex h-full flex-col items-center justify-center gap-4 p-8 text-center", children: [_jsx("div", { className: "text-6xl text-gray-200", children: "\uD83D\uDCC4" }), _jsxs("div", { children: [_jsx("h3", { className: "text-lg font-medium text-gray-700", children: "No Item Selected" }), _jsx("p", { className: "mt-1 text-sm text-gray-500", children: "The agent's edits will appear here when working on an item" })] })] }));
        }
        return (_jsx(EditorSlotContextProvider, { value: slotContext, children: _jsx(SingleEditView, { compareView: false, name: "agents-workspace-preview", view: "primary" }) }));
    }, [slotContext]);
    useEffect(() => {
        if (!showEditorPanel && activeAgentTab === "preview") {
            setActiveAgentTab("chat");
        }
    }, [showEditorPanel, activeAgentTab]);
    const desktopPanels = useMemo(() => {
        const panels = [
            {
                name: "agents-list",
                defaultSize: 350,
                content: (_jsx("div", { className: "h-full overflow-hidden border-r border-gray-200", children: getAgentsListContent(false) })),
            },
            {
                name: "agent-terminal",
                defaultSize: "auto",
                content: (_jsx("div", { className: "relative h-full w-full overflow-hidden bg-white", children: _jsx("div", { className: "absolute inset-0", children: agentTerminalContent }) })),
            },
        ];
        if (showEditorPanel) {
            panels.push({
                name: "editor-preview",
                defaultSize: 500,
                content: (_jsx("div", { className: "h-full overflow-hidden border-l border-gray-200 bg-gray-50", children: itemPreviewContent })),
            });
        }
        return panels;
    }, [
        getAgentsListContent,
        agentTerminalContent,
        itemPreviewContent,
        showEditorPanel,
    ]);
    if (isDesktop) {
        return (_jsx("div", { className: "h-full w-full", children: _jsx(Splitter, { panels: desktopPanels, localStorageKey: "agents-workspace.panelSizes", direction: "horizontal" }) }));
    }
    return (_jsxs("div", { className: "flex h-full min-h-0 w-full flex-col", children: [_jsxs("div", { className: "relative shrink-0 border-b border-gray-200", children: [_jsx(PageHeader, { icon: _jsx(SecretAgentIcon, { size: 28, strokeWidth: 1.5 }), title: "AI Agents", description: pageHeaderDescription, variant: "compact" }), _jsx("div", { className: "absolute top-1/2 right-4 z-30 flex -translate-y-1/2 items-center gap-2", children: _jsx("button", { type: "button", onClick: () => setMobileSidebarOpen((v) => !v), className: "inline-flex h-9 w-9 items-center justify-center rounded-md border border-gray-300 bg-white text-gray-700 shadow-sm transition-colors hover:bg-gray-50", "aria-label": mobileSidebarOpen
                                ? "Close agents navigation"
                                : "Open agents navigation", title: mobileSidebarOpen
                                ? "Close agents navigation"
                                : "Open agents navigation", children: _jsxs("span", { className: "relative inline-flex", children: [_jsx(Menu, { className: "h-4 w-4", strokeWidth: 1.75 }), inboxCount > 0 && (_jsx("span", { className: "absolute -top-3 -right-3 flex h-4 min-w-4 items-center justify-center rounded-full bg-emerald-500 px-1 text-[10px] font-semibold text-white ring-2 ring-white", "aria-label": `${inboxCount} items in inbox`, children: inboxCount > 99 ? "99+" : inboxCount }))] }) }) })] }), _jsxs("div", { className: "relative flex min-h-0 flex-1 overflow-hidden", children: [mobileSidebarOpen && (_jsx("button", { type: "button", className: "absolute inset-0 z-10 bg-black/20", "aria-label": "Close agents navigation", onClick: () => setMobileSidebarOpen(false) })), _jsx("div", { className: cn("z-20 flex min-h-0 flex-col border-r border-gray-200 bg-gray-50", "transition-[width,transform,box-shadow] duration-300 ease-out", mobileSidebarOpen
                            ? "absolute inset-y-0 left-0 w-64 shadow-xl"
                            : "absolute inset-y-0 left-0 w-0 -translate-x-full overflow-hidden border-r-0"), children: _jsx(AgentsSidebar, { mainNavItems: mainNavItems, activeAgents: sortedActiveAgents, activeSidebarKey: activeSidebarKey, onNavClick: handleSidebarNavClick, onCloseAgent: handleCloseActiveAgent }) }), _jsxs("div", { className: "relative flex min-h-0 flex-1 flex-col overflow-hidden bg-white", children: [activeSection !== undefined && (_jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: getAgentsListContent(true, activeSection) })), isActiveAgentView && (_jsxs("div", { className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: [showEditorPanel && (_jsx("div", { className: "shrink-0 border-b border-gray-100 bg-white px-4 shadow-[0_1px_2px_rgba(0,0,0,0.03)]", children: _jsx(SimpleTabs, { tabs: [
                                                {
                                                    id: "chat",
                                                    label: "Chat",
                                                    content: null,
                                                    testId: "active-agent-tab-chat",
                                                },
                                                {
                                                    id: "preview",
                                                    label: "Item Preview",
                                                    content: null,
                                                    testId: "active-agent-tab-preview",
                                                },
                                            ], activeTab: activeAgentTab === "preview" ? 1 : 0, setActiveTab: (index) => setActiveAgentTab(index === 0 ? "chat" : "preview"), hideContent: true, variant: "elegant", className: "gap-6" }) })), _jsxs("div", { className: "relative min-h-0 flex-1 overflow-hidden", children: [_jsx("div", { className: cn("absolute inset-0", activeAgentTab !== "chat" && "hidden"), children: agentTerminalContent }), showEditorPanel && (_jsx("div", { className: cn("absolute inset-0 overflow-hidden border-l border-gray-200 bg-gray-50", activeAgentTab !== "preview" && "hidden"), children: itemPreviewContent }))] })] }))] })] })] }));
}
//# sourceMappingURL=AgentsWorkspaceView.js.map