import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useMemo, useRef, useCallback, } from "react";
import { AgentsView } from "./AgentsView";
import { AgentGalleryView } from "./AgentGalleryView";
import { AgentsSidebar, ACTIVE_AGENT_PREFIX } from "./AgentsSidebar";
import { AgentTerminal } from "../editor/ai/AgentTerminal";
import { useAgentPanes } from "../editor/ai/useAgentPanes";
import { AgentPanesGrid } from "../editor/ai/AgentPanesGrid";
import { AGENT_PANES_LAYOUT_STORAGE_KEY, } from "../editor/ai/agentPanesTypes";
import { ItemEditorPane } from "../editor/views/ItemEditorPane";
import { useEditContext } from "../editor/client/editContext";
import { setActiveAgentConversation } from "../editor/ai/useActiveAgentConversation";
import { getAgent, getAgentsGrouped, } from "../editor/services/agentService";
import { parseAgentRunStatusData } from "../editor/services/agentStatus";
import { loadAiProfiles } from "../editor/services/aiService";
import { ParheliaAgentIcon } from "../editor/ui/Icons";
import { Spinner } from "../editor/ui/Spinner";
import { SimpleTabs } from "../editor/ui/SimpleTabs";
import { Splitter } from "../editor/ui/Splitter";
import { Menu, PanelRightOpen, PanelBottomOpen, X as XIcon, } from "lucide-react";
import { cn } from "../lib/utils";
import { startViewTransition } from "../lib/viewTransition";
function isLocalOnlyDraftAgent(agent) {
    return agent?.status === "new" && !agent.userId;
}
function isAgentNotFoundError(error) {
    const message = error instanceof Error ? error.message : String(error ?? "");
    const normalized = message.toLowerCase();
    return message.includes("404") || normalized.includes("not found");
}
/**
 * AgentsWorkspaceView - Desktop: Splitter (AgentsView | AgentTerminal | ItemEditorPane).
 * 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 [profiles, setProfiles] = useState([]);
    const [loadingAgent, setLoadingAgent] = useState(false);
    const [activeSidebarKey, setActiveSidebarKey] = useState(null);
    const [activeAgentTab, setActiveAgentTab] = useState("chat");
    const isInitialUrlLoad = useRef(true);
    const skipNextUrlUpdate = useRef(false);
    // Multi-pane layout — workspace gets its own storage key so it doesn't
    // share splits with the embedded tabbed Agents UI.
    const panes = useAgentPanes(activeAgents, {
        storageKey: `${AGENT_PANES_LAYOUT_STORAGE_KEY}.workspace`,
    });
    const { layout: panesLayout, focusedPaneId, panesByAgentId, focusedAgentId, setFocusedPane, showAgentInFocusedPane, showOverviewInFocusedPane, showProfileSelectorInFocusedPane, splitPane, closePane, closeAgentEverywhere, pruneMissingAgents, } = panes;
    // Compat aliases: the rest of this component still reads `selectedAgentId`
    // (= the agent shown in the focused pane). Writes go through the hook.
    const selectedAgentId = focusedAgentId;
    const selectedAgentIdRef = useRef(null);
    useEffect(() => {
        selectedAgentIdRef.current = focusedAgentId;
    }, [focusedAgentId]);
    const setSelectedAgentId = useCallback((next) => {
        const value = typeof next === "function"
            ? next(focusedAgentId)
            : next;
        if (value === null) {
            showOverviewInFocusedPane();
        }
        else {
            showAgentInFocusedPane(value);
        }
    }, [focusedAgentId, showOverviewInFocusedPane, showAgentInFocusedPane]);
    const selectedAgent = selectedAgentId != null
        ? (activeAgents.find((agent) => agent.id === selectedAgentId) ?? null)
        : null;
    const selectedAgentIsLocalOnlyDraft = isLocalOnlyDraftAgent(selectedAgent);
    // Stable ref to closeAgentEverywhere so the WebSocket effect (with empty
    // deps over its handler) calls the current implementation rather than a
    // stale closure.
    const closeAgentEverywhereRef = useRef(closeAgentEverywhere);
    useEffect(() => {
        closeAgentEverywhereRef.current = closeAgentEverywhere;
    }, [closeAgentEverywhere]);
    const clearAgentIdFromUrl = useCallback((agentId) => {
        if (typeof window === "undefined")
            return;
        try {
            const url = new URL(window.location.href);
            if (url.searchParams.get("agentId") !== agentId)
                return;
            url.searchParams.delete("agentId");
            window.history.replaceState({}, "", url.toString());
        }
        catch (error) {
            console.error("Error clearing stale agentId from URL:", error);
        }
    }, []);
    const handleAgentNotFound = useCallback((agentId) => {
        setActiveAgents((prev) => prev.filter((agent) => agent.id !== agentId));
        closeAgentEverywhereRef.current(agentId);
        setActiveSidebarKey((prev) => prev === `${ACTIVE_AGENT_PREFIX}${agentId}` ? null : prev);
        clearAgentIdFromUrl(agentId);
    }, [clearAgentIdFromUrl]);
    // Tracks whether the initial getAgentsGrouped() fetch has resolved. Used
    // to gate `pruneMissingAgents` so a pane whose agent hasn't yet been
    // populated isn't wiped to overview during the loading window. The flip
    // to `true` happens in the fetch effect lower in this file.
    const [agentsFetched, setAgentsFetched] = useState(false);
    // Whether the user has any agents at all (active or closed). `null` until
    // the initial fetch resolves; sticky-true once any agent exists so the
    // first-time gallery never flickers back after the first chat is created.
    const [hasAnyAgents, setHasAnyAgents] = useState(null);
    // Note: we deliberately do NOT auto-prune panes against `activeAgents`.
    // `getAgentsGrouped` returns only currently-active agents, so a pane that
    // references a closed-but-not-deleted agent would otherwise be wiped on
    // every workspace switch. The pane's placeholder stub lets AgentTerminal
    // mount and call `loadAgent()` itself, which works for closed agents too.
    // Panes are only cleared in response to explicit close events from the run
    // lifecycle, such as WS `agent:run:closed`.
    // `pruneMissingAgents` is still imported and available; we just don't run
    // it on a timer.
    void pruneMissingAgents;
    useEffect(() => {
        editContext?.setSelectedAgentsWorkspaceAgentId(selectedAgentId);
        setActiveAgentConversation(selectedAgentId);
    }, [editContext, selectedAgentId]);
    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, options) => {
        setHasAnyAgents(true);
        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];
            });
            // If this agent already has a pane (e.g. layout restored from
            // localStorage and the URL agentId matches what's already shown),
            // just move focus there instead of replacing the focused pane's
            // content with a duplicate.
            const existingPanes = panesByAgentId.get(agent.id);
            const firstPane = existingPanes?.[0];
            if (firstPane) {
                setFocusedPane(firstPane);
            }
            else if (options?.split && focusedPaneId) {
                // Alt-click → open in a new pane next to the focused one
                // instead of replacing the focused pane's content.
                splitPane(focusedPaneId, agent.id, "right");
            }
            else {
                setSelectedAgentId(agent.id);
            }
            setActiveSidebarKey(`${ACTIVE_AGENT_PREFIX}${agent.id}`);
            setActiveAgentTab("chat");
        });
    }, [
        panesByAgentId,
        setFocusedPane,
        setSelectedAgentId,
        splitPane,
        focusedPaneId,
    ]);
    const handleSelectAgent = useCallback(async (agent, options) => {
        addOrUpdateActiveAgent(agent, options);
        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) {
                if (isAgentNotFoundError(error)) {
                    handleAgentNotFound(agent.id);
                }
                else {
                    console.error("Failed to fetch agent details:", error);
                }
            }
            finally {
                setLoadingAgent(false);
            }
        }
    }, [addOrUpdateActiveAgent, handleAgentNotFound]);
    // Build a draft agent from a gallery profile pick and show it in the
    // focused pane. The agent is only persisted once the first prompt is sent.
    const handleProfilePicked = useCallback((profile) => {
        const agentDisplayName = profile.agentName || profile.displayTitle || profile.name;
        const newAgent = {
            status: "new",
            id: crypto.randomUUID(),
            name: agentDisplayName,
            updatedDate: new Date().toISOString(),
            userId: "",
            profileId: profile.id,
            profileName: profile.name,
            profileSvgIcon: profile.svgIcon,
        };
        handleSelectAgent(newAgent);
    }, [handleSelectAgent]);
    const getAgentsListContent = useCallback((compact, hideNewAgentButton = false) => (_jsx(AgentsView, { onSelectAgent: handleSelectAgent, selectedAgentId: selectedAgentId ?? undefined, compact: compact, onRequestCreateAgent: showProfileSelectorInFocusedPane, hideNewAgentButton: hideNewAgentButton })), [handleSelectAgent, selectedAgentId, showProfileSelectorInFocusedPane]);
    useEffect(() => {
        let cancelled = false;
        (async () => {
            try {
                const response = await getAgentsGrouped(undefined, true, true);
                if (cancelled)
                    return;
                const fromApi = response.activeAgents ?? [];
                const anyClosed = (response.closedAgentsByProfile ?? []).some((group) => (group.totalClosedCount ?? 0) > 0 ||
                    (group.agents?.length ?? 0) > 0);
                setHasAnyAgents((prev) => prev === true ? true : fromApi.length > 0 || anyClosed);
                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);
            }
            finally {
                if (!cancelled)
                    setAgentsFetched(true);
            }
        })();
        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 && !selectedAgentIsLocalOnlyDraft) {
                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, selectedAgentIsLocalOnlyDraft]);
    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(null);
                }
            }
            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));
                // Replace this agent in any pane that's showing it. Calling
                // through a ref so the empty-deps WS handler always uses the
                // current implementation.
                closeAgentEverywhereRef.current(agentId);
                setActiveSidebarKey((prev) => prev === `${ACTIVE_AGENT_PREFIX}${agentId}` ? null : prev);
            }
        });
        return unsubscribe;
    }, [editContext?.addSocketMessageListener]);
    // When the selected agent was removed from activeAgents (e.g. another tab
    // closed it), fall back to the overview. Gated on `agentsFetched` so this
    // doesn't fire during the initial load window — at that point activeAgents
    // is briefly [] while the focused pane already has an agent restored from
    // localStorage, and we don't want to spuriously clear it.
    // We also no longer auto-switch when activeAgents has other entries: the
    // focused pane may legitimately host a closed-but-still-openable agent
    // that AgentTerminal can render via its own loadAgent().
    useEffect(() => {
        if (!agentsFetched)
            return;
        if (selectedAgentId == null)
            return;
        const stillActive = activeAgents.some((a) => a.id === selectedAgentId);
        if (stillActive)
            return;
        if (activeAgents.length === 0) {
            setActiveSidebarKey(null);
        }
    }, [activeAgents, selectedAgentId, agentsFetched]);
    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 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 handleSidebarNavClick = (id) => {
        startViewTransition(() => {
            if (id.startsWith(ACTIVE_AGENT_PREFIX)) {
                setSelectedAgentId(id.slice(ACTIVE_AGENT_PREFIX.length));
                setActiveSidebarKey(id);
            }
            else {
                setSelectedAgentId(null);
                setActiveSidebarKey(null);
            }
        });
        if (!getIsDesktop()) {
            setMobileSidebarOpen(false);
        }
    };
    const isActiveAgentView = typeof activeSidebarKey === "string" &&
        activeSidebarKey.startsWith(ACTIVE_AGENT_PREFIX);
    // Render a single pane's content. Used as the renderPane callback for
    // AgentPanesGrid. Includes a small overlay header (split/close actions)
    // pinned to the top-right of each pane so the user can shape the layout
    // without leaving the workspace view.
    const renderWorkspacePane = useCallback((pane, isFocused) => {
        const isOnlyPane = panesLayout.rows.flat().length === 1;
        const overlay = (_jsxs("div", { className: "ring-border-default pointer-events-none absolute top-2 right-2 z-10 flex items-center gap-1 rounded-md bg-white/80 px-1 py-0.5 shadow-sm ring-1 backdrop-blur-sm", children: [_jsx("button", { type: "button", className: "text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-100 pointer-events-auto inline-flex h-6 w-6 items-center justify-center rounded", title: "Split right (empty pane \u2014 pick an agent next)", "aria-label": "Split right", onClick: (e) => {
                        e.stopPropagation();
                        splitPane(pane.id, null, "right");
                    }, children: _jsx(PanelRightOpen, { className: "h-3.5 w-3.5", strokeWidth: 1 }) }), _jsx("button", { type: "button", className: "text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-100 pointer-events-auto inline-flex h-6 w-6 items-center justify-center rounded", title: "Split down (empty pane \u2014 pick an agent next)", "aria-label": "Split down", onClick: (e) => {
                        e.stopPropagation();
                        splitPane(pane.id, null, "down");
                    }, children: _jsx(PanelBottomOpen, { className: "h-3.5 w-3.5", strokeWidth: 1 }) }), !isOnlyPane && (_jsx("button", { type: "button", className: "text-neutral-grey-50 hover:bg-feedback-red-light hover:text-feedback-red pointer-events-auto inline-flex h-6 w-6 items-center justify-center rounded", title: "Close pane", "aria-label": "Close pane", onClick: (e) => {
                        e.stopPropagation();
                        closePane(pane.id);
                    }, children: _jsx(XIcon, { className: "h-3.5 w-3.5", strokeWidth: 1 }) }))] }));
        if (pane.view.kind === "overview") {
            return (_jsxs("div", { className: "absolute inset-0 flex flex-col items-center justify-center gap-4 p-8 text-center", children: [overlay, _jsx(ParheliaAgentIcon, { size: 64, strokeWidth: 0.5, className: "text-neutral-grey-50" }), _jsxs("div", { children: [_jsx("h3", { className: "text-neutral-grey-100 text-lg font-medium", children: "No Agent Selected" }), _jsx("p", { className: "text-neutral-grey-50 mt-1 text-[12px]", children: "Select an agent from the list to view its conversation" })] })] }));
        }
        if (pane.view.kind === "profile-selector") {
            // Render the agent gallery directly. Picking a profile fires
            // handleProfilePicked → addOrUpdateActiveAgent, which puts the new
            // agent into the focused pane (this one).
            return (_jsxs("div", { className: "bg-neutral-grey-5 absolute inset-0 overflow-auto", children: [overlay, _jsx(AgentGalleryView, { variant: "pane", onSelectProfile: handleProfilePicked })] }));
        }
        const paneAgentId = pane.view.agentId;
        const agentForPane = activeAgents.find((a) => a.id === paneAgentId);
        const isLoadingThisPane = loadingAgent && isFocused;
        if (isLoadingThisPane) {
            return (_jsxs("div", { className: "absolute inset-0 flex items-center justify-center gap-2", children: [overlay, _jsx(Spinner, { size: "sm" }), _jsx("span", { className: "text-neutral-grey-50 text-[12px]", children: "Loading agent..." })] }));
        }
        // If the layout was just restored from localStorage and the initial
        // agents fetch is still in flight, build a minimal stub so
        // AgentTerminal can still mount and fire its own loadAgent(). Without
        // this, the pane would render `null` and stay blank until the fetch
        // resolves; on slow networks that's perceived as "agents not
        // restored". Once activeAgents includes the real entry the pane
        // re-renders with the full data.
        const stubForPane = agentForPane ?? {
            id: paneAgentId,
            name: "Loading…",
            userId: "",
            updatedDate: "",
            status: "idle",
        };
        return (_jsxs("div", { className: "flex h-full min-h-0 flex-col", children: [overlay, _jsx(AgentTerminal, { agentStub: stubForPane, profiles: profiles, onAgentNotFound: handleAgentNotFound, isVisible: true, isFocused: isFocused, compact: false, hideContext: false, hideBottomControls: false }, stubForPane.id)] }));
    }, [
        activeAgents,
        profiles,
        loadingAgent,
        panesLayout,
        splitPane,
        closePane,
        handleProfilePicked,
        handleAgentNotFound,
    ]);
    const agentTerminalContent = useMemo(() => {
        return (_jsx(AgentPanesGrid, { layout: panesLayout, focusedPaneId: focusedPaneId, onPaneMouseDownCapture: setFocusedPane, renderPane: renderWorkspacePane }));
    }, [panesLayout, focusedPaneId, setFocusedPane, renderWorkspacePane]);
    const itemPreviewContent = useMemo(() => {
        return (_jsx(ItemEditorPane, { name: "agents-workspace-preview", emptyTitle: "No Item Selected", emptyDescription: "The agent's edits will appear here when working on an item" }));
    }, []);
    useEffect(() => {
        if (!showEditorPanel && activeAgentTab === "preview") {
            setActiveAgentTab("chat");
        }
    }, [showEditorPanel, activeAgentTab]);
    const desktopWorkAreaPanels = useMemo(() => {
        const panels = [
            {
                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: "border-border-default bg-neutral-grey-5 h-full overflow-hidden border-l", children: itemPreviewContent })),
            });
        }
        return panels;
    }, [agentTerminalContent, itemPreviewContent, showEditorPanel]);
    const desktopWorkAreaContent = useMemo(() => {
        return (_jsx("div", { className: "flex h-full min-h-0 flex-col overflow-hidden bg-white", children: showEditorPanel ? (_jsx(Splitter, { panels: desktopWorkAreaPanels, localStorageKey: "agents-workspace.workAreaPanelSizes", direction: "horizontal" })) : (_jsx("div", { className: "relative h-full w-full overflow-hidden bg-white", children: _jsx("div", { className: "absolute inset-0", children: agentTerminalContent }) })) }));
    }, [agentTerminalContent, desktopWorkAreaPanels, showEditorPanel]);
    const desktopPanels = useMemo(() => [
        {
            name: "agents-list",
            defaultSize: 280,
            minSize: 220,
            content: (_jsx("div", { className: "border-border-default h-full overflow-hidden border-r bg-white", children: getAgentsListContent(true) })),
        },
        {
            name: "agents-work-area",
            defaultSize: "auto",
            minSize: 360,
            content: desktopWorkAreaContent,
        },
    ], [desktopWorkAreaContent, getAgentsListContent]);
    // First-time experience: no agents exist at all, so show the full-width
    // gallery without the chat sidebar. Gated on `agentsFetched` so the gallery
    // never flashes while the initial fetch is in flight; `hasAnyAgents` is
    // sticky-true once the first agent (draft or fetched) appears.
    const showFirstTimeGallery = agentsFetched && hasAnyAgents === false && activeAgents.length === 0;
    if (isDesktop) {
        if (showFirstTimeGallery) {
            return (_jsx("div", { className: "bg-neutral-grey-5 flex h-full min-h-0 w-full flex-col", children: _jsx(AgentGalleryView, { variant: "full", onSelectProfile: handleProfilePicked }) }));
        }
        return (_jsx("div", { className: "bg-neutral-grey-5 h-full w-full", children: _jsx(Splitter, { panels: desktopPanels, localStorageKey: "agents-workspace.sidebarPanelSizes", direction: "horizontal" }) }));
    }
    return (_jsxs("div", { className: "bg-neutral-grey-5 flex h-full min-h-0 w-full flex-col", children: [_jsx("div", { className: "border-border-default flex shrink-0 justify-end border-b bg-white px-4 py-2", children: _jsx("button", { type: "button", onClick: () => setMobileSidebarOpen((v) => !v), className: "border-border-default text-neutral-grey-100 hover:bg-neutral-grey-5 inline-flex h-9 w-9 items-center justify-center rounded-md border bg-white shadow-sm transition-colors", "aria-label": mobileSidebarOpen
                        ? "Close agents navigation"
                        : "Open agents navigation", title: mobileSidebarOpen
                        ? "Close agents navigation"
                        : "Open agents navigation", children: _jsx(Menu, { className: "h-4 w-4", strokeWidth: 1 }) }) }), _jsxs("div", { className: "relative flex min-h-0 flex-1 overflow-hidden", children: [mobileSidebarOpen && (_jsx("button", { type: "button", className: "bg-neutral-grey-100/20 absolute inset-0 z-10", "aria-label": "Close agents navigation", onClick: () => setMobileSidebarOpen(false) })), _jsx("div", { className: cn("border-border-default bg-neutral-grey-5 z-20 flex min-h-0 flex-col border-r", "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, { activeAgents: sortedActiveAgents, activeSidebarKey: activeSidebarKey ?? "", onNavClick: handleSidebarNavClick }) }), _jsxs("div", { className: "relative flex min-h-0 flex-1 flex-col overflow-hidden bg-white", children: [!isActiveAgentView && (_jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: getAgentsListContent(true) })), isActiveAgentView && (_jsxs("div", { className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: [showEditorPanel && (_jsx("div", { className: "border-border-default shrink-0 border-b bg-white px-4 shadow-[0_1px_2px_color-mix(in_srgb,var(--color-neutral-grey-100)_3%,transparent)]", 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, 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("border-border-default bg-neutral-grey-5 absolute inset-0 overflow-hidden border-l", activeAgentTab !== "preview" && "hidden"), children: itemPreviewContent }))] })] }))] })] })] }));
}
//# sourceMappingURL=AgentsWorkspaceView.js.map