"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useCallback, startTransition, useRef, } from "react";
import { flushSync } from "react-dom";
import { Loader2, RotateCcw, History, ArrowRight, X, Paperclip, FileText, Image as ImageIcon, } from "lucide-react";
import { CloseButton } from "../components/ui/close-button";
import { useEditContext } from "../editor/client/editContext";
import { loadAiProfiles } from "../editor/services/aiService";
import { AGENT_DOCUMENT_UPLOADED_EVENT, AGENT_DOCUMENTS_CHANGED_EVENT, closeAgent, deleteDocument, getAgentDocuments, getAgentsGrouped, uploadDocument, } from "../editor/services/agentService";
import { AgentTerminal } from "../editor/ai/AgentTerminal";
import { useSplashScreenAgent } from "./SplashScreenAgentContext";
import { ParheliaIconWhite } from "../editor/ui/ParheliaIconWhite";
import { cn } from "../lib/utils";
import { Button } from "../components/ui/button";
import { getSamplePrompts } from "../editor/services/systemService";
const SUGGESTED_PROMPTS = [
    {
        title: "Draft a blog post",
        description: "Write a 500-word post about digital marketing trends.",
        prompt: "Can you help me draft a 500-word blog post about the latest trends in digital marketing for 2025?",
    },
    {
        title: "Analyze my page",
        description: "Give me feedback on the SEO of my current page.",
        prompt: "Please analyze my current page and give me feedback on how I can improve its SEO and readability.",
    },
    {
        title: "Generate ideas",
        description: "Suggest 5 creative topics for my next newsletter.",
        prompt: "Suggest 5 creative and engaging topics for my next monthly customer newsletter.",
    },
    {
        title: "Fix tone of voice",
        description: "Make this text sound more professional and welcoming.",
        prompt: "I have some text that I want to sound more professional and welcoming. Can you help me rewrite it?",
    },
];
export const ParheliaAssistantChat = ({ className, externalAgent, }) => {
    const editContext = useEditContext();
    // Agent/terminal/input state is held in SplashScreenAgentProvider so it
    // survives ModernSplashScreen unmount when the user switches workspaces.
    const { agent, setAgent, agentKey, setAgentKey, isTerminalVisible, setIsTerminalVisible, initialPrompt, setInitialPrompt, initialPromptDelivered, setInitialPromptDelivered, attachedDocs, setAttachedDocs, inputValue, setInputValue, } = useSplashScreenAgent();
    const [profile, setProfile] = useState(null);
    const [profiles, setProfiles] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [recentAgents, setRecentAgents] = useState([]);
    const [hasLoadedRecentAgents, setHasLoadedRecentAgents] = useState(false);
    const [isLoadingRecentAgents, setIsLoadingRecentAgents] = useState(false);
    const [samplePrompts, setSamplePrompts] = useState(SUGGESTED_PROMPTS);
    const inputRef = useRef(null);
    const fileInputRef = useRef(null);
    const [isUploading, setIsUploading] = useState(false);
    const [uploadError, setUploadError] = useState(null);
    const [isDragOver, setIsDragOver] = useState(false);
    // Create a new agent
    const createNewAgent = useCallback((selectedProfile) => {
        const agentDisplayName = selectedProfile.agentName || "Parhelia";
        const agentId = crypto.randomUUID();
        const newAgent = {
            status: "new",
            id: agentId,
            name: agentDisplayName,
            updatedDate: new Date().toISOString(),
            userId: "",
            profileId: selectedProfile.id,
            profileName: selectedProfile.name,
        };
        setAttachedDocs([]);
        setAgent(newAgent);
        return newAgent;
    }, [setAgent, setAttachedDocs]);
    // Track current agent in a ref so loadData can decide whether to skip
    // creating a fresh draft on remount without depending on `agent` directly
    // (which would re-run loadData on every agent update).
    const agentRef = useRef(agent);
    useEffect(() => {
        agentRef.current = agent;
    }, [agent]);
    const loadRecentAgents = useCallback(async (selectedProfile, options) => {
        if (!options?.force && (hasLoadedRecentAgents || isLoadingRecentAgents)) {
            return;
        }
        setIsLoadingRecentAgents(true);
        try {
            const response = await getAgentsGrouped();
            const allAgents = [...response.activeAgents];
            response.closedAgentsByProfile.forEach((group) => {
                allAgents.push(...group.agents);
            });
            const parheliaAgents = allAgents.filter((item) => item.profileId === selectedProfile.id);
            setRecentAgents(parheliaAgents.slice(0, 5));
            setHasLoadedRecentAgents(true);
        }
        catch (err) {
            console.error("Failed to load recent agents:", err);
        }
        finally {
            setIsLoadingRecentAgents(false);
        }
    }, [hasLoadedRecentAgents, isLoadingRecentAgents]);
    // Function to load profiles and initialize a draft agent
    const loadData = useCallback(async () => {
        try {
            setIsLoading(true);
            // Fetch sample prompts
            getSamplePrompts().then((res) => {
                if (res.data && res.data.length > 0) {
                    setSamplePrompts(res.data);
                }
            });
            const profileList = await loadAiProfiles();
            if (!profileList || profileList.length === 0) {
                setIsLoading(false);
                return;
            }
            // Try to find Parhelia profile with multiple strategies
            let assistantProfile;
            // Strategy 1: Look for exact ID match
            assistantProfile = profileList.find((p) => p.id === "7d45ab97-f253-4915-8b32-f9e8c762c5e9");
            // Strategy 2: Look for exact name match (case-insensitive)
            if (!assistantProfile) {
                assistantProfile = profileList.find((p) => p.name.toLowerCase() === "parhelia");
            }
            // Strategy 3: Look for profile containing "parhelia" in name or displayTitle
            if (!assistantProfile) {
                assistantProfile = profileList.find((p) => p.name.toLowerCase().includes("parhelia") ||
                    p.displayTitle?.toLowerCase().includes("parhelia"));
            }
            // Strategy 4: Fallback to first available profile
            const selectedProfile = assistantProfile || profileList[0];
            if (selectedProfile) {
                setProfile(selectedProfile);
                setProfiles(profileList);
                setRecentAgents([]);
                setHasLoadedRecentAgents(false);
                // Only create a fresh draft agent if the persistent splash state
                // doesn't already hold one for this profile (e.g. user switched
                // workspaces away and back while an agent is running).
                const existing = agentRef.current;
                if (!existing || existing.profileId !== selectedProfile.id) {
                    createNewAgent(selectedProfile);
                }
            }
            else {
                console.error("ParheliaAssistantChat: Could not select a profile from the available profiles.");
            }
        }
        catch (err) {
            console.error("Failed to load AI profile:", err);
        }
        finally {
            setIsLoading(false);
        }
    }, [createNewAgent]);
    // Load AI profiles and data on mount
    useEffect(() => {
        loadData();
    }, [loadData]);
    // Listen for agent profile changes via websocket
    useEffect(() => {
        if (!editContext?.addSocketMessageListener)
            return;
        const removeListener = editContext.addSocketMessageListener((message) => {
            if (message.type === "agent-profiles-changed") {
                loadData();
            }
        });
        return () => {
            removeListener();
        };
    }, [editContext?.addSocketMessageListener, loadData]);
    // Handle external agent selection
    useEffect(() => {
        if (externalAgent) {
            setAgent(externalAgent);
            setAgentKey((prev) => prev + 1);
            setInitialPrompt(undefined);
            setInitialPromptDelivered(true);
            setIsTerminalVisible(true);
        }
    }, [externalAgent]);
    // Mark the initial prompt as delivered after the first render that
    // exposes it to AgentTerminal. AgentTerminal captures the prompt in a
    // closure when its auto-send effect runs (children-first effect order),
    // so flipping this flag immediately after that is safe and prevents a
    // workspace-switch remount from re-passing the same prompt.
    useEffect(() => {
        if (isTerminalVisible &&
            initialPrompt !== undefined &&
            initialPrompt !== "" &&
            !initialPromptDelivered) {
            setInitialPromptDelivered(true);
        }
    }, [
        isTerminalVisible,
        initialPrompt,
        initialPromptDelivered,
        setInitialPromptDelivered,
    ]);
    // Handle revealing the terminal
    const handleRevealTerminal = useCallback(() => {
        if (typeof document !== "undefined" &&
            document.startViewTransition) {
            document.startViewTransition(() => {
                flushSync(() => {
                    setIsTerminalVisible(true);
                });
            });
        }
        else {
            startTransition(() => {
                setIsTerminalVisible(true);
            });
        }
    }, []);
    // Handle starting a conversation with a prompt
    const handleStartWithPrompt = useCallback((prompt) => {
        if (!profile || isUploading)
            return;
        const performUpdate = () => {
            // Clear any previous state first
            setInitialPrompt(undefined);
            setInitialPromptDelivered(false);
            // Keep the current draft when splash attachments were uploaded to it.
            if (attachedDocs.length === 0) {
                createNewAgent(profile);
            }
            setInitialPrompt(prompt);
            setAgentKey((prev) => prev + 1);
            setIsTerminalVisible(true);
        };
        if (typeof document !== "undefined" &&
            document.startViewTransition) {
            document.startViewTransition(() => {
                flushSync(() => {
                    performUpdate();
                });
            });
        }
        else {
            performUpdate();
        }
    }, [profile, isUploading, attachedDocs.length, createNewAgent]);
    const uploadFiles = useCallback(async (files) => {
        if (!agent || !profile?.enableDocumentUpload || !files)
            return;
        const list = Array.from(files);
        if (list.length === 0)
            return;
        const maxBytes = (profile.maxDocumentSizeMB ?? 10) * 1024 * 1024;
        setUploadError(null);
        setIsUploading(true);
        try {
            for (const file of list) {
                if (file.size > maxBytes) {
                    setUploadError(`"${file.name}" exceeds ${profile.maxDocumentSizeMB ?? 10} MB`);
                    continue;
                }
                const result = await uploadDocument(agent.id, file, profile.id);
                if (!result.success) {
                    setUploadError(result.error || `Failed to upload "${file.name}"`);
                }
            }
        }
        finally {
            setIsUploading(false);
        }
    }, [agent, profile]);
    // Sync attached docs from server when the active agent changes.
    useEffect(() => {
        if (!agent?.id || !profile?.enableDocumentUpload) {
            setAttachedDocs([]);
            return;
        }
        let cancelled = false;
        void getAgentDocuments(agent.id).then((res) => {
            if (cancelled)
                return;
            if (res.success && res.documents)
                setAttachedDocs(res.documents);
        });
        return () => {
            cancelled = true;
        };
    }, [agent?.id, profile?.enableDocumentUpload]);
    // Listen for upload/change events to keep chips in sync.
    useEffect(() => {
        if (!agent?.id)
            return;
        const handleUploaded = (event) => {
            const detail = event.detail;
            if (!detail || detail.agentId !== agent.id)
                return;
            setAttachedDocs((prev) => {
                const existing = prev.findIndex((d) => d.id === detail.document.id);
                if (existing === -1)
                    return [detail.document, ...prev];
                const next = [...prev];
                next[existing] = detail.document;
                return next;
            });
        };
        const handleChanged = (event) => {
            const detail = event.detail;
            if (!detail || detail.agentId !== agent.id)
                return;
            void getAgentDocuments(agent.id).then((res) => {
                if (res.success && res.documents)
                    setAttachedDocs(res.documents);
            });
        };
        window.addEventListener(AGENT_DOCUMENT_UPLOADED_EVENT, handleUploaded);
        window.addEventListener(AGENT_DOCUMENTS_CHANGED_EVENT, handleChanged);
        return () => {
            window.removeEventListener(AGENT_DOCUMENT_UPLOADED_EVENT, handleUploaded);
            window.removeEventListener(AGENT_DOCUMENTS_CHANGED_EVENT, handleChanged);
        };
    }, [agent?.id]);
    const handleRemoveAttachment = useCallback(async (documentId) => {
        setUploadError(null);
        const result = await deleteDocument(documentId);
        if (result.success) {
            setAttachedDocs((prev) => prev.filter((d) => d.id !== documentId));
        }
        else {
            setUploadError(result.error || "Failed to remove attachment");
        }
    }, []);
    const handleInputPaste = useCallback((e) => {
        if (!profile?.enableDocumentUpload)
            return;
        const items = e.clipboardData?.items;
        if (!items)
            return;
        const files = [];
        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (!item)
                continue;
            if (item.type.indexOf("image") !== -1 || item.kind === "file") {
                const file = item.getAsFile();
                if (!file)
                    continue;
                if (file.name === "image.png" && item.type.indexOf("image") !== -1) {
                    const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
                    const extension = item.type.split("/")[1] || "png";
                    files.push(new File([file], `pasted-image-${timestamp}.${extension}`, {
                        type: file.type,
                    }));
                }
                else {
                    files.push(file);
                }
            }
        }
        if (files.length > 0) {
            e.preventDefault();
            void uploadFiles(files);
        }
    }, [profile, uploadFiles]);
    const handleDragOver = useCallback((e) => {
        if (!profile?.enableDocumentUpload)
            return;
        e.preventDefault();
        e.stopPropagation();
        if (!isDragOver)
            setIsDragOver(true);
    }, [profile, isDragOver]);
    const handleDragLeave = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);
    }, []);
    const handleDrop = useCallback((e) => {
        if (!profile?.enableDocumentUpload)
            return;
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            void uploadFiles(e.dataTransfer.files);
        }
    }, [profile, uploadFiles]);
    // Handle submit from smart input
    const handleSubmitInput = (e) => {
        e?.preventDefault();
        if (!inputValue.trim() || isUploading)
            return;
        handleStartWithPrompt(inputValue);
        setInputValue("");
    };
    // Handle start over
    const handleStartOver = useCallback(async () => {
        if (!profile || !agent)
            return;
        try {
            // Close the current agent first
            await closeAgent(agent.id);
        }
        catch (error) {
            console.error("Failed to close agent:", error);
        }
        const performUpdate = () => {
            // Create new agent and force re-render
            createNewAgent(profile);
            setAgentKey((prev) => prev + 1);
            setInitialPrompt(undefined);
            setInitialPromptDelivered(false);
        };
        if (typeof document !== "undefined" &&
            document.startViewTransition) {
            document.startViewTransition(() => {
                flushSync(() => {
                    performUpdate();
                });
            });
        }
        else {
            performUpdate();
        }
    }, [profile, agent, createNewAgent]);
    // Handle agent updates from AgentTerminal (e.g., name changes)
    const handleAgentUpdate = useCallback((updates) => {
        setAgent((prev) => (prev ? { ...prev, ...updates } : prev));
    }, []);
    // Handle close
    const handleClose = useCallback(async () => {
        if (!profile)
            return;
        const performUpdate = () => {
            setIsTerminalVisible(false);
            setInitialPrompt(undefined);
            setInitialPromptDelivered(false);
            createNewAgent(profile);
            setAgentKey((prev) => prev + 1);
        };
        void loadRecentAgents(profile, { force: true });
        if (typeof document !== "undefined" &&
            document.startViewTransition) {
            document.startViewTransition(() => {
                flushSync(() => {
                    performUpdate();
                });
            });
        }
        else {
            performUpdate();
        }
    }, [createNewAgent, loadRecentAgents, profile]);
    if (isLoading) {
        return (_jsx("div", { className: cn("flex items-center justify-center rounded-2xl border border-white/10 bg-white/3 p-12 shadow-xl", className), children: _jsx(Loader2, { className: "text-highlight-100 h-6 w-6 animate-spin" }) }));
    }
    const renderAttachments = (variant) => {
        if (!profile?.enableDocumentUpload)
            return null;
        if (attachedDocs.length === 0 && !uploadError && !isUploading)
            return null;
        return (_jsxs("div", { className: cn("flex flex-col gap-2", variant === "overview"
                ? "-mt-4"
                : "border-b border-white/10 bg-white/5 px-5 py-3"), children: [(attachedDocs.length > 0 || isUploading) && (_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [attachedDocs.map((doc) => {
                            const isImage = doc.contentType?.startsWith("image/") ||
                                /\.(png|jpe?g|gif|webp)$/i.test(doc.fileName);
                            return (_jsxs("div", { className: "group text-neutral-grey-50 flex max-w-[260px] items-center gap-2 rounded-full border border-white/10 bg-white/5 py-1.5 pr-1.5 pl-3 text-xs", children: [isImage ? (_jsx(ImageIcon, { className: "text-highlight-100 h-3.5 w-3.5 shrink-0", strokeWidth: 1.5 })) : (_jsx(FileText, { className: "text-highlight-100 h-3.5 w-3.5 shrink-0", strokeWidth: 1.5 })), _jsx("span", { className: "truncate", title: doc.fileName, children: doc.fileName }), _jsx("button", { type: "button", onClick: () => handleRemoveAttachment(doc.id), "aria-label": `Remove ${doc.fileName}`, className: "text-neutral-grey-50 flex h-5 w-5 items-center justify-center rounded-full transition-colors hover:bg-white/10 hover:text-white", children: _jsx(X, { className: "h-3 w-3", strokeWidth: 2 }) })] }, doc.id));
                        }), isUploading && (_jsxs("span", { className: "text-neutral-grey-50 flex items-center gap-1.5 text-xs", children: [_jsx(Loader2, { className: "h-3 w-3 animate-spin" }), "Uploading..."] })), variant === "terminal" && (_jsxs("button", { type: "button", onClick: () => fileInputRef.current?.click(), disabled: isUploading, className: "text-neutral-grey-50 hover:border-highlight-100/40 flex items-center gap-1.5 rounded-full border border-dashed border-white/15 px-3 py-1.5 text-xs transition-colors hover:text-white disabled:opacity-50", children: [_jsx(Paperclip, { className: "h-3 w-3", strokeWidth: 1.75 }), "Attach"] }))] })), uploadError && (_jsx("p", { className: "text-feedback-red text-xs", children: uploadError }))] }));
    };
    if (!agent || !profile) {
        return (_jsx("div", { className: cn("flex items-center justify-center rounded-2xl border border-white/10 bg-white/3 p-12 shadow-xl", className), children: _jsx("p", { className: "text-neutral-grey-50 text-sm", children: "Assistant unavailable. Please try again later." }) }));
    }
    return (_jsxs("div", { className: cn("flex flex-col overflow-hidden transition-all duration-300", !isTerminalVisible ? "rounded-2xl" : "rounded-xl shadow-2xl", className), style: { viewTransitionName: "assistant-chat-container" }, children: [profile.enableDocumentUpload && (_jsx("input", { ref: fileInputRef, type: "file", multiple: true, className: "hidden", onChange: (e) => {
                    void uploadFiles(e.target.files);
                    e.target.value = "";
                }, accept: ".txt,.md,.pdf,.docx,.xlsx,.pptx,.csv,.json,.xml,.cs,.js,.ts,.tsx,.jsx,.py,.java,.cpp,.c,.h,.hpp,.cshtml,.razor,.vb,.php,.rb,.go,.rs,.swift,.kt,.scala,.sql,.sh,.ps1,.bat,.yaml,.yml,.png,.jpg,.jpeg,.gif,.webp" })), !isTerminalVisible && (_jsxs("div", { className: "flex flex-col gap-8", children: [_jsx("div", { className: "group relative", style: { viewTransitionName: "assistant-chat-box" }, onDragOver: handleDragOver, onDragEnter: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop, children: _jsxs("form", { onSubmit: handleSubmitInput, className: "relative flex items-center", children: [_jsx("div", { className: "absolute left-5", children: _jsx(ParheliaIconWhite, { size: 24 }) }), _jsx("input", { ref: inputRef, type: "text", placeholder: "Ask Parhelia anything...", value: inputValue, onChange: (e) => setInputValue(e.target.value), onPaste: handleInputPaste, onFocus: () => {
                                        void loadRecentAgents(profile);
                                    }, style: { viewTransitionName: "assistant-chat-input" }, className: cn("placeholder:text-neutral-grey-50 h-16 w-full rounded-2xl border bg-white/5 text-lg text-white shadow-2xl transition-all duration-300 focus:bg-white/8 focus:shadow-[0_0_30px_-5px_color-mix(in_srgb,var(--color-highlight-100)_30%,transparent)] focus:outline-none", profile.enableDocumentUpload ? "pr-28 pl-14" : "pr-16 pl-14", isDragOver
                                        ? "border-highlight-100/60 bg-highlight-100/10"
                                        : "focus:border-highlight-100/40 border-white/10") }), profile.enableDocumentUpload && (_jsx("button", { type: "button", onClick: () => fileInputRef.current?.click(), disabled: isUploading, "aria-label": "Attach documents", title: "Attach documents", className: "text-neutral-grey-50 absolute right-14 flex h-10 w-10 items-center justify-center rounded-xl transition-colors hover:bg-white/10 hover:text-white disabled:opacity-50", children: isUploading ? (_jsx(Loader2, { className: "h-5 w-5 animate-spin" })) : (_jsx(Paperclip, { className: "h-5 w-5", strokeWidth: 1.75 })) })), _jsx("button", { type: "submit", disabled: !inputValue.trim() || isUploading, className: "bg-highlight-100 hover:bg-highlight-100 disabled:text-neutral-grey-50 absolute right-3 flex h-10 w-10 items-center justify-center rounded-xl text-white shadow-lg transition-colors disabled:bg-white/5", children: _jsx(ArrowRight, { className: "h-5 w-5", strokeWidth: 2 }) })] }) }), renderAttachments("overview"), _jsx("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", children: samplePrompts.map((item, idx) => (_jsxs("button", { onClick: () => handleStartWithPrompt(item.prompt), className: "group flex flex-col items-start rounded-xl border border-white/10 bg-white/3 p-5 text-left transition-all hover:bg-white/[0.07]", children: [_jsx("span", { className: "text-neutral-grey-15 group-hover:text-highlight-100 text-sm font-semibold transition-colors", children: item.title }), _jsx("span", { className: "text-neutral-grey-50 mt-1 line-clamp-1 text-xs", children: item.description })] }, idx))) }), (isLoadingRecentAgents ||
                        !hasLoadedRecentAgents ||
                        recentAgents.length > 0) && (_jsxs("div", { className: "flex flex-col gap-3", children: [_jsxs("div", { className: "text-neutral-grey-50 flex items-center gap-2 px-1 text-[10px] font-bold tracking-[0.2em]", children: [_jsx(History, { className: "h-3 w-3" }), "Recent Parhelia Conversations"] }), !hasLoadedRecentAgents && !isLoadingRecentAgents && (_jsx("button", { onClick: () => {
                                    void loadRecentAgents(profile);
                                }, className: "text-neutral-grey-50 hover:border-highlight-100/30 hover:text-neutral-grey-15 w-fit rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs transition-all hover:bg-white/10", children: "Load recent conversations" })), isLoadingRecentAgents && (_jsxs("div", { className: "text-neutral-grey-50 flex items-center gap-2 px-1 text-xs", children: [_jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }), "Loading recent conversations..."] })), recentAgents.length > 0 && (_jsxs("div", { className: "flex flex-wrap gap-2", children: [recentAgents.slice(0, 3).map((ra) => (_jsx("button", { onClick: () => {
                                            setAgent(ra);
                                            setIsTerminalVisible(true);
                                            setAgentKey((prev) => prev + 1);
                                            setInitialPrompt(undefined);
                                            setInitialPromptDelivered(true);
                                        }, className: "text-neutral-grey-50 hover:border-highlight-100/30 max-w-[200px] truncate overflow-hidden rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs whitespace-nowrap transition-all hover:bg-white/10", children: ra.name }, ra.id))), recentAgents.length > 3 && (_jsx("button", { onClick: () => {
                                            editContext?.switchWorkspace("agents");
                                        }, className: "text-highlight-100 hover:text-highlight-100 rounded-full px-3 py-1.5 text-xs font-medium transition-colors", children: "View All Agents" }))] }))] }))] })), isTerminalVisible && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex items-center justify-between border-b border-white/10 bg-white/5 px-5 py-3.5", style: { viewTransitionName: "assistant-chat-box" }, children: [_jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-3", children: [_jsx("div", { className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-white/5 bg-white/5 shadow-inner", children: _jsx(ParheliaIconWhite, { size: 22 }) }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("span", { className: "text-highlight-100/80 truncate text-[10px] font-bold tracking-[0.2em]", children: agent.description || "Parhelia AI" }), _jsx("span", { className: "text-neutral-grey-5 text-sm font-semibold tracking-tight", children: agent.name || profile.agentName || "Assistant" })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsxs(Button, { variant: "ghost", size: "sm", onClick: handleStartOver, className: "text-neutral-grey-50 h-9 gap-2 rounded-xl px-4 text-xs font-medium transition-all hover:bg-white/10 hover:text-white", children: [_jsx(RotateCcw, { className: "h-4 w-4", strokeWidth: 1.5 }), "New Chat"] }), _jsx("div", { className: "mx-1 h-5 w-px bg-white/10" }), _jsx(CloseButton, { onClick: handleClose, className: "text-neutral-grey-50 hover:text-neutral-grey-15 hover:bg-white/10", label: "Close" })] })] }), renderAttachments("terminal"), (() => {
                        // Only pass the initial prompt the first time the terminal is
                        // mounted for this prompt. After delivery, a workspace-switch
                        // remount re-mounts AgentTerminal with a fresh initialPromptSentRef
                        // — without this guard it would auto-submit the same prompt again
                        // before getAgent finishes loading history, producing a duplicate.
                        const promptForTerminal = initialPromptDelivered
                            ? undefined
                            : initialPrompt;
                        return (_jsx("div", { className: "bg-neutral-grey-5/95 flex-1 overflow-hidden", "data-testid": "splash-agent-terminal", "data-agent-id": agent.id, children: _jsx("div", { className: "animate-view-slide-in h-[650px]", children: _jsx(AgentTerminal, { agentStub: agent, initialMetadata: {
                                        profile: profile.name,
                                        additionalData: {
                                            profileId: profile.id,
                                            profileName: profile.name,
                                            initialPrompt: promptForTerminal,
                                        },
                                    }, profiles: profiles, isActive: true, compact: true, hideContext: true, hideBottomControls: true, showStatusBar: true, showAgentConfigControls: true, hideGreeting: true, className: "h-full", initialPrompt: promptForTerminal, onAgentUpdate: handleAgentUpdate }) }, agentKey) }));
                    })()] }))] }));
};
//# sourceMappingURL=ParheliaAssistantChat.js.map