'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useRef, useCallback, useState, useMemo } from 'react';
import { useChat } from '@ai-sdk/react';
import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls } from 'ai';
import { ArrowUp, Square, Image as ImageIcon, X } from '@phosphor-icons/react';
import { Button } from '@/components/ui/button';
import { encodeCardMessage, detectErrorType } from './cards';
import { buildEndpointIndex, searchEndpoints, findRequestById, formatRequestForAI } from '@/lib/api-docs/agent/indexer';
import { ChatMessage, TypingIndicator } from './chat-message';
import { cn } from '@/lib/utils';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useModeContext, useNotes, useWorkspace } from '@/lib/api-docs/code-editor';
import { useCurrentRequestPayload, useSendTrigger } from '@/lib/api-docs/playground/context';
import { useSuggestions } from '@/lib/api-docs/agent/use-suggestions';
/**
 * Custom transport that intercepts streaming events for write_file tool
 * Wraps DefaultChatTransport and intercepts the stream to extract write_file content
 */ function createStreamingTransport(config, callbacks) {
    const transport = new DefaultChatTransport(config);
    // Track active write_file tool calls
    const activeWriteFiles = new Map();
    const toolInputBuffers = new Map();
    // Override the fetch to intercept the stream
    const originalFetch = transport['fetch'] || globalThis.fetch;
    transport['fetch'] = async (input, init)=>{
        const response = await originalFetch(input, init);
        if (!response.body) return response;
        // Create a transform stream to intercept and process the SSE events
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        const processedStream = new ReadableStream({
            async start (controller) {
                try {
                    while(true){
                        const { done, value } = await reader.read();
                        if (done) {
                            // Stream ended - close all active write_files
                            for (const [toolCallId] of activeWriteFiles){
                                callbacks.onWriteFileEnd(toolCallId);
                            }
                            activeWriteFiles.clear();
                            toolInputBuffers.clear();
                            controller.close();
                            break;
                        }
                        // Pass through the original data
                        controller.enqueue(value);
                        // Parse the SSE events for write_file content
                        buffer += decoder.decode(value, {
                            stream: true
                        });
                        const lines = buffer.split('\n');
                        buffer = lines.pop() || ''; // Keep incomplete line in buffer
                        for (const line of lines){
                            if (line.startsWith('data: ')) {
                                const data = line.slice(6);
                                if (data === '[DONE]') continue;
                                try {
                                    const event = JSON.parse(data);
                                    // Handle tool-input-start for write_file
                                    if (event.type === 'tool-input-start' && event.toolName === 'write_file') {
                                        toolInputBuffers.set(event.toolCallId, '');
                                    }
                                    // Handle tool-input-delta for write_file
                                    if (event.type === 'tool-input-delta' && toolInputBuffers.has(event.toolCallId)) {
                                        const currentBuffer = toolInputBuffers.get(event.toolCallId) || '';
                                        const newBuffer = currentBuffer + (event.inputTextDelta || '');
                                        toolInputBuffers.set(event.toolCallId, newBuffer);
                                        // Try to parse partial JSON to extract content
                                        try {
                                            // Look for "content": " and extract what comes after
                                            const contentMatch = newBuffer.match(/"content":\s*"((?:[^"\\]|\\.)*)/);
                                            if (contentMatch) {
                                                const escapedContent = contentMatch[1];
                                                // Unescape the content
                                                const content = escapedContent.replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\r/g, '\r').replace(/\\"/g, '"').replace(/\\\\/g, '\\');
                                                const activeWrite = activeWriteFiles.get(event.toolCallId);
                                                // Also try to extract path
                                                const pathMatch = newBuffer.match(/"path":\s*"([^"]+)"/);
                                                const path = pathMatch?.[1] || '';
                                                if (!activeWrite && path) {
                                                    // First time seeing content with path - start streaming
                                                    activeWriteFiles.set(event.toolCallId, {
                                                        path,
                                                        lastContent: content
                                                    });
                                                    callbacks.onWriteFileStart(event.toolCallId, path);
                                                    callbacks.onWriteFileDelta(event.toolCallId, path, content);
                                                } else if (activeWrite && content.length > activeWrite.lastContent.length) {
                                                    // Content grew - send new content
                                                    activeWrite.lastContent = content;
                                                    callbacks.onWriteFileDelta(event.toolCallId, activeWrite.path, content);
                                                }
                                            }
                                        } catch  {
                                        // JSON not complete yet, continue buffering
                                        }
                                    }
                                    // Handle tool-input-available (complete)
                                    if (event.type === 'tool-input-available' && event.toolName === 'write_file') {
                                        const activeWrite = activeWriteFiles.get(event.toolCallId);
                                        if (activeWrite) {
                                            callbacks.onWriteFileEnd(event.toolCallId);
                                            activeWriteFiles.delete(event.toolCallId);
                                        }
                                        toolInputBuffers.delete(event.toolCallId);
                                    }
                                } catch  {
                                // Invalid JSON, skip
                                }
                            }
                        }
                    }
                } catch (err) {
                    controller.error(err);
                }
            }
        });
        // Return new response with the processed stream
        return new Response(processedStream, {
            headers: response.headers,
            status: response.status,
            statusText: response.statusText
        });
    };
    return transport;
}
// Storage key for chat history
const CHAT_STORAGE_KEY = 'brainfish-agent-chat';
export function AgentChat({ collection, currentEndpoint, onNavigate, onPrefill, apiSummary, debugContext, onDebugContextConsumed, explainContext, onExplainContextConsumed, onOpenGlobalAuth, onNavigateToAuthTab, onNavigateToParamsTab, onNavigateToBodyTab, onNavigateToHeadersTab, onNavigateToDocSection, onNavigateToDocPage, onHasMessagesChange }) {
    const messagesEndRef = useRef(null);
    const textareaRef = useRef(null);
    const processedDebugRef = useRef(null);
    // Local input state (controlled by us, not useChat)
    const [inputValue, setInputValue] = useState('');
    // Image upload state
    const [selectedImages, setSelectedImages] = useState([]);
    const fileInputRef = useRef(null);
    // Mode context for notes, API client, and docs
    const { switchToNotes, switchToApiClient, switchToDocs, setActiveFilePath, setStreamingContent, triggerNotesRefresh } = useModeContext();
    // Get workspace for notes
    const apiSpecUrl = process.env.NEXT_PUBLIC_OPENAPI_URL || collection.name || 'default';
    const { workspace } = useWorkspace(apiSpecUrl, collection.name);
    const { notes, createNote, updateNote, deleteNote, deleteAllNotes, refresh: refreshNotes } = useNotes(workspace?.id || null);
    // Build endpoint index for search
    const endpointIndex = useMemo(()=>buildEndpointIndex(collection), [
        collection
    ]);
    // Suggestions - use shared hook
    const { suggestions, isLoading: loadingSuggestions } = useSuggestions({
        currentEndpoint: currentEndpoint ? {
            id: currentEndpoint.id,
            name: currentEndpoint.name
        } : null,
        endpointIndex
    });
    const [showSuggestions, setShowSuggestions] = useState(true);
    // Current request payload from playground
    const { currentRequestPayload } = useCurrentRequestPayload();
    // Send trigger - to invoke playground's send button
    const { requestSend } = useSendTrigger();
    // Handler to open a file from chat (when user clicks on file name in tool display)
    const handleOpenFile = useCallback((path)=>{
        switchToNotes(path); // Pass path directly to avoid URL reset
    }, [
        switchToNotes
    ]);
    // Track last streamed content to compute deltas
    const lastStreamedContent = useRef(new Map());
    // Build documentation index for search (including nested pages)
    const docIndex = useMemo(()=>{
        if (!collection.docGroups) return [];
        const pages = [];
        // Helper to recursively add pages
        const addPages = (pageList, groupTitle, groupId)=>{
            for (const page of pageList){
                pages.push({
                    id: page.id,
                    slug: page.slug,
                    title: page.title,
                    description: page.description || '',
                    group: groupTitle,
                    groupId: groupId
                });
                // Also add children if present
                if (page.children && page.children.length > 0) {
                    addPages(page.children, page.title || groupTitle, groupId);
                }
            }
        };
        for (const group of collection.docGroups){
            addPages(group.pages, group.title, group.id);
        }
        return pages;
    }, [
        collection
    ]);
    // Build changelog index for search
    const changelogIndex = useMemo(()=>{
        if (!collection.changelogReleases) return [];
        return collection.changelogReleases.map((release)=>({
                version: release.version,
                date: release.date,
                title: release.title,
                slug: release.slug
            }));
    }, [
        collection
    ]);
    // Create streaming transport with callbacks
    const transport = useMemo(()=>{
        return createStreamingTransport({
            api: '/api/chat',
            body: {
                endpointIndex,
                docIndex,
                changelogIndex,
                currentEndpointId: currentEndpoint?.id,
                apiSummary: apiSummary || undefined
            }
        }, {
            onWriteFileStart: (toolCallId, path)=>{
                lastStreamedContent.current.set(toolCallId, '');
                setStreamingContent({
                    path,
                    content: '',
                    isStreaming: true
                });
                // Navigate to the file being written
                setActiveFilePath(path);
            },
            onWriteFileDelta: (toolCallId, path, fullContent)=>{
                // Update streaming content with full content (already includes all previous)
                setStreamingContent({
                    path,
                    content: fullContent,
                    isStreaming: true
                });
            },
            onWriteFileEnd: (toolCallId)=>{
                lastStreamedContent.current.delete(toolCallId);
            // Don't clear streaming content immediately - let the final save do it
            }
        });
    }, [
        endpointIndex,
        docIndex,
        changelogIndex,
        currentEndpoint?.id,
        apiSummary,
        setStreamingContent,
        setActiveFilePath
    ]);
    // Chat hook with custom streaming transport
    const { messages, status, sendMessage, addToolOutput, setMessages, stop } = useChat({
        id: 'agent-chat',
        transport,
        // Automatically submit when all tool calls are complete
        sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
        // Handle client-side tool execution
        async onToolCall ({ toolCall }) {
            if ('dynamic' in toolCall && toolCall.dynamic) {
                return;
            }
            const { toolName, toolCallId, input: toolInput } = toolCall;
            try {
                // === UNIFIED SEARCH TOOL ===
                // Searches across docs, endpoints, changelog, and future content types
                if (toolName === 'search') {
                    const { query, type = 'all' } = toolInput;
                    const results = [];
                    // Tokenize query
                    const queryTokens = query.toLowerCase().split(/\s+/).filter((t)=>t.length > 1);
                    const queryLower = query.toLowerCase();
                    // Search changelog if type is 'all' or 'changelog'
                    const changelogReleases = collection.changelogReleases || [];
                    if ((type === 'all' || type === 'changelog') && changelogReleases.length > 0) {
                        // Check for keywords that indicate changelog intent
                        const changelogKeywords = [
                            'release',
                            'changelog',
                            'version',
                            'update',
                            'latest',
                            'new',
                            'what\'s new',
                            'history'
                        ];
                        const isChangelogQuery = changelogKeywords.some((kw)=>queryLower.includes(kw));
                        for (const release of changelogReleases){
                            let score = 0;
                            const versionLower = release.version.toLowerCase();
                            const titleLower = release.title.toLowerCase();
                            const dateLower = release.date.toLowerCase();
                            // Boost score for changelog-related queries
                            if (isChangelogQuery) score += 50;
                            if (versionLower.includes(queryLower)) score += 100;
                            if (titleLower.includes(queryLower)) score += 80;
                            if (queryLower.includes('latest') && release === changelogReleases[0]) score += 150;
                            for (const token of queryTokens){
                                if (versionLower.includes(token)) score += 30;
                                if (titleLower.includes(token)) score += 25;
                                if (dateLower.includes(token)) score += 20;
                            }
                            if (score > 0) {
                                // Extract just the version from the slug (e.g., "changelog/v1.2.0" -> "v1.2.0")
                                const versionId = release.slug.replace(/^changelog\//, '');
                                results.push({
                                    type: 'changelog',
                                    id: versionId,
                                    title: `${release.version} - ${release.title}`,
                                    description: `Released ${release.date}`,
                                    date: release.date,
                                    group: 'Changelog',
                                    score
                                });
                            }
                        }
                    }
                    // Search docs if type is 'all' or 'docs'
                    if ((type === 'all' || type === 'docs') && docIndex && docIndex.length > 0) {
                        for (const doc of docIndex){
                            let score = 0;
                            const titleLower = doc.title.toLowerCase();
                            const descLower = doc.description.toLowerCase();
                            const slugLower = doc.slug.toLowerCase();
                            if (titleLower.includes(queryLower)) score += 100;
                            if (slugLower.includes(queryLower)) score += 80;
                            if (descLower.includes(queryLower)) score += 60;
                            for (const token of queryTokens){
                                if (titleLower.includes(token)) score += 20;
                                if (slugLower.includes(token)) score += 25;
                                if (descLower.includes(token)) score += 15;
                            }
                            if (score > 0) {
                                results.push({
                                    type: 'doc',
                                    id: doc.slug,
                                    title: doc.title,
                                    description: doc.description,
                                    group: doc.group,
                                    score
                                });
                            }
                        }
                    }
                    // Search endpoints if type is 'all' or 'endpoints'
                    if ((type === 'all' || type === 'endpoints') && endpointIndex && endpointIndex.length > 0) {
                        for (const ep of endpointIndex){
                            let score = 0;
                            const nameLower = ep.name.toLowerCase();
                            const pathLower = ep.path.toLowerCase();
                            const descLower = (ep.description || '').toLowerCase();
                            if (nameLower.includes(queryLower)) score += 100;
                            if (pathLower.includes(queryLower)) score += 80;
                            if (descLower.includes(queryLower)) score += 60;
                            for (const token of queryTokens){
                                if (nameLower.includes(token)) score += 20;
                                if (pathLower.includes(token)) score += 25;
                                if (descLower.includes(token)) score += 15;
                                if (ep.method.toLowerCase() === token) score += 30;
                            }
                            if (score > 0) {
                                results.push({
                                    type: 'endpoint',
                                    id: ep.id,
                                    title: ep.name,
                                    description: ep.description || undefined,
                                    method: ep.method,
                                    path: ep.path,
                                    score
                                });
                            }
                        }
                    }
                    // Sort by score and limit
                    const sortedResults = results.sort((a, b)=>b.score - a.score).slice(0, 10)// eslint-disable-next-line @typescript-eslint/no-unused-vars
                    .map(({ score, ...rest })=>rest);
                    addToolOutput({
                        tool: 'search',
                        toolCallId,
                        output: {
                            results: sortedResults,
                            message: sortedResults.length > 0 ? `Found ${sortedResults.length} result(s)` : 'No results found. Try different keywords.'
                        }
                    });
                }
                // === UNIFIED NAVIGATE TOOL ===
                // Navigates to docs, endpoints, changelog, sections, and future content types
                if (toolName === 'navigate') {
                    const { type, id, title } = toolInput;
                    if (type === 'doc') {
                        switchToDocs();
                        if (onNavigateToDocPage) {
                            onNavigateToDocPage(id);
                        }
                        addToolOutput({
                            tool: 'navigate',
                            toolCallId,
                            output: {
                                success: true,
                                type: 'doc',
                                id,
                                title,
                                message: `Opened ${title || id}`
                            }
                        });
                    } else if (type === 'changelog') {
                        // Navigate to changelog tab and scroll to specific release
                        // handleSelectDocPage handles the scrolling automatically
                        switchToDocs();
                        if (onNavigateToDocPage) {
                            onNavigateToDocPage(`changelog/${id}`);
                        }
                        addToolOutput({
                            tool: 'navigate',
                            toolCallId,
                            output: {
                                success: true,
                                type: 'changelog',
                                id,
                                title,
                                message: `Opened changelog ${title || id}`
                            }
                        });
                    } else if (type === 'endpoint') {
                        switchToDocs();
                        onNavigate(id);
                        const endpoint = endpointIndex.find((e)=>e.id === id);
                        addToolOutput({
                            tool: 'navigate',
                            toolCallId,
                            output: {
                                success: true,
                                type: 'endpoint',
                                id,
                                title: endpoint?.name || title,
                                method: endpoint?.method,
                                message: `Opened ${endpoint?.name || title || id}`
                            }
                        });
                    } else if (type === 'section') {
                        // Scroll to section on current page with retry for newly rendered content
                        const scrollToSection = ()=>{
                            const headings = document.querySelectorAll('.docs-content h1[id], .docs-content h2[id], .docs-content h3[id], .docs-content h4[id], .docs-prose h1[id], .docs-prose h2[id], .docs-prose h3[id], .docs-prose h4[id], .docs-page h1[id], .docs-page h2[id], .docs-page h3[id], .docs-page h4[id]');
                            for (const heading of headings){
                                const text = heading.textContent?.toLowerCase() || '';
                                const headingId = heading.getAttribute('id') || '';
                                if (text.includes(id.toLowerCase()) || headingId.includes(id.toLowerCase())) {
                                    heading.scrollIntoView({
                                        behavior: 'smooth',
                                        block: 'start'
                                    });
                                    return true;
                                }
                            }
                            return false;
                        };
                        // Try immediately, then retry with delays if not found
                        let found = scrollToSection();
                        if (!found) {
                            // Retry after a short delay (page might still be rendering)
                            setTimeout(()=>{
                                found = scrollToSection();
                                if (!found) {
                                    // Final retry after longer delay
                                    setTimeout(()=>{
                                        scrollToSection();
                                    }, 300);
                                }
                            }, 100);
                        }
                        addToolOutput({
                            tool: 'navigate',
                            toolCallId,
                            output: {
                                success: true,
                                type: 'section',
                                id,
                                message: `Scrolled to ${id}`
                            }
                        });
                    }
                }
                // === LEGACY TOOL HANDLERS (for backwards compatibility) ===
                // These can be removed once the unified tools are fully adopted
                if (toolName === 'search_docs') {
                    // Redirect to unified search
                    const { query } = toolInput;
                    const results = docIndex.filter((doc)=>doc.title.toLowerCase().includes(query.toLowerCase()) || doc.slug.toLowerCase().includes(query.toLowerCase())).slice(0, 10);
                    addToolOutput({
                        tool: 'search_docs',
                        toolCallId,
                        output: {
                            results,
                            message: `Found ${results.length} result(s)`
                        }
                    });
                }
                if (toolName === 'search_endpoints') {
                    const { query, method } = toolInput;
                    const results = searchEndpoints(endpointIndex, query, method);
                    addToolOutput({
                        tool: 'search_endpoints',
                        toolCallId,
                        output: results
                    });
                }
                if (toolName === 'navigate_to_doc_page') {
                    const { slug, title } = toolInput;
                    switchToDocs();
                    if (onNavigateToDocPage) {
                        onNavigateToDocPage(slug);
                    }
                    addToolOutput({
                        tool: 'navigate_to_doc_page',
                        toolCallId,
                        output: {
                            success: true,
                            slug,
                            title,
                            message: `Navigated to "${title}"`
                        }
                    });
                }
                if (toolName === 'navigate_to_endpoint') {
                    const { endpointId } = toolInput;
                    switchToDocs();
                    onNavigate(endpointId);
                    const endpoint = endpointIndex.find((e)=>e.id === endpointId);
                    addToolOutput({
                        tool: 'navigate_to_endpoint',
                        toolCallId,
                        output: {
                            success: true,
                            endpoint
                        }
                    });
                }
                if (toolName === 'navigate_to_doc_section') {
                    const { sectionId, sectionName } = toolInput;
                    switchToDocs();
                    if (onNavigateToDocSection) {
                        onNavigateToDocSection(sectionId);
                    }
                    addToolOutput({
                        tool: 'navigate_to_doc_section',
                        toolCallId,
                        output: {
                            success: true,
                            sectionId,
                            sectionName
                        }
                    });
                }
                // Handle scroll_to_section tool - scroll within current page
                if (toolName === 'scroll_to_section') {
                    const { query } = toolInput;
                    // Find matching heading in the current page
                    const findAndScrollToSection = ()=>{
                        const queryLower = query.toLowerCase();
                        const headings = document.querySelectorAll('.docs-content h1[id], .docs-content h2[id], .docs-content h3[id], .docs-content h4[id], .docs-content h5[id], .docs-content h6[id], .docs-prose h1[id], .docs-prose h2[id], .docs-prose h3[id], .docs-prose h4[id], .docs-prose h5[id], .docs-prose h6[id], .docs-page h1[id], .docs-page h2[id], .docs-page h3[id], .docs-page h4[id], .docs-page h5[id], .docs-page h6[id]');
                        let bestMatch = null;
                        for (const heading of headings){
                            const text = heading.textContent?.toLowerCase() || '';
                            const id = heading.getAttribute('id') || '';
                            let score = 0;
                            // Exact match
                            if (text === queryLower || id === queryLower) {
                                score = 100;
                            } else if (text.startsWith(queryLower) || id.startsWith(queryLower)) {
                                score = 80;
                            } else if (text.includes(queryLower) || id.includes(queryLower)) {
                                score = 60;
                            } else {
                                const queryWords = queryLower.split(/\s+/);
                                const textWords = text.split(/\s+/);
                                const matchingWords = queryWords.filter((qw)=>textWords.some((tw)=>tw.includes(qw) || qw.includes(tw)));
                                if (matchingWords.length > 0) {
                                    score = 30 + matchingWords.length / queryWords.length * 30;
                                }
                            }
                            if (score > 0 && (!bestMatch || score > bestMatch.score)) {
                                bestMatch = {
                                    element: heading,
                                    score,
                                    text: heading.textContent || '',
                                    id
                                };
                            }
                        }
                        if (bestMatch) {
                            // Scroll to the section
                            bestMatch.element.scrollIntoView({
                                behavior: 'smooth',
                                block: 'start'
                            });
                            return {
                                found: true,
                                heading: bestMatch.text,
                                id: bestMatch.id
                            };
                        }
                        return {
                            found: false
                        };
                    };
                    // Try immediately
                    let result = findAndScrollToSection();
                    // If not found, retry with delays (page might still be rendering)
                    if (!result.found) {
                        setTimeout(()=>{
                            result = findAndScrollToSection();
                            if (!result.found) {
                                setTimeout(()=>{
                                    findAndScrollToSection();
                                }, 300);
                            }
                        }, 100);
                    }
                    addToolOutput({
                        tool: 'scroll_to_section',
                        toolCallId,
                        output: result.found ? {
                            success: true,
                            heading: result.heading,
                            id: result.id,
                            message: `Scrolled to "${result.heading}"`
                        } : {
                            success: true,
                            heading: query,
                            id: query.toLowerCase().replace(/\s+/g, '-'),
                            message: `Scrolling to "${query}"`
                        }
                    });
                }
                if (toolName === 'prefill_parameters') {
                    const prefillData = toolInput;
                    onPrefill(prefillData);
                    addToolOutput({
                        tool: 'prefill_parameters',
                        toolCallId,
                        output: {
                            success: true,
                            ...prefillData
                        }
                    });
                }
                if (toolName === 'get_endpoint_details') {
                    const { endpointId } = toolInput;
                    const fullRequest = findRequestById(collection, endpointId);
                    if (fullRequest) {
                        const formattedDetails = formatRequestForAI(fullRequest);
                        addToolOutput({
                            tool: 'get_endpoint_details',
                            toolCallId,
                            output: formattedDetails
                        });
                    } else {
                        addToolOutput({
                            tool: 'get_endpoint_details',
                            toolCallId,
                            output: {
                                error: 'Endpoint not found'
                            }
                        });
                    }
                }
                // Handle get_current_request tool - returns current playground request payload
                if (toolName === 'get_current_request') {
                    if (currentRequestPayload) {
                        addToolOutput({
                            tool: 'get_current_request',
                            toolCallId,
                            output: {
                                success: true,
                                request: {
                                    method: currentRequestPayload.method,
                                    url: currentRequestPayload.endpoint,
                                    queryParams: currentRequestPayload.params.filter((p)=>p.active),
                                    headers: currentRequestPayload.headers.filter((h)=>h.active),
                                    body: currentRequestPayload.body,
                                    contentType: currentRequestPayload.bodyContentType
                                }
                            }
                        });
                    } else {
                        addToolOutput({
                            tool: 'get_current_request',
                            toolCallId,
                            output: {
                                success: false,
                                error: 'No request payload available. Please select an endpoint first.'
                            }
                        });
                    }
                }
                // Handle switch_to_notes tool
                if (toolName === 'switch_to_notes') {
                    switchToNotes();
                    addToolOutput({
                        tool: 'switch_to_notes',
                        toolCallId,
                        output: {
                            success: true,
                            message: 'Switched to Notes workspace'
                        }
                    });
                }
                // Handle switch_to_docs tool
                if (toolName === 'switch_to_docs') {
                    switchToDocs();
                    addToolOutput({
                        tool: 'switch_to_docs',
                        toolCallId,
                        output: {
                            success: true,
                            message: 'Switched to Docs'
                        }
                    });
                }
                // Handle switch_to_api_client tool
                if (toolName === 'switch_to_api_client') {
                    switchToApiClient();
                    addToolOutput({
                        tool: 'switch_to_api_client',
                        toolCallId,
                        output: {
                            success: true,
                            message: 'Switched to API Client'
                        }
                    });
                }
                // Handle list_notes tool (lists existing files to check for duplicates)
                if (toolName === 'list_notes') {
                    const { filter } = toolInput;
                    // Switch to notes workspace
                    switchToNotes();
                    // Filter notes if a filter is provided
                    let filteredNotes = notes.filter((n)=>!n.path.endsWith('.folder')) // Exclude folder placeholders
                    ;
                    if (filter) {
                        const lowerFilter = filter.toLowerCase();
                        filteredNotes = filteredNotes.filter((n)=>n.path.toLowerCase().includes(lowerFilter));
                    }
                    // Return list of file paths with basic info
                    const notesList = filteredNotes.map((n)=>({
                            path: n.path,
                            updatedAt: n.updatedAt
                        }));
                    addToolOutput({
                        tool: 'list_notes',
                        toolCallId,
                        output: {
                            success: true,
                            count: notesList.length,
                            files: notesList,
                            message: notesList.length > 0 ? `Found ${notesList.length} file(s)${filter ? ` matching "${filter}"` : ''}` : `No files found${filter ? ` matching "${filter}"` : ' in workspace'}`
                        }
                    });
                }
                // Handle open_file tool (opens existing file)
                if (toolName === 'open_file') {
                    const { path } = toolInput;
                    // Switch to notes mode with the file path
                    switchToNotes(path);
                    addToolOutput({
                        tool: 'open_file',
                        toolCallId,
                        output: {
                            success: true,
                            path,
                            message: `Opened ${path}`
                        }
                    });
                }
                // Handle create_folder tool (creates a folder for organizing files)
                if (toolName === 'create_folder') {
                    const { path, description } = toolInput;
                    // Switch to notes workspace
                    switchToNotes();
                    // Folders are virtual in our system - files with paths like "folder/file.ext" 
                    // automatically create the folder structure when files are added.
                    // We just acknowledge the intent - the folder will appear when files are created inside it.
                    addToolOutput({
                        tool: 'create_folder',
                        toolCallId,
                        output: {
                            success: true,
                            path,
                            description,
                            message: `Folder "${path}" will be created when files are added`
                        }
                    });
                }
                // Handle create_file tool (creates empty file)
                if (toolName === 'create_file') {
                    const { path, description } = toolInput;
                    // Switch to notes workspace
                    switchToNotes();
                    if (workspace) {
                        try {
                            // Create truly empty file - content will be written by write_file
                            await createNote(path, '');
                            await refreshNotes();
                            // Trigger refresh in notes-mode UI
                            triggerNotesRefresh();
                            setActiveFilePath(path);
                            addToolOutput({
                                tool: 'create_file',
                                toolCallId,
                                output: {
                                    success: true,
                                    path,
                                    description
                                }
                            });
                        } catch (err) {
                            console.error('[AgentChat] Failed to create file:', err);
                            addToolOutput({
                                tool: 'create_file',
                                toolCallId,
                                output: {
                                    success: false,
                                    error: err instanceof Error ? err.message : 'Failed to create file'
                                }
                            });
                        }
                    } else {
                        addToolOutput({
                            tool: 'create_file',
                            toolCallId,
                            output: {
                                success: false,
                                error: 'Workspace not available'
                            }
                        });
                    }
                }
                // Handle write_file tool (writes content to file)
                // Note: Streaming already shows content in real-time via onWriteFileDelta
                // This handler saves the final content to IndexedDB for persistence
                if (toolName === 'write_file') {
                    const { path, content } = toolInput;
                    // Switch to notes workspace
                    switchToNotes();
                    if (workspace) {
                        try {
                            // Don't clear streaming content here - notes-mode will clear it after loading
                            // This prevents flash of empty content for mermaid previews
                            // Save the final content to IndexedDB for persistence
                            await updateNote(path, content);
                            await refreshNotes();
                            // Trigger refresh in notes-mode UI
                            triggerNotesRefresh();
                            // Force reload the file content from DB
                            setActiveFilePath(`${path}?t=${Date.now()}`);
                            addToolOutput({
                                tool: 'write_file',
                                toolCallId,
                                output: {
                                    success: true,
                                    path
                                }
                            });
                        } catch (err) {
                            console.error('[AgentChat] Failed to save file:', err);
                            setStreamingContent(null); // Clear on error too
                            addToolOutput({
                                tool: 'write_file',
                                toolCallId,
                                output: {
                                    success: false,
                                    error: err instanceof Error ? err.message : 'Failed to save file'
                                }
                            });
                        }
                    } else {
                        setStreamingContent(null);
                        addToolOutput({
                            tool: 'write_file',
                            toolCallId,
                            output: {
                                success: false,
                                error: 'Workspace not available'
                            }
                        });
                    }
                }
                // Handle delete_file tool (deletes a file from workspace)
                if (toolName === 'delete_file') {
                    const { path, reason } = toolInput;
                    // Switch to notes workspace
                    switchToNotes();
                    if (workspace) {
                        try {
                            // Check if file exists
                            const fileExists = notes.some((n)=>n.path === path);
                            if (!fileExists) {
                                addToolOutput({
                                    tool: 'delete_file',
                                    toolCallId,
                                    output: {
                                        success: false,
                                        error: `File not found: ${path}`
                                    }
                                });
                                return;
                            }
                            // Delete the file
                            await deleteNote(path);
                            await refreshNotes();
                            // Trigger refresh in notes-mode UI
                            triggerNotesRefresh();
                            // Clear active file if it was the deleted one
                            setActiveFilePath(null);
                            addToolOutput({
                                tool: 'delete_file',
                                toolCallId,
                                output: {
                                    success: true,
                                    path,
                                    reason,
                                    message: `Deleted ${path}`
                                }
                            });
                        } catch (err) {
                            console.error('[AgentChat] Failed to delete file:', err);
                            addToolOutput({
                                tool: 'delete_file',
                                toolCallId,
                                output: {
                                    success: false,
                                    error: err instanceof Error ? err.message : 'Failed to delete file'
                                }
                            });
                        }
                    } else {
                        addToolOutput({
                            tool: 'delete_file',
                            toolCallId,
                            output: {
                                success: false,
                                error: 'Workspace not available'
                            }
                        });
                    }
                }
                // Handle delete_all_notes tool (deletes all files from workspace)
                if (toolName === 'delete_all_notes') {
                    const { confirmed } = toolInput;
                    // Switch to notes workspace
                    switchToNotes();
                    if (!confirmed) {
                        addToolOutput({
                            tool: 'delete_all_notes',
                            toolCallId,
                            output: {
                                success: false,
                                error: 'Deletion not confirmed. Please confirm with the user first.'
                            }
                        });
                        return;
                    }
                    if (workspace) {
                        try {
                            // Refresh notes first to get accurate count (notes state might be stale)
                            await refreshNotes();
                            // Get fresh count from database directly
                            const { dbOperations } = await import('@/lib/api-docs/code-editor/db');
                            const currentNotes = await dbOperations.listNotes(workspace.id);
                            const visibleNotes = currentNotes.filter((n)=>!n.path.endsWith('.folder'));
                            const noteCount = visibleNotes.length;
                            // Get list of files for display
                            const fileList = visibleNotes.map((n)=>n.path);
                            if (noteCount === 0) {
                                addToolOutput({
                                    tool: 'delete_all_notes',
                                    toolCallId,
                                    output: {
                                        success: true,
                                        deletedCount: 0,
                                        files: [],
                                        message: 'No notes to delete'
                                    }
                                });
                                return;
                            }
                            // Delete all notes
                            await deleteAllNotes();
                            await refreshNotes();
                            // Trigger refresh in notes-mode UI
                            triggerNotesRefresh();
                            // Clear active file
                            setActiveFilePath(null);
                            addToolOutput({
                                tool: 'delete_all_notes',
                                toolCallId,
                                output: {
                                    success: true,
                                    deletedCount: noteCount,
                                    files: fileList,
                                    message: `Deleted ${noteCount} note${noteCount !== 1 ? 's' : ''}`
                                }
                            });
                        } catch (err) {
                            console.error('[AgentChat] Failed to delete all notes:', err);
                            addToolOutput({
                                tool: 'delete_all_notes',
                                toolCallId,
                                output: {
                                    success: false,
                                    error: err instanceof Error ? err.message : 'Failed to delete notes'
                                }
                            });
                        }
                    } else {
                        addToolOutput({
                            tool: 'delete_all_notes',
                            toolCallId,
                            output: {
                                success: false,
                                error: 'Workspace not available'
                            }
                        });
                    }
                }
                // Handle check_request_validity tool - validates if request is ready to send
                if (toolName === 'check_request_validity') {
                    const { endpointId } = toolInput;
                    const endpoint = findRequestById(collection, endpointId);
                    if (!endpoint) {
                        addToolOutput({
                            tool: 'check_request_validity',
                            toolCallId,
                            output: {
                                success: false,
                                error: 'Endpoint not found'
                            }
                        });
                        return;
                    }
                    // Get current request payload from context
                    const payload = currentRequestPayload;
                    // Analyze path parameters from the endpoint URL
                    const pathParamMatches = endpoint.endpoint.match(/\{([^}]+)\}/g) || [];
                    const requiredPathParams = pathParamMatches.map((p)=>p.slice(1, -1));
                    // Check which path params have values
                    const filledPathParams = requiredPathParams.filter((param)=>{
                        // Check if the URL has been filled with actual values (not still containing {param})
                        return payload?.endpoint && !payload.endpoint.includes(`{${param}}`);
                    });
                    const missingPathParams = requiredPathParams.filter((p)=>!filledPathParams.includes(p));
                    // Analyze query parameters
                    const requiredQueryParams = endpoint.params.filter((p)=>p.description?.toLowerCase().includes('required')).map((p)=>p.key);
                    const filledQueryParams = (payload?.params || []).filter((p)=>p.active && p.value).map((p)=>p.key);
                    const missingQueryParams = requiredQueryParams.filter((p)=>!filledQueryParams.includes(p));
                    // Analyze body (for POST/PUT/PATCH)
                    const needsBody = [
                        'POST',
                        'PUT',
                        'PATCH'
                    ].includes(endpoint.method);
                    const hasBody = !!(payload?.body && typeof payload.body === 'string' && payload.body.trim().length > 0);
                    // Try to extract required fields from the body schema
                    const bodyRequiredFields = [];
                    if (endpoint.body.body && typeof endpoint.body.body === 'string') {
                        try {
                            const bodySchema = JSON.parse(endpoint.body.body);
                            if (bodySchema.required && Array.isArray(bodySchema.required)) {
                                bodyRequiredFields.push(...bodySchema.required);
                            }
                        } catch  {
                        // Not a schema, might be example body
                        }
                    }
                    // Check missing body fields
                    let missingBodyFields = [];
                    if (hasBody && bodyRequiredFields.length > 0) {
                        try {
                            const currentBody = JSON.parse(payload?.body || '{}');
                            missingBodyFields = bodyRequiredFields.filter((field)=>currentBody[field] === undefined || currentBody[field] === '');
                        } catch  {
                        // Invalid JSON in body
                        }
                    }
                    // Check authentication
                    const needsAuth = endpoint.auth.authType !== 'none';
                    const hasAuth = payload?.headers?.some((h)=>h.active && (h.key.toLowerCase() === 'authorization' || h.key.toLowerCase() === 'x-api-key')) || false;
                    // Build validation result
                    const isValid = missingPathParams.length === 0 && missingQueryParams.length === 0 && (!needsBody || hasBody) && (!needsAuth || hasAuth);
                    // Build summary message
                    const issues = [];
                    if (missingPathParams.length > 0) {
                        issues.push(`Missing path params: ${missingPathParams.join(', ')}`);
                    }
                    if (missingQueryParams.length > 0) {
                        issues.push(`Missing required params: ${missingQueryParams.join(', ')}`);
                    }
                    if (needsBody && !hasBody) {
                        issues.push('Request body is empty');
                    }
                    if (missingBodyFields.length > 0) {
                        issues.push(`Missing body fields: ${missingBodyFields.join(', ')}`);
                    }
                    if (needsAuth && !hasAuth) {
                        issues.push('Authentication not configured');
                    }
                    const summary = isValid ? 'Request is ready to send!' : `Issues found: ${issues.join('; ')}`;
                    const result = {
                        isValid,
                        endpoint: {
                            id: endpoint.id || endpointId,
                            name: endpoint.name,
                            method: endpoint.method,
                            path: endpoint.endpoint
                        },
                        validation: {
                            pathParams: {
                                required: requiredPathParams,
                                filled: filledPathParams,
                                missing: missingPathParams
                            },
                            queryParams: {
                                required: requiredQueryParams,
                                filled: filledQueryParams,
                                missing: missingQueryParams
                            },
                            body: {
                                required: needsBody,
                                hasContent: hasBody,
                                requiredFields: bodyRequiredFields,
                                missingFields: missingBodyFields
                            },
                            auth: {
                                required: needsAuth,
                                configured: hasAuth,
                                type: needsAuth ? endpoint.auth.authType : null
                            }
                        },
                        summary
                    };
                    addToolOutput({
                        tool: 'check_request_validity',
                        toolCallId,
                        output: result
                    });
                }
                // Handle send_request tool - triggers the playground's send button
                if (toolName === 'send_request') {
                    const { confirmSend } = toolInput;
                    if (!confirmSend) {
                        addToolOutput({
                            tool: 'send_request',
                            toolCallId,
                            output: {
                                success: false,
                                error: 'Request not confirmed'
                            }
                        });
                        return;
                    }
                    if (!currentEndpoint) {
                        addToolOutput({
                            tool: 'send_request',
                            toolCallId,
                            output: {
                                success: false,
                                error: 'No endpoint selected'
                            }
                        });
                        return;
                    }
                    // Trigger the playground's send button
                    requestSend();
                    addToolOutput({
                        tool: 'send_request',
                        toolCallId,
                        output: {
                            success: true,
                            message: 'Request sent! Check the response viewer in the playground.'
                        }
                    });
                }
            } catch (err) {
                addToolOutput({
                    tool: toolName,
                    toolCallId,
                    state: 'output-error',
                    errorText: err instanceof Error ? err.message : 'Tool execution failed'
                });
            }
        }
    });
    // Derived loading state
    const isLoading = status === 'streaming' || status === 'submitted';
    // Load saved messages on mount
    useEffect(()=>{
        try {
            const saved = localStorage.getItem(CHAT_STORAGE_KEY);
            if (saved) {
                const parsed = JSON.parse(saved);
                if (Array.isArray(parsed) && parsed.length > 0) {
                    setMessages(parsed);
                    setShowSuggestions(false);
                }
            }
        } catch  {
        // Ignore parse errors
        }
    }, [
        setMessages
    ]);
    // Save messages when they change
    useEffect(()=>{
        if (messages.length > 0) {
            try {
                localStorage.setItem(CHAT_STORAGE_KEY, JSON.stringify(messages));
            } catch  {
            // Ignore storage errors
            }
        }
    }, [
        messages
    ]);
    // Notify parent about message count changes
    useEffect(()=>{
        onHasMessagesChange?.(messages.length > 0);
    }, [
        messages.length,
        onHasMessagesChange
    ]);
    // Auto-scroll to bottom
    useEffect(()=>{
        messagesEndRef.current?.scrollIntoView({
            behavior: 'smooth'
        });
    }, [
        messages
    ]);
    // Track pending debug error type for showing options after AI response
    const [pendingErrorType, setPendingErrorType] = useState(null);
    const prevStatus = useRef(status);
    // Handle debug context from response viewer - show context card and send prompt
    useEffect(()=>{
        if (!debugContext || status === 'streaming' || status === 'submitted') {
            if (!debugContext) processedDebugRef.current = null;
            return;
        }
        const contextKey = JSON.stringify(debugContext);
        if (processedDebugRef.current === contextKey) return;
        processedDebugRef.current = contextKey;
        // Detect and store error type for later (to show options after AI responds)
        const errorType = detectErrorType(debugContext.status, debugContext.responseBody);
        setPendingErrorType(errorType);
        // Create a concise debug prompt
        const prompt = `Debug this ${debugContext.status} error and suggest a fix.`;
        // Encode the debug context as a card message
        const contextCardMessage = encodeCardMessage({
            type: 'debug_context',
            context: debugContext
        });
        // Add the debug context card as a user message
        const debugContextMessage = {
            id: `debug-${Date.now()}`,
            role: 'user',
            parts: [
                {
                    type: 'text',
                    text: contextCardMessage
                }
            ]
        };
        // Add context card, then send the actual prompt
        setMessages((prev)=>[
                ...prev,
                debugContextMessage
            ]);
        setShowSuggestions(false);
        // Small delay to let the card render, then send prompt
        setTimeout(()=>{
            sendMessage({
                role: 'user',
                parts: [
                    {
                        type: 'text',
                        text: prompt
                    }
                ]
            });
        }, 100);
        onDebugContextConsumed?.();
    }, [
        debugContext,
        status,
        sendMessage,
        setMessages,
        onDebugContextConsumed
    ]);
    // Track processed explain context to avoid duplicates
    const processedExplainRef = useRef(null);
    // Handle explain context from response viewer - send explain prompt
    useEffect(()=>{
        if (!explainContext || status === 'streaming' || status === 'submitted') {
            if (!explainContext) processedExplainRef.current = null;
            return;
        }
        const contextKey = JSON.stringify(explainContext);
        if (processedExplainRef.current === contextKey) return;
        processedExplainRef.current = contextKey;
        // Create a concise explain prompt
        const prompt = `Explain this ${explainContext.status} response. What does it mean and what are the key fields?`;
        // Encode the context as a card message (reuse debug_context type)
        const contextCardMessage = encodeCardMessage({
            type: 'debug_context',
            context: {
                ...explainContext,
                errorMessage: undefined
            }
        });
        // Add the context card as a user message
        const explainContextMessage = {
            id: `explain-${Date.now()}`,
            role: 'user',
            parts: [
                {
                    type: 'text',
                    text: contextCardMessage
                }
            ]
        };
        // Add context card, then send the actual prompt
        setMessages((prev)=>[
                ...prev,
                explainContextMessage
            ]);
        setShowSuggestions(false);
        // Small delay to let the card render, then send prompt
        setTimeout(()=>{
            sendMessage({
                role: 'user',
                parts: [
                    {
                        type: 'text',
                        text: prompt
                    }
                ]
            });
        }, 100);
        onExplainContextConsumed?.();
    }, [
        explainContext,
        status,
        sendMessage,
        setMessages,
        onExplainContextConsumed
    ]);
    // Add response options card after AI finishes responding to debug request
    useEffect(()=>{
        // Check if status changed from streaming/submitted to ready
        const wasProcessing = prevStatus.current === 'streaming' || prevStatus.current === 'submitted';
        const isNowReady = status === 'ready';
        if (wasProcessing && isNowReady && pendingErrorType) {
            // Encode the response options as a card message
            const optionsCardMessage = encodeCardMessage({
                type: 'response_options',
                errorType: pendingErrorType
            });
            // Add the response options card after AI response
            const responseOptionsMessage = {
                id: `options-${Date.now()}`,
                role: 'assistant',
                parts: [
                    {
                        type: 'text',
                        text: optionsCardMessage
                    }
                ]
            };
            setMessages((prev)=>[
                    ...prev,
                    responseOptionsMessage
                ]);
            // Clear pending error type
            setPendingErrorType(null);
        }
        // Update previous status
        prevStatus.current = status;
    }, [
        status,
        pendingErrorType,
        setMessages
    ]);
    // Handle image selection
    const handleImageSelect = useCallback(async (e)=>{
        const files = Array.from(e.target.files || []);
        if (files.length === 0) return;
        // Limit to 4 images total
        const availableSlots = 4 - selectedImages.length;
        const filesToProcess = files.slice(0, availableSlots);
        const newImages = await Promise.all(filesToProcess.map(async (file)=>{
            // Create preview URL
            const preview = URL.createObjectURL(file);
            // Convert to base64
            const base64 = await new Promise((resolve)=>{
                const reader = new FileReader();
                reader.onloadend = ()=>{
                    const result = reader.result;
                    // Extract base64 data without the data URL prefix
                    resolve(result);
                };
                reader.readAsDataURL(file);
            });
            return {
                file,
                preview,
                base64
            };
        }));
        setSelectedImages((prev)=>[
                ...prev,
                ...newImages
            ]);
        // Reset file input
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    }, [
        selectedImages.length
    ]);
    // Remove selected image
    const handleRemoveImage = useCallback((index)=>{
        setSelectedImages((prev)=>{
            const newImages = [
                ...prev
            ];
            // Revoke the preview URL to free memory
            URL.revokeObjectURL(newImages[index].preview);
            newImages.splice(index, 1);
            return newImages;
        });
    }, []);
    // Auto-resize textarea
    const handleInputChange = useCallback((e)=>{
        setInputValue(e.target.value);
        const textarea = e.target;
        textarea.style.height = 'auto';
        textarea.style.height = `${Math.min(textarea.scrollHeight, 128)}px`;
    }, []);
    // Handle form submit
    const handleSubmit = useCallback((e)=>{
        e.preventDefault();
        if (!inputValue.trim() && selectedImages.length === 0 || isLoading) return;
        const trimmedInput = inputValue.trim();
        setInputValue('');
        if (textareaRef.current) {
            textareaRef.current.style.height = 'auto';
        }
        // Build message parts with images and text
        const parts = [];
        // Add images first
        selectedImages.forEach((img)=>{
            parts.push({
                type: 'image',
                image: img.base64
            });
        });
        // Add text if present
        if (trimmedInput) {
            parts.push({
                type: 'text',
                text: trimmedInput
            });
        } else if (selectedImages.length > 0) {
            // If only images, add a default prompt
            parts.push({
                type: 'text',
                text: 'What can you tell me about this image?'
            });
        }
        // Clear selected images
        selectedImages.forEach((img)=>URL.revokeObjectURL(img.preview));
        setSelectedImages([]);
        setShowSuggestions(false);
        sendMessage({
            role: 'user',
            // Cast to allow image parts which our API handles correctly
            parts: parts
        });
    }, [
        inputValue,
        isLoading,
        sendMessage,
        selectedImages
    ]);
    // Handle suggestion click
    const handleSuggestionClick = useCallback((prompt)=>{
        setShowSuggestions(false);
        sendMessage({
            role: 'user',
            parts: [
                {
                    type: 'text',
                    text: prompt
                }
            ]
        });
    }, [
        sendMessage
    ]);
    // Handle delete single message
    const handleDeleteMessage = useCallback((messageId)=>{
        setMessages((prevMessages)=>{
            const newMessages = prevMessages.filter((msg)=>msg.id !== messageId);
            // Update localStorage with the new messages
            if (newMessages.length === 0) {
                localStorage.removeItem(CHAT_STORAGE_KEY);
                setShowSuggestions(true);
            } else {
                localStorage.setItem(CHAT_STORAGE_KEY, JSON.stringify(newMessages));
            }
            return newMessages;
        });
    }, [
        setMessages
    ]);
    // Handle keyboard shortcuts
    const handleKeyDown = useCallback((e)=>{
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSubmit(e);
        }
    }, [
        handleSubmit
    ]);
    // Card actions for error handling
    const cardActions = useMemo(()=>({
            onOpenGlobalAuth,
            onNavigateToAuthTab,
            onNavigateToParamsTab,
            onNavigateToBodyTab,
            onNavigateToHeadersTab
        }), [
        onOpenGlobalAuth,
        onNavigateToAuthTab,
        onNavigateToParamsTab,
        onNavigateToBodyTab,
        onNavigateToHeadersTab
    ]);
    // Convert AI SDK messages to our format for rendering
    const renderableMessages = messages.map((msg)=>({
            id: msg.id,
            role: msg.role,
            content: getMessageContent(msg),
            images: getMessageImages(msg),
            toolInvocations: getToolInvocations(msg)
        }));
    return /*#__PURE__*/ _jsxs("div", {
        className: "flex flex-col h-full",
        children: [
            /*#__PURE__*/ _jsx("div", {
                className: "flex-1 overflow-y-auto flex flex-col",
                children: /*#__PURE__*/ _jsxs("div", {
                    className: cn("max-w-2xl mx-auto px-4 py-4 w-full", messages.length === 0 && showSuggestions ? "flex-1 flex flex-col" : ""),
                    children: [
                        messages.length === 0 && showSuggestions && /*#__PURE__*/ _jsxs("div", {
                            className: "flex w-full grow flex-col",
                            children: [
                                /*#__PURE__*/ _jsx("div", {
                                    className: "flex w-full grow flex-col items-center justify-center",
                                    children: /*#__PURE__*/ _jsxs("div", {
                                        className: "flex flex-col items-center text-center px-4",
                                        children: [
                                            /*#__PURE__*/ _jsx("h1", {
                                                className: "font-semibold text-2xl animate-in fade-in slide-in-from-bottom-1 duration-200",
                                                children: currentEndpoint ? currentEndpoint.name : 'Hello there!'
                                            }),
                                            /*#__PURE__*/ _jsx("p", {
                                                className: "text-muted-foreground text-lg animate-in fade-in slide-in-from-bottom-1 duration-200 delay-75",
                                                children: currentEndpoint ? 'Ask me anything about this endpoint' : 'How can I help you today?'
                                            })
                                        ]
                                    })
                                }),
                                /*#__PURE__*/ _jsx("div", {
                                    className: "grid w-full grid-cols-1 gap-2 pb-4 mt-8",
                                    children: loadingSuggestions ? // Loading skeletons
                                    /*#__PURE__*/ _jsx(_Fragment, {
                                        children: [
                                            1,
                                            2,
                                            3,
                                            4
                                        ].map((i)=>/*#__PURE__*/ _jsx("div", {
                                                className: "h-[52px] w-full rounded-2xl border bg-muted/30 animate-pulse",
                                                style: {
                                                    animationDelay: `${i * 100}ms`
                                                }
                                            }, i))
                                    }) : suggestions.map((suggestion, index)=>/*#__PURE__*/ _jsx("div", {
                                            className: "animate-in fade-in slide-in-from-bottom-2 duration-200 fill-mode-both",
                                            style: {
                                                animationDelay: `${100 + index * 50}ms`
                                            },
                                            children: /*#__PURE__*/ _jsxs("button", {
                                                onClick: ()=>handleSuggestionClick(suggestion.prompt),
                                                className: "h-auto w-full flex flex-wrap items-start justify-start gap-1 rounded-2xl border px-4 py-3 text-left text-sm transition-colors hover:bg-muted",
                                                children: [
                                                    /*#__PURE__*/ _jsx("span", {
                                                        className: "font-medium",
                                                        children: suggestion.title
                                                    }),
                                                    /*#__PURE__*/ _jsx("span", {
                                                        className: "text-muted-foreground",
                                                        children: suggestion.label
                                                    })
                                                ]
                                            })
                                        }, suggestion.prompt))
                                })
                            ]
                        }),
                        renderableMessages.map((message, i)=>/*#__PURE__*/ _jsx(ChatMessage, {
                                role: message.role,
                                content: message.content,
                                messageId: message.id,
                                images: message.images,
                                toolInvocations: message.toolInvocations,
                                isStreaming: isLoading && i === renderableMessages.length - 1,
                                onDeleteMessage: handleDeleteMessage,
                                onNavigate: onNavigate,
                                onNavigateToDocPage: onNavigateToDocPage,
                                onOpenFile: handleOpenFile,
                                cardActions: cardActions
                            }, message.id)),
                        status === 'submitted' && /*#__PURE__*/ _jsx(TypingIndicator, {}),
                        /*#__PURE__*/ _jsx("div", {
                            ref: messagesEndRef
                        })
                    ]
                })
            }),
            /*#__PURE__*/ _jsx("div", {
                className: "border-t border-border p-4",
                children: /*#__PURE__*/ _jsxs("form", {
                    onSubmit: handleSubmit,
                    className: "max-w-2xl mx-auto",
                    children: [
                        /*#__PURE__*/ _jsx("input", {
                            ref: fileInputRef,
                            type: "file",
                            accept: "image/*",
                            multiple: true,
                            onChange: handleImageSelect,
                            className: "hidden",
                            "aria-hidden": "true"
                        }),
                        /*#__PURE__*/ _jsxs("div", {
                            className: "relative rounded-2xl border border-border bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring",
                            children: [
                                selectedImages.length > 0 && /*#__PURE__*/ _jsx("div", {
                                    className: "flex flex-wrap gap-2 p-3 pb-0",
                                    children: selectedImages.map((img, index)=>/*#__PURE__*/ _jsxs("div", {
                                            className: "relative group",
                                            children: [
                                                /*#__PURE__*/ _jsx("img", {
                                                    src: img.preview,
                                                    alt: `Selected image ${index + 1}`,
                                                    className: "h-16 w-16 object-cover rounded-lg border border-border"
                                                }),
                                                /*#__PURE__*/ _jsx(Button, {
                                                    type: "button",
                                                    size: "icon",
                                                    variant: "secondary",
                                                    onClick: ()=>handleRemoveImage(index),
                                                    className: "absolute -top-1.5 -right-1.5 h-4 w-4 min-w-0 rounded-full opacity-0 group-hover:opacity-100 transition-opacity shadow-sm p-2",
                                                    "aria-label": `Remove image ${index + 1}`,
                                                    children: /*#__PURE__*/ _jsx(X, {
                                                        className: "h-2.5 w-2.5 p-1",
                                                        weight: "bold"
                                                    })
                                                })
                                            ]
                                        }, index))
                                }),
                                /*#__PURE__*/ _jsx("textarea", {
                                    ref: textareaRef,
                                    value: inputValue,
                                    onChange: handleInputChange,
                                    onKeyDown: handleKeyDown,
                                    placeholder: "Send a message...",
                                    className: cn("w-full resize-none bg-transparent px-4 pt-3 pb-12 text-sm", "placeholder:text-muted-foreground/70 outline-none", "min-h-[56px] max-h-32"),
                                    rows: 1,
                                    disabled: isLoading,
                                    "aria-label": "Message input"
                                }),
                                /*#__PURE__*/ _jsxs("div", {
                                    className: "absolute bottom-2 left-2 right-2 flex items-center justify-between",
                                    children: [
                                        /*#__PURE__*/ _jsx("div", {
                                            children: /*#__PURE__*/ _jsxs(Tooltip, {
                                                children: [
                                                    /*#__PURE__*/ _jsx(TooltipTrigger, {
                                                        asChild: true,
                                                        children: /*#__PURE__*/ _jsx(Button, {
                                                            type: "button",
                                                            size: "icon",
                                                            variant: "ghost",
                                                            className: cn("h-8 w-8 rounded-full text-muted-foreground hover:text-foreground", selectedImages.length >= 4 && "opacity-50 cursor-not-allowed"),
                                                            onClick: ()=>fileInputRef.current?.click(),
                                                            disabled: isLoading || selectedImages.length >= 4,
                                                            "aria-label": "Upload image",
                                                            children: /*#__PURE__*/ _jsx(ImageIcon, {
                                                                className: "h-4 w-4",
                                                                weight: "bold"
                                                            })
                                                        })
                                                    }),
                                                    /*#__PURE__*/ _jsx(TooltipContent, {
                                                        side: "top",
                                                        children: selectedImages.length >= 4 ? 'Maximum 4 images' : 'Upload image'
                                                    })
                                                ]
                                            })
                                        }),
                                        isLoading ? /*#__PURE__*/ _jsxs(Tooltip, {
                                            children: [
                                                /*#__PURE__*/ _jsx(TooltipTrigger, {
                                                    asChild: true,
                                                    children: /*#__PURE__*/ _jsx(Button, {
                                                        type: "button",
                                                        onClick: ()=>stop(),
                                                        size: "icon",
                                                        variant: "default",
                                                        className: "h-8 w-8 rounded-full",
                                                        "aria-label": "Stop generating",
                                                        children: /*#__PURE__*/ _jsx(Square, {
                                                            className: "h-3 w-3",
                                                            weight: "fill"
                                                        })
                                                    })
                                                }),
                                                /*#__PURE__*/ _jsx(TooltipContent, {
                                                    side: "top",
                                                    children: "Stop generating"
                                                })
                                            ]
                                        }) : /*#__PURE__*/ _jsxs(Tooltip, {
                                            children: [
                                                /*#__PURE__*/ _jsx(TooltipTrigger, {
                                                    asChild: true,
                                                    children: /*#__PURE__*/ _jsx(Button, {
                                                        type: "submit",
                                                        disabled: !inputValue.trim(),
                                                        size: "icon",
                                                        variant: "default",
                                                        className: "h-8 w-8 rounded-full",
                                                        "aria-label": "Send message",
                                                        children: /*#__PURE__*/ _jsx(ArrowUp, {
                                                            className: "h-4 w-4",
                                                            weight: "bold"
                                                        })
                                                    })
                                                }),
                                                /*#__PURE__*/ _jsx(TooltipContent, {
                                                    side: "top",
                                                    children: "Send message"
                                                })
                                            ]
                                        })
                                    ]
                                })
                            ]
                        })
                    ]
                })
            })
        ]
    });
}
// Helper to extract text content from a message
function getMessageContent(msg) {
    if (!msg.parts) return '';
    const textParts = msg.parts.filter((part)=>part.type === 'text' && typeof part.text === 'string');
    let content = textParts.map((p)=>p.text).join('');
    // Remove any trailing JSON blocks that the model might have included
    content = content.replace(/\n*```json[\s\S]*?```\n*/g, '');
    content = content.replace(/\n*\{[\s\S]*?"id":\s*"[^"]+",[\s\S]*?"name":\s*"[^"]+"[\s\S]*?\}\s*$/g, '');
    return content.trim();
}
// Helper to extract images from a message
function getMessageImages(msg) {
    if (!msg.parts) return [];
    return msg.parts.filter((part)=>part.type === 'image' && typeof part.image === 'string').map((part)=>({
            image: part.image
        }));
}
// Helper to extract tool invocations from a message
function getToolInvocations(msg) {
    if (!msg.parts) return [];
    // Use a Map to deduplicate by toolCallId (keep latest version)
    const toolCallMap = new Map();
    msg.parts.filter((part)=>{
        return typeof part === 'object' && part !== null && 'type' in part && typeof part.type === 'string' && part.type.startsWith('tool-') && part.type !== 'tool-call' && 'toolCallId' in part;
    }).forEach((part)=>{
        const toolName = part.toolName || part.type.replace('tool-', '');
        // Only update if we don't have this tool call yet, or if the new one has more info
        const existing = toolCallMap.get(part.toolCallId);
        const newState = getToolState(part);
        // Prefer 'result' state over 'pending'
        if (!existing || newState === 'result' || newState === 'error' && existing.state === 'pending') {
            toolCallMap.set(part.toolCallId, {
                toolCallId: part.toolCallId,
                toolName,
                args: part.input || part.args || {},
                result: part.output ?? part.result,
                state: newState
            });
        }
    });
    return Array.from(toolCallMap.values());
}
// Helper to determine tool state from part
function getToolState(part) {
    if (part.state === 'output-error') return 'error';
    if (part.state === 'output-available') return 'result';
    if (part.state === 'input-streaming' || part.state === 'input-available') return 'pending';
    return 'result';
}
