/**
 * AI Agent - Frontend JavaScript for SSE Stream Handling
 * 
 * @package AI_Auto_Tool
 */

(function ($) {
    'use strict';

    // Time tracking for events - moved to module scope
    let timeTrackers = {}; // Store start times for each event
    let timerIntervals = {}; // Store interval IDs for live updates

    /**
     * Load Marked.js for Markdown rendering if not already loaded
     */
    if (typeof marked === 'undefined') {
        $.getScript('https://cdn.jsdelivr.net/npm/marked/marked.min.js')
            .done(function () {
                console.log('Marked.js loaded via CDN');
            })
            .fail(function () {
                console.error('Failed to load Marked.js');
            });
    }

    /**
     * Insert content into WordPress Editor
     * 
     * @param {string} content Content to insert
     */
    window.insertAgentContentToEditor = function (content) {
        // Try Block Editor (Gutenberg)
        if (typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
            try {
                // Convert Markdown to HTML if marked is available
                let htmlContent = content;
                if (typeof marked !== 'undefined') {
                    try {
                        htmlContent = marked.parse(content);
                    } catch (e) {
                        console.error('Marked parsing error:', e);
                    }
                }

                const blocks = wp.blocks.parse(htmlContent);
                wp.data.dispatch('core/editor').insertBlocks(blocks);

                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Success!',
                        text: 'Content inserted into editor',
                        icon: 'success',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 3000
                    });
                } else {
                    alert('Content inserted into editor');
                }
                return;
            } catch (e) {
                console.log('Block editor insertion failed, trying classic...', e);
            }
        }

        // Try Classic Editor (TinyMCE)
        if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor) {
            // Convert Markdown to HTML if marked is available
            let htmlContent = content;
            if (typeof marked !== 'undefined') {
                try {
                    htmlContent = marked.parse(content);
                } catch (e) {
                    console.error('Marked parsing error:', e);
                }
            }

            tinyMCE.activeEditor.insertContent(htmlContent);
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    title: 'Success!',
                    text: 'Content inserted into editor',
                    icon: 'success',
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000
                });
            } else {
                alert('Content inserted into editor');
            }
            return;
        }

        // Fallback to text area
        const contentField = document.querySelector('textarea#content');
        if (contentField) {
            contentField.value += content;
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    title: 'Success!',
                    text: 'Content appended to editor text area',
                    icon: 'success',
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000
                });
            } else {
                alert('Content appended to editor text area');
            }
            return;
        }

        alert('Could not find active editor to insert content.');
    };

    /**
     * Execute prompt with AI Agent using SSE streaming
     * 
     * @param {string} prompt User prompt
     * @param {string} targetDiv Target div ID for output
     * @returns {Promise} Promise that resolves when execution is complete
     */
    window.executePromptWithAgent = function (prompt, targetDiv) {
        return new Promise((resolve, reject) => {
            if (!prompt || !prompt.trim()) {
                if (typeof showError === 'function') {
                    showError('Please provide a prompt');
                }
                reject(new Error('Prompt is required'));
                return;
            }

            // Show loading
            if (typeof showLoading === 'function') {
                // showLoading('Starting AI Agent...');
            }

            // Prepare target container
            const container = document.getElementById(targetDiv);
            if (container) {
                // Add custom scrollbar styles
                const style = document.createElement('style');
                style.textContent = `
                    #agent-progress::-webkit-scrollbar,
                    #agent-status::-webkit-scrollbar,
                    .markdown-body::-webkit-scrollbar {
                        width: 8px;
                    }
                    #agent-progress::-webkit-scrollbar-track,
                    #agent-status::-webkit-scrollbar-track,
                    .markdown-body::-webkit-scrollbar-track {
                        background: #f1f1f1;
                        border-radius: 4px;
                    }
                    #agent-progress::-webkit-scrollbar-thumb,
                    #agent-status::-webkit-scrollbar-thumb,
                    .markdown-body::-webkit-scrollbar-thumb {
                        background: #c1c1c1;
                        border-radius: 4px;
                    }
                    #agent-progress::-webkit-scrollbar-thumb:hover,
                    #agent-status::-webkit-scrollbar-thumb:hover,
                    .markdown-body::-webkit-scrollbar-thumb:hover {
                        background: #a8a8a8;
                    }
                    @keyframes agent-spin {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                `;
                document.head.appendChild(style);

                container.innerHTML = `
                    <div id="agent-progress" style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; max-height: 95%; overflow-y: auto; background: #f8f9fa; border-radius: 8px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
                        
                        <div id="agent-status" style="margin-bottom: 16px;  overflow-y: auto; padding-right: 4px;"></div>
                        <div id="agent-tools" style="margin-bottom: 16px;"></div>
                        <div id="agent-result" style="display: none;"></div>
                        <div id="agent-progress-footer" style="display: none; margin-top: 16px; padding-top: 12px; border-top: 2px solid #e0e0e0;">
                            <div style="display: flex; align-items: center; justify-content: space-between;">
                                <div style="flex: 1; margin-right: 12px;">
                                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px;">
                                        <span style="font-size: 13px; font-weight: 600; color: #333;">Sections Progress</span>
                                        <span id="agent-progress-text" style="font-size: 13px; font-weight: 600; color: #2196f3;">0 / 0</span>
                                    </div>
                                    <div style="width: 100%; height: 8px; background: #e0e0e0; border-radius: 4px; overflow: hidden;">
                                        <div id="agent-progress-bar" style="height: 100%; background: linear-gradient(90deg, #2196f3 0%, #21cbf3 100%); border-radius: 4px; transition: width 0.3s ease; width: 0%;"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div id="agent-stream-loading" style="display: none; margin-top: 16px; padding: 12px; background: #fff; border-radius: 6px; border: 1px solid #e0e0e0; box-shadow: 0 1px 3px rgba(0,0,0,0.08);">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <div class="agent-loading-spinner" style="width: 20px; height: 20px; border: 3px solid #f3f3f3; border-top: 3px solid #667eea; border-radius: 50%; animation: agent-spin 1s linear infinite; flex-shrink: 0;"></div>
                                <span style="font-size: 13px; color: #666; font-weight: 500;">Đang xử lý...</span>
                            </div>
                        </div>
                    </div>
                `;

                // Add collapse all functionality
                const collapseAllBtn = document.getElementById('agent-collapse-all');
                if (collapseAllBtn) {
                    let allCollapsed = false;
                    collapseAllBtn.addEventListener('click', function () {
                        const toolItems = document.querySelectorAll('.agent-tool-item');
                        toolItems.forEach(item => {
                            const content = item.querySelector('.tool-content');
                            const toggle = item.querySelector('.tool-toggle');
                            if (content && toggle) {
                                if (allCollapsed) {
                                    content.style.display = 'block';
                                    toggle.textContent = '▼';
                                    toggle.style.transform = 'rotate(0deg)';
                                } else {
                                    content.style.display = 'none';
                                    toggle.textContent = '▶';
                                    toggle.style.transform = 'rotate(-90deg)';
                                }
                            }
                        });
                        allCollapsed = !allCollapsed;
                        collapseAllBtn.textContent = allCollapsed ? 'Expand All' : 'Collapse All';
                    });
                    collapseAllBtn.addEventListener('mouseenter', function () {
                        this.style.background = '#f5f5f5';
                        this.style.borderColor = '#bbb';
                    });
                    collapseAllBtn.addEventListener('mouseleave', function () {
                        this.style.background = '#fff';
                        this.style.borderColor = '#ddd';
                    });
                }
            }

            // Prepare form data
            const formData = new FormData();
            formData.append('action', 'aiautotool_ai_agent_execute');
            formData.append('prompt', prompt);
            formData.append('security', aiautotool_js_setting.security);

            // Track state
            let currentTool = null;
            let toolsExecuted = 0;
            let capturedContent = '';

            // Reset time trackers for new execution
            timeTrackers = {};
            timerIntervals = {};

            // Show loading indicator
            const loadingIndicator = document.getElementById('agent-stream-loading');
            if (loadingIndicator) {
                loadingIndicator.style.display = 'block';
            }

            // Start SSE fetch
            fetch(aiautotool_js_setting.ajax_url, {
                method: 'POST',
                body: formData
            }).then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.status);
                }

                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('text/event-stream')) {
                    return response.text().then(text => {
                        throw new Error('Unexpected response format: ' + text.substring(0, 200));
                    });
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let currentEvent = null;

                function readChunk() {
                    return reader.read().then(({ done, value }) => {
                        if (done) {
                            // Hide loading indicator
                            const loadingIndicator = document.getElementById('agent-stream-loading');
                            if (loadingIndicator) {
                                loadingIndicator.style.display = 'none';
                            }
                            if (typeof hideLoading === 'function') {
                                // hideLoading();
                            }
                            return;
                        }

                        try {
                            buffer += decoder.decode(value, { stream: true });
                            const lines = buffer.split('\n');
                            buffer = lines.pop() || '';

                            lines.forEach(line => {
                                line = line.trim();

                                if (!line) {
                                    currentEvent = null;
                                    return;
                                }

                                if (line.startsWith('event:')) {
                                    currentEvent = line.substring(6).trim();
                                    // console.log('SSE Event:', currentEvent);
                                } else if (line.startsWith('data:')) {
                                    try {
                                        const jsonData = line.substring(5).trim();
                                        if (!jsonData) return;

                                        const data = JSON.parse(jsonData);
                                        // console.log('SSE Data:', currentEvent, data);

                                        // Capture content for insertion later if available
                                        if (currentEvent === 'complete' && data.content) {
                                            capturedContent = data.content;
                                        }

                                        // Handle events
                                        handleAgentEvent(data, currentEvent, targetDiv, capturedContent);

                                    } catch (e) {
                                        console.error('Failed to parse SSE data:', e);
                                        console.error('Line content:', line.substring(0, 200));
                                        console.error('Current event:', currentEvent);
                                        // Don't break the stream, just log and continue
                                    }
                                }
                            });

                            return readChunk();
                        } catch (error) {
                            console.error('Error in readChunk:', error);
                            throw error;
                        }
                    }).catch(error => {
                        console.error('Error reading chunk:', error);
                        throw error;
                    });
                }

                return readChunk();

            }).then(() => {
                console.log('AI Agent execution completed');
                // Hide loading indicator
                const loadingIndicator = document.getElementById('agent-stream-loading');
                if (loadingIndicator) {
                    loadingIndicator.style.display = 'none';
                }
                if (typeof hideLoading === 'function') {
                    hideLoading();
                }
                resolve();
            }).catch(error => {
                console.error('AI Agent error:', error);
                // Hide loading indicator
                const loadingIndicator = document.getElementById('agent-stream-loading');
                if (loadingIndicator) {
                    loadingIndicator.style.display = 'none';
                }
                if (typeof hideLoading === 'function') {
                    hideLoading();
                }
                if (typeof showError === 'function') {
                    showError('Error: ' + error.message);
                }
                reject(error);
            });
        });
    };

    /**
     * Handle AI Agent SSE events
     * 
     * @param {object} data Event data
     * @param {string} eventType Event type
     * @param {string} targetDiv Target div ID
     * @param {string} fullContent Full accumulated content for insertion
     */
    function handleAgentEvent(data, eventType, targetDiv, fullContent) {
        const statusDiv = document.getElementById('agent-status');
        const toolsDiv = document.getElementById('agent-tools');
        const resultDiv = document.getElementById('agent-result');

        switch (eventType) {
            case 'connected':
                if (statusDiv) {
                    statusDiv.innerHTML = '<div class="agent-status-item" style="">Connected to AI Agent</div>';
                }
                break;

            case 'status':
                if (statusDiv && data.message) {
                    const statusItem = document.createElement('div');
                    statusItem.className = 'agent-status-item';
                    statusItem.style.cssText = '';

                    // Check if message contains HTML (like section task list)
                    let messageHtml;
                    if (data.message.includes('section-task-list')) {
                        // Render HTML directly for task lists
                        messageHtml = data.message;
                        
                        // Adjust styling for task list container
                        statusItem.style.padding = '0';
                        statusItem.style.margin = '12px 0';

                        // Count total sections and update progress after DOM is updated
                        setTimeout(() => {
                            const totalCount = countSectionsFromTaskList(data.message);
                            if (totalCount > 0) {
                                const completed = countCompletedSections();
                                updateSectionsProgress(completed, totalCount);
                                
                                // Ensure all task items are accessible
                                const statusDiv = document.getElementById('agent-status');
                                if (statusDiv) {
                                    const taskItems = statusDiv.querySelectorAll('[id^="section-task-"]');
                                    console.log('Task list rendered with', taskItems.length, 'sections');
                                }
                            }
                        }, 100);
                    } else {
                        // Check if message contains JSON checklist first
                        const formattedChecklist = formatChecklistContent(data.message);
                        if (formattedChecklist !== data.message) {
                            // It's a checklist, display formatted version
                            messageHtml = formattedChecklist;
                            statusItem.style.padding = '6px 0';
                            statusItem.style.margin = '8px 0';
                        } else {
                            // Check if message is keywords output (not the "Analyzing keywords..." status message)
                            // Keywords output typically: multiple short phrases separated by commas/newlines, no JSON, no HTML
                            const isKeywordsOutput = !data.message.includes('Analyzing keywords') &&
                                !data.message.includes('{') &&
                                !data.message.includes('<') &&
                                !data.message.includes('section-task-list') &&
                                (data.message.split(/[\n,;]/).filter(line => line.trim().length > 0).length >= 3 ||
                                    data.message.match(/[a-zA-Z0-9\s]{2,30}(?:[,;\n]|$)/g)?.length >= 5);

                            if (isKeywordsOutput) {
                                // Format keywords output
                                const formattedKeywords = formatKeywordsContent(data.message);
                                if (formattedKeywords !== data.message) {
                                    messageHtml = formattedKeywords;
                                    statusItem.style.padding = '6px 0';
                                    statusItem.style.margin = '8px 0';
                                } else {
                                    // Regular message, escape for security
                                    messageHtml = escapeHtml(data.message);
                                    if (data.duration) {
                                        messageHtml += ` <span style="font-size: 11px; margin-left: 6px;">(${data.duration}s)</span>`;
                                    }
                                }
                            } else {
                                // Check if message contains HTML content (like section content with images)
                                // This is typically longer content with HTML tags (p, img, h2, etc.)
                                const hasHtmlTags = containsHtml(data.message);
                                const isLongContent = data.message.length > 200; // Section content is usually longer
                                const hasSectionContentPattern = data.message.match(/<(p|div|h[1-6]|img|figure|section)/i);
                                
                                if (hasHtmlTags && (isLongContent || hasSectionContentPattern)) {
                                    // This is HTML content (like section content), render directly
                                    // Try to parse as Markdown first if marked is available
                                    if (typeof marked !== 'undefined') {
                                        try {
                                            // Check if it's already HTML or Markdown
                                            if (data.message.match(/^<[a-z]/i)) {
                                                // Already HTML, render directly
                                                messageHtml = data.message;
                                            } else {
                                                // Try Markdown parsing
                                                messageHtml = marked.parse(data.message);
                                            }
                                        } catch (e) {
                                            console.error('Marked parsing error:', e);
                                            messageHtml = data.message; // Render HTML directly
                                        }
                                    } else {
                                        // No marked available, render HTML directly
                                        messageHtml = data.message;
                                    }
                                    
                                    // Style for section content display
                                    statusItem.style.padding = '12px';
                                    statusItem.style.margin = '12px 0';
                                    statusItem.style.background = '#f8f9fa';
                                    statusItem.style.borderRadius = '8px';
                                    statusItem.style.border = '1px solid #e0e0e0';
                                    statusItem.style.maxHeight = '400px';
                                    statusItem.style.overflowY = 'auto';
                                } else {
                                    // Regular message, escape for security
                                    messageHtml = escapeHtml(data.message);
                                    if (data.duration) {
                                        messageHtml += ` <span style="font-size: 11px; margin-left: 6px;">(${data.duration}s)</span>`;
                                    }
                                }
                            }
                        }
                    }

                    statusItem.innerHTML = messageHtml;
                    statusDiv.appendChild(statusItem);

                    // Auto scroll
                    statusItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                }
                break;

            case 'status_chunk':
                // Handle chunked status updates - update existing item or create new one
                if (statusDiv && data.message && data.message_id) {
                    // Try to find existing status item with this message_id
                    let statusItem = statusDiv.querySelector('[data-message-id="' + data.message_id + '"]');
                    
                    if (!statusItem) {
                        // Create new status item if it doesn't exist
                        statusItem = document.createElement('div');
                        statusItem.className = 'agent-status-item';
                        statusItem.setAttribute('data-message-id', data.message_id);
                        statusItem.style.cssText = '';
                        statusDiv.appendChild(statusItem);
                    }
                    
                    // Update content - escape HTML for security
                    statusItem.innerHTML = escapeHtml(data.message);
                    
                    // Auto scroll
                    statusItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                }
                break;

            case 'tool_start':
                if (toolsDiv && data.tool) {
                    // Record start time
                    timeTrackers[data.tool] = Date.now();

                    const toolItem = document.createElement('div');
                    toolItem.id = 'tool-' + data.tool;
                    toolItem.className = 'agent-tool-item';
                    toolItem.style.cssText = 'margin: 6px 0; background: #fff; border: 1px solid #e0e0e0; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.08); transition: all 0.2s;';
                    toolItem.innerHTML = `
                        <div class="tool-header" style="display: flex; align-items: center; padding: 10px 12px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); cursor: pointer; user-select: none; transition: opacity 0.2s;">
                            <span class="tool-toggle" style="font-size: 10px; color: #fff; margin-right: 10px; transition: transform 0.2s; display: inline-block;">▼</span>
                            <span style="font-size: 16px; margin-right: 8px; filter: brightness(0) invert(1);">🔧</span>
                            <strong style="font-size: 14px; color: #fff; flex: 1; font-weight: 600;">${escapeHtml(data.tool)}</strong>
                            <span style="color: rgba(255,255,255,0.9); font-size: 12px; background: rgba(255,255,255,0.2); padding: 2px 8px; border-radius: 12px; margin-right: 8px;">Step ${data.step}/${data.total}</span>
                            <span class="tool-timer" style="color: rgba(255,255,255,0.9); font-size: 12px; font-weight: 600; min-width: 45px; text-align: right;">0.0s</span>
                        </div>
                        
                    `;
                    toolsDiv.appendChild(toolItem);

                    // Add toggle functionality
                    const header = toolItem.querySelector('.tool-header');
                    const content = toolItem.querySelector('.tool-content');
                    const toggle = toolItem.querySelector('.tool-toggle');
                    if (header && content && toggle) {
                        header.addEventListener('click', function () {
                            const isHidden = content.style.display === 'none';
                            content.style.display = isHidden ? 'block' : 'none';
                            toggle.textContent = isHidden ? '▼' : '▶';
                            toggle.style.transform = isHidden ? 'rotate(0deg)' : 'rotate(-90deg)';
                        });
                        header.addEventListener('mouseenter', function () {
                            this.style.opacity = '0.9';
                        });
                        header.addEventListener('mouseleave', function () {
                            this.style.opacity = '1';
                        });
                    }

                    // Start live timer update
                    const timerElement = toolItem.querySelector('.tool-timer');
                    if (timerElement) {
                        timerIntervals[data.tool] = setInterval(() => {
                            const elapsed = Date.now() - timeTrackers[data.tool];
                            timerElement.textContent = formatElapsedTime(elapsed);
                        }, 100); // Update every 100ms for smooth display
                    }

                    // Auto-scroll to show the latest tool
                    setTimeout(() => {
                        toolItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                    }, 50);
                }
                break;

            case 'tool_complete':
                const toolItemComplete = document.getElementById('tool-' + data.tool);
                if (toolItemComplete) {
                    // Stop the live timer
                    if (timerIntervals[data.tool]) {
                        clearInterval(timerIntervals[data.tool]);
                        delete timerIntervals[data.tool];
                    }

                    // Calculate final duration
                    let finalDuration = '';
                    if (timeTrackers[data.tool]) {
                        const elapsed = Date.now() - timeTrackers[data.tool];
                        finalDuration = formatElapsedTime(elapsed);
                        delete timeTrackers[data.tool];
                    } else if (data.duration) {
                        finalDuration = data.duration + 's';
                    }

                    // Update header gradient to success color
                    const header = toolItemComplete.querySelector('.tool-header');
                    if (header) {
                        header.style.background = 'linear-gradient(135deg, #11998e 0%, #38ef7d 100%)';
                    }

                    // Update timer in header
                    const timerEl = toolItemComplete.querySelector('.tool-timer');
                    if (timerEl && finalDuration) {
                        timerEl.textContent = finalDuration;
                    }

                    // Update status
                    const statusEl = toolItemComplete.querySelector('.tool-status');
                    if (statusEl) {
                        const statusIcon = statusEl.querySelector('.tool-status-icon');
                        if (statusIcon) {
                            statusIcon.textContent = '✅';
                        }
                        statusEl.innerHTML = `<span class="tool-status-icon" style="font-size: 14px;">✅</span><span style="color: #4CAF50; font-weight: 500;">Completed</span>`;
                        if (finalDuration) {
                            statusEl.innerHTML += ` <span style="color: #999; font-size: 11px; margin-left: 6px;">(${finalDuration})</span>`;
                        }
                    }

                    // Update tool details if there's output data (like checklist)
                    const detailsEl = toolItemComplete.querySelector('.tool-details');
                    if (detailsEl) {
                        let outputData = data.output || data.result || data.data;
                        if (outputData) {
                            // Convert to string if it's an object
                            if (typeof outputData === 'object') {
                                outputData = JSON.stringify(outputData, null, 2);
                            }

                            const formattedContent = formatChecklistContent(outputData);
                            if (formattedContent !== outputData) {
                                detailsEl.innerHTML = formattedContent;
                                detailsEl.style.display = 'block';
                            } else {
                                detailsEl.innerHTML = '<pre style="white-space: pre-wrap; word-wrap: break-word; font-size: 12px; color: #666; margin: 0; padding: 8px; background: #f9f9f9; border-radius: 4px;">' + escapeHtml(outputData) + '</pre>';
                                detailsEl.style.display = 'block';
                            }
                        }
                    }

                    // Update border color
                    toolItemComplete.style.borderColor = '#4CAF50';
                    toolItemComplete.style.boxShadow = '0 2px 4px rgba(76, 175, 80, 0.2)';

                    // Collapse by default when completed
                    const content = toolItemComplete.querySelector('.tool-content');
                    const toggle = toolItemComplete.querySelector('.tool-toggle');
                    if (content && toggle) {
                        content.style.display = 'none';
                        toggle.textContent = '▶';
                        toggle.style.transform = 'rotate(-90deg)';
                    }
                }
                break;

            case 'tool_error':
                const toolItemError = document.getElementById('tool-' + data.tool);
                if (toolItemError) {
                    // Stop the live timer
                    if (timerIntervals[data.tool]) {
                        clearInterval(timerIntervals[data.tool]);
                        delete timerIntervals[data.tool];
                    }

                    // Calculate duration at error time
                    let errorDuration = '';
                    if (timeTrackers[data.tool]) {
                        const elapsed = Date.now() - timeTrackers[data.tool];
                        errorDuration = formatElapsedTime(elapsed);
                        delete timeTrackers[data.tool];
                    }

                    // Update header gradient to error color
                    const header = toolItemError.querySelector('.tool-header');
                    if (header) {
                        header.style.background = 'linear-gradient(135deg, #eb3349 0%, #f45c43 100%)';
                    }

                    // Update timer in header
                    const timerEl = toolItemError.querySelector('.tool-timer');
                    if (timerEl && errorDuration) {
                        timerEl.textContent = errorDuration;
                    }

                    // Update status
                    const statusEl = toolItemError.querySelector('.tool-status');
                    if (statusEl) {
                        statusEl.innerHTML = `<span class="tool-status-icon" style="font-size: 14px;">❌</span><span style="color: #f44336; font-weight: 500;">Error: ${escapeHtml(data.error || 'Unknown error')}</span>`;
                        if (errorDuration) {
                            statusEl.innerHTML += ` <span style="color: #999; font-size: 11px; margin-left: 6px;">(${errorDuration})</span>`;
                        }
                    }

                    // Update border color
                    toolItemError.style.borderColor = '#f44336';
                    toolItemError.style.boxShadow = '0 2px 4px rgba(244, 67, 54, 0.2)';

                    // Keep expanded to show error details
                    const content = toolItemError.querySelector('.tool-content');
                    if (content) {
                        content.style.display = 'block';
                    }
                }
                break;

            case 'complete':
                if (resultDiv && data.content) {
                    resultDiv.style.display = 'block';

                    // Check if content is a checklist JSON and format it
                    let displayContent = formatChecklistContent(data.content);

                    // If it's not a checklist, try to parse as Markdown
                    if (displayContent === data.content) {
                        if (typeof marked !== 'undefined') {
                            try {
                                displayContent = marked.parse(data.content);
                            } catch (e) {
                                console.error('Marked parsing error:', e);
                                displayContent = '<pre style="white-space: pre-wrap; word-wrap: break-word; padding: 12px; background: #f5f5f5; border-radius: 4px; font-size: 13px; line-height: 1.5;">' + escapeHtml(data.content) + '</pre>';
                            }
                        } else {
                            displayContent = '<pre style="white-space: pre-wrap; word-wrap: break-word; padding: 12px; background: #f5f5f5; border-radius: 4px; font-size: 13px; line-height: 1.5;">' + escapeHtml(data.content) + '</pre>';
                        }
                    }

                    resultDiv.innerHTML = `
                        <div id="agent-result-container" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 8px; padding: 1px; margin-top: 16px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                            <div style="background: #fff; border-radius: 7px; padding: 16px;">
                                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; padding-bottom: 12px; border-bottom: 2px solid #f0f0f0;">
                                    <h4 style="margin: 0; color: #2E7D32; font-size: 16px; font-weight: 600; display: flex; align-items: center; gap: 8px;">
                                        <span style="font-size: 20px;">✅</span>
                                        Final Result
                                    </h4>
                                </div>
                                <div class="markdown-body" style="background: #fafafa; padding: 16px; border-radius: 6px; overflow-x: auto; margin-bottom: 12px; max-height: 400px; overflow-y: auto; border: 1px solid #e8e8e8; font-size: 14px; line-height: 1.6;">
                                    ${displayContent}
                                </div>
                                <div style="text-align: right; padding-top: 12px; border-top: 1px solid #f0f0f0;">
                                    <button type="button" class="button button-primary button-large" id="agent-insert-btn" style="font-size: 13px; padding: 8px 16px; border-radius: 4px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; color: #fff; cursor: pointer; transition: all 0.2s; box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3);">
                                        <span class="dashicons dashicons-plus-alt2" style="line-height:20px; margin-right:5px; vertical-align: middle;"></span>
                                        Insert to Editor
                                    </button>
                                </div>
                            </div>
                        </div>
                    `;

                    // Bind click event for insert button
                    const insertBtn = document.getElementById('agent-insert-btn');
                    if (insertBtn) {
                        insertBtn.addEventListener('click', function () {
                            insertAgentContentToEditor(data.content);
                        });
                        insertBtn.addEventListener('mouseenter', function () {
                            this.style.transform = 'translateY(-1px)';
                            this.style.boxShadow = '0 4px 8px rgba(102, 126, 234, 0.4)';
                        });
                        insertBtn.addEventListener('mouseleave', function () {
                            this.style.transform = 'translateY(0)';
                            this.style.boxShadow = '0 2px 4px rgba(102, 126, 234, 0.3)';
                        });
                    }

                    // Auto-scroll to the result with smooth behavior
                    const resultContainer = document.getElementById('agent-result-container');
                    if (resultContainer) {
                        setTimeout(() => {
                            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'end' });
                        }, 100);
                    }
                }

                // Hide loading indicator
                const loadingIndicatorComplete = document.getElementById('agent-stream-loading');
                if (loadingIndicatorComplete) {
                    loadingIndicatorComplete.style.display = 'none';
                }

                if (typeof hideLoading === 'function') {
                    hideLoading();
                }
                break;

            case 'error':
                if (resultDiv) {
                    resultDiv.style.display = 'block';
                    resultDiv.innerHTML = `
                        <div style="background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%); border-radius: 8px; padding: 1px; margin-top: 16px; box-shadow: 0 4px 6px rgba(235, 51, 73, 0.2);">
                            <div style="background: #fff; border-radius: 7px; padding: 16px;">
                                <h4 style="margin: 0 0 12px 0; color: #c62828; font-size: 16px; font-weight: 600; display: flex; align-items: center; gap: 8px; padding-bottom: 12px; border-bottom: 2px solid #ffebee;">
                                    <span style="font-size: 20px;">❌</span>
                                    Error
                                </h4>
                                <pre style="white-space: pre-wrap; word-wrap: break-word; background: #ffebee; padding: 12px; border-radius: 4px; color: #c62828; font-size: 13px; line-height: 1.5; border: 1px solid #ffcdd2; margin: 0;">${escapeHtml(data.message || 'Unknown error')}</pre>
                            </div>
                        </div>
                    `;
                    resultDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                }

                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        title: 'Error!',
                        text: data.message || 'Unknown error',
                        icon: 'error',
                        confirmButtonText: 'Close'
                    });
                }

                // Hide loading indicator
                const loadingIndicatorError = document.getElementById('agent-stream-loading');
                if (loadingIndicatorError) {
                    loadingIndicatorError.style.display = 'none';
                }

                if (typeof hideLoading === 'function') {
                    hideLoading();
                }
                break;

            case 'step_output':
                // Handle step output (like checklist or keywords)
                if (data.content || data.output) {
                    const outputContent = data.content || data.output;

                    // Try formatting as keywords first
                    let formattedContent = formatKeywordsContent(outputContent);

                    // If not keywords, try checklist
                    if (formattedContent === outputContent) {
                        formattedContent = formatChecklistContent(outputContent);
                    }

                    // Display in status area
                    if (statusDiv) {
                        const statusItem = document.createElement('div');
                        statusItem.className = 'agent-status-item';
                        statusItem.style.cssText = 'padding: 6px 0; margin: 8px 0; font-size: 13px; color: #333; line-height: 1.4; background: transparent;';
                        
                        // If content was formatted, use formatted version
                        // Otherwise, check if it contains HTML - if yes, render directly; if no, escape for safety
                        if (formattedContent !== outputContent) {
                            statusItem.innerHTML = formattedContent;
                        } else if (containsHtml(outputContent)) {
                            // Content contains HTML tags, render directly
                            statusItem.innerHTML = outputContent;
                        } else {
                            // Plain text, escape for safety
                            statusItem.innerHTML = escapeHtml(outputContent);
                        }
                        
                        statusDiv.appendChild(statusItem);
                        statusItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                    }
                }
                break;

            case 'section_complete':
                // Update task list checkbox when a section is completed and display section result
                if (data.data && typeof data.data.section_index !== 'undefined') {
                    const sectionIndex = data.data.section_index;
                    const sectionId = 'section-task-' + sectionIndex;
                    const sectionText = data.data.section_text || '';
                    
                    // Function to update checkbox and display result
                    const updateCheckbox = () => {
                        // Try to find in statusDiv first (more reliable)
                        const statusDiv = document.getElementById('agent-status');
                        let taskItem = null;
                        
                        if (statusDiv) {
                            taskItem = statusDiv.querySelector('#' + sectionId);
                        }
                        
                        // Fallback: try document.getElementById
                        if (!taskItem) {
                            taskItem = document.getElementById(sectionId);
                        }

                        if (taskItem) {
                            const checkbox = taskItem.querySelector('.task-checkbox');
                            const taskName = taskItem.querySelector('.task-name');

                            if (checkbox) {
                                checkbox.innerHTML = '✓';
                                checkbox.style.backgroundColor = '#4CAF50';
                                checkbox.style.borderColor = '#4CAF50';
                                checkbox.style.color = 'white';
                                checkbox.style.fontWeight = 'bold';
                            }

                            if (taskName) {
                                taskName.style.color = '#4CAF50';
                                taskName.style.textDecoration = 'line-through';
                            }

                            // Display section result if available
                            if (sectionText && sectionText.trim().length > 0) {
                                // Check if result already exists for this section
                                const existingResult = taskItem.parentElement.querySelector(`#section-result-${sectionIndex}`);
                                if (!existingResult) {
                                    // Format and display section content
                                    const formattedContent = formatSectionWritingContent(sectionText);
                                    
                                    // Create result container
                                    const resultContainer = document.createElement('div');
                                    resultContainer.id = `section-result-${sectionIndex}`;
                                    resultContainer.className = 'section-result-container';
                                    resultContainer.style.cssText = 'margin-top: 8px;';
                                    resultContainer.innerHTML = formattedContent;
                                    
                                    // Insert after the task item
                                    if (taskItem.parentElement) {
                                        taskItem.parentElement.insertBefore(resultContainer, taskItem.nextSibling);
                                    } else {
                                        statusDiv.appendChild(resultContainer);
                                    }
                                    
                                    // Scroll to show the result
                                    setTimeout(() => {
                                        resultContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                                    }, 100);
                                }
                            }

                            // Update progress after marking section as complete
                            setTimeout(() => {
                                const totalSections = countSectionsFromTaskList();
                                if (totalSections > 0) {
                                    const completed = countCompletedSections();
                                    updateSectionsProgress(completed, totalSections);
                                }
                            }, 50);
                            
                            return true;
                        }
                        
                        return false;
                    };
                    
                    // Try to update immediately
                    if (!updateCheckbox()) {
                        // If not found, try again after a short delay (DOM might not be ready)
                        setTimeout(() => {
                            if (!updateCheckbox()) {
                                console.warn('Could not find task item for section:', sectionIndex, 'ID:', sectionId);
                            }
                        }, 100);
                    }
                } else {
                    console.warn('section_complete event missing section_index:', data);
                }
                break;

            case 'aithink':
                // Display provider, model, and prompt information - append to agent-status
                if (statusDiv && data.provider && data.model) {
                    // Check if there's an existing think item with same provider/model (for updates)
                    const existingItems = statusDiv.querySelectorAll('.agent-aithink-item');
                    let thinkItem = null;
                    let isUpdate = false;
                    
                    // Find existing item with same provider/model (most recent one)
                    for (let i = existingItems.length - 1; i >= 0; i--) {
                        const item = existingItems[i];
                        const providerSpan = item.querySelector('.aithink-provider');
                        const modelSpan = item.querySelector('.aithink-model');
                        if (providerSpan && modelSpan) {
                            const existingProvider = providerSpan.textContent.trim();
                            const existingModel = modelSpan.textContent.trim();
                            if (existingProvider === data.provider && existingModel === data.model) {
                                thinkItem = item;
                                isUpdate = true;
                                break;
                            }
                        }
                    }
                    
                    // Create new item if not found
                    if (!thinkItem) {
                        thinkItem = document.createElement('div');
                        thinkItem.className = 'agent-aithink-item';
                        thinkItem.style.cssText = '';
                        
                        // Create unique ID for this think item
                        const thinkItemId = 'aithink-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
                        thinkItem.id = thinkItemId;
                        
                        // Set initial collapsed state
                        thinkItem.setAttribute('data-collapsed', 'true');
                        
                        // Append to agent-status
                        statusDiv.appendChild(thinkItem);
                    }
                    
                    // Build header content
                    let headerContent = '<div class="aithink-header" style="display: flex; align-items: center; cursor: pointer; user-select: none;">';
                    headerContent += '<span style="font-size: 16px; margin-right: 8px;">🤔</span>';
                    headerContent += '<div style="flex: 1; min-width: 0;">';
                    headerContent += '<div style="display: flex; align-items: center; gap: 12px; flex-wrap: wrap;">';
                    headerContent += `<span class="aithink-provider" style="font-size: 12px; font-weight: 600; color: #1976d2;">Provider: <span style="color: #333; font-weight: 500;">${escapeHtml(data.provider)}</span></span>`;
                    headerContent += `<span class="aithink-model" style="font-size: 12px; font-weight: 600; color: #1976d2;">Model: <span style="color: #333; font-weight: 500;">${escapeHtml(data.model)}</span></span>`;
                    
                    // Show retry badge if retry
                    if (data.retry) {
                        headerContent += '<span style="font-size: 10px; color: #ff9800; background: #fff3e0; padding: 2px 6px; border-radius: 8px;">Retry</span>';
                    }
                    
                    // Show error badge if failed
                    if (data.failed && data.error) {
                        headerContent += '<span style="font-size: 10px; color: #f44336; background: #ffebee; padding: 2px 6px; border-radius: 8px;">Failed</span>';
                    }
                    
                    headerContent += '</div>';
                    
                    // Prompt preview area (only if prompt is provided and it's a new item or prompt changed)
                    if (data.prompt && !isUpdate) {
                        headerContent += '<div class="aithink-prompt-container" style="margin-top: 6px;">';
                        headerContent += '<div style="font-size: 10px; color: #666; margin-bottom: 4px; font-weight: 600;">Prompt:</div>';
                        headerContent += `<div class="aithink-prompt-text" style="font-size: 11px; color: #333; line-height: 1.4; white-space: pre-wrap; word-wrap: break-word; max-height: 1.4em; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; transition: max-height 0.3s ease;"></div>`;
                        headerContent += '</div>';
                    } else if (data.prompt && isUpdate) {
                        // Update existing item - check if prompt container exists
                        const existingPromptContainer = thinkItem.querySelector('.aithink-prompt-container');
                        if (!existingPromptContainer) {
                            // Add prompt container if it doesn't exist
                            const headerDiv = thinkItem.querySelector('.aithink-header > div');
                            if (headerDiv) {
                                const promptContainer = document.createElement('div');
                                promptContainer.className = 'aithink-prompt-container';
                                promptContainer.style.cssText = 'margin-top: 6px;';
                                promptContainer.innerHTML = '<div style="font-size: 10px; color: #666; margin-bottom: 4px; font-weight: 600;">Prompt:</div>' +
                                    '<div class="aithink-prompt-text" style="font-size: 11px; color: #333; line-height: 1.4; white-space: pre-wrap; word-wrap: break-word; max-height: 1.4em; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; transition: max-height 0.3s ease;"></div>';
                                headerDiv.appendChild(promptContainer);
                            }
                        }
                    }
                    
                    // Error message if failed (always show/update)
                    if (data.failed && data.error) {
                        // Check if error container already exists
                        const existingErrorContainer = thinkItem.querySelector('.aithink-error-container');
                        if (!existingErrorContainer) {
                            headerContent += '<div class="aithink-error-container" style="margin-top: 6px; padding: 6px; background: #ffebee; border-radius: 4px; border: 1px solid #ffcdd2; max-height: none; overflow: visible;">';
                            headerContent += '<div style="font-size: 10px; color: #c62828; margin-bottom: 4px; font-weight: 600;">Error:</div>';
                            headerContent += `<div class="aithink-error-text" style="font-size: 11px; color: #c62828; line-height: 1.4; white-space: pre-wrap; word-wrap: break-word;"></div>`;
                            headerContent += '</div>';
                        }
                    }
                    
                    headerContent += '</div>';
                    headerContent += '<span class="aithink-toggle" style="font-size: 10px; color: #666; margin-left: 8px; transition: transform 0.3s ease; display: inline-block; transform: rotate(-90deg);">▶</span>';
                    headerContent += '</div>';
                    
                    // Update or set innerHTML
                    if (isUpdate) {
                        // Update existing item - only update header badges and add error if needed
                        const headerDiv = thinkItem.querySelector('.aithink-header > div');
                        if (headerDiv) {
                            // Update badges section
                            const badgesDiv = headerDiv.querySelector('div:first-child');
                            if (badgesDiv) {
                                let badgesHtml = `<span class="aithink-provider" style="font-size: 12px; font-weight: 600; color: #1976d2;">Provider: <span style="color: #333; font-weight: 500;">${escapeHtml(data.provider)}</span></span>`;
                                badgesHtml += `<span class="aithink-model" style="font-size: 12px; font-weight: 600; color: #1976d2;">Model: <span style="color: #333; font-weight: 500;">${escapeHtml(data.model)}</span></span>`;
                                if (data.retry) {
                                    badgesHtml += '<span style="font-size: 10px; color: #ff9800; background: #fff3e0; padding: 2px 6px; border-radius: 8px;">Retry</span>';
                                }
                                if (data.failed && data.error) {
                                    badgesHtml += '<span style="font-size: 10px; color: #f44336; background: #ffebee; padding: 2px 6px; border-radius: 8px;">Failed</span>';
                                }
                                badgesDiv.innerHTML = badgesHtml;
                            }
                        }
                    } else {
                        thinkItem.innerHTML = headerContent;
                    }
                    
                    // Stream prompt text 10 characters at a time (only if prompt provided and new item)
                    if (data.prompt && !isUpdate) {
                        const promptTextEl = thinkItem.querySelector('.aithink-prompt-text');
                        if (promptTextEl) {
                            const promptFullText = data.prompt_full || data.prompt;
                            let currentIndex = 0;
                            let isStreaming = true;
                            
                            const streamPrompt = () => {
                                if (currentIndex < promptFullText.length) {
                                    const chunkSize = 10;
                                    currentIndex += chunkSize;
                                    
                                    // Update text content
                                    promptTextEl.textContent = promptFullText.substr(0, currentIndex);
                                    
                                    // Expand while streaming
                                    promptTextEl.style.maxHeight = 'none';
                                    promptTextEl.style.overflow = 'visible';
                                    promptTextEl.style.textOverflow = 'clip';
                                    promptTextEl.style.display = 'block';
                                    promptTextEl.style.webkitLineClamp = '';
                                    promptTextEl.style.webkitBoxOrient = '';
                                    
                                    // Continue streaming
                                    setTimeout(streamPrompt, 50); // 50ms delay between chunks
                                } else {
                                    // Streaming complete - auto collapse to one line
                                    isStreaming = false;
                                    setTimeout(() => {
                                        collapseThinkItem(thinkItem);
                                    }, 500); // Wait 500ms after streaming completes
                                }
                            };
                            
                            // Start streaming
                            streamPrompt();
                        }
                    } else if (data.prompt && isUpdate) {
                        // Update existing prompt if provided
                        const promptTextEl = thinkItem.querySelector('.aithink-prompt-text');
                        if (promptTextEl) {
                            const promptFullText = data.prompt_full || data.prompt;
                            promptTextEl.textContent = promptFullText;
                        }
                    }
                    
                    // Stream error text if failed (always show error)
                    if (data.failed && data.error) {
                        let errorTextEl = thinkItem.querySelector('.aithink-error-text');
                        let errorContainer = thinkItem.querySelector('.aithink-error-container');
                        
                        // Create error container if it doesn't exist
                        if (!errorContainer) {
                            const headerDiv = thinkItem.querySelector('.aithink-header > div');
                            if (headerDiv) {
                                errorContainer = document.createElement('div');
                                errorContainer.className = 'aithink-error-container';
                                errorContainer.style.cssText = 'margin-top: 6px; padding: 6px; background: #ffebee; border-radius: 4px; border: 1px solid #ffcdd2; max-height: none; overflow: visible;';
                                errorContainer.innerHTML = '<div style="font-size: 10px; color: #c62828; margin-bottom: 4px; font-weight: 600;">Error:</div>' +
                                    '<div class="aithink-error-text" style="font-size: 11px; color: #c62828; line-height: 1.4; white-space: pre-wrap; word-wrap: break-word;"></div>';
                                headerDiv.appendChild(errorContainer);
                                errorTextEl = errorContainer.querySelector('.aithink-error-text');
                            }
                        } else {
                            errorTextEl = errorContainer.querySelector('.aithink-error-text');
                        }
                        
                        if (errorTextEl) {
                            const errorFullText = data.error;
                            let currentIndex = 0;
                            
                            const streamError = () => {
                                if (currentIndex < errorFullText.length) {
                                    const chunkSize = 10;
                                    currentIndex += chunkSize;
                                    
                                    // Update text content
                                    errorTextEl.textContent = errorFullText.substr(0, currentIndex);
                                    
                                    // Expand container
                                    if (errorContainer) {
                                        errorContainer.style.maxHeight = 'none';
                                        errorContainer.style.padding = '6px';
                                    }
                                    
                                    // Continue streaming
                                    setTimeout(streamError, 50);
                                }
                            };
                            
                            // Start streaming error
                            streamError();
                        }
                    }
                    
                    // Add click handler for expand/collapse (only if not already added)
                    const header = thinkItem.querySelector('.aithink-header');
                    const toggle = thinkItem.querySelector('.aithink-toggle');
                    if (header && toggle && !header.hasAttribute('data-handler-attached')) {
                        header.setAttribute('data-handler-attached', 'true');
                        header.addEventListener('click', function() {
                            toggleThinkItem(thinkItem);
                        });
                    }
                    
                    // Auto scroll to show the latest think item
                    setTimeout(() => {
                        thinkItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                    }, 50);
                }
                break;

            case 'done':
                console.log('Stream closed');
                break;
        }
    }

    /**
     * Collapse think item to one line
     * 
     * @param {HTMLElement} thinkItem The think item element
     */
    function collapseThinkItem(thinkItem) {
        const promptTextEl = thinkItem.querySelector('.aithink-prompt-text');
        const errorContainer = thinkItem.querySelector('.aithink-error-container');
        const toggle = thinkItem.querySelector('.aithink-toggle');
        
        if (promptTextEl) {
            // Collapse to show only first line using webkit-line-clamp
            promptTextEl.style.maxHeight = '1.4em';
            promptTextEl.style.overflow = 'hidden';
            promptTextEl.style.textOverflow = 'ellipsis';
            promptTextEl.style.display = '-webkit-box';
            promptTextEl.style.webkitLineClamp = '1';
            promptTextEl.style.webkitBoxOrient = 'vertical';
            promptTextEl.style.whiteSpace = 'normal'; // Allow text wrapping for ellipsis
        }
        
        if (errorContainer) {
            errorContainer.style.maxHeight = '0';
            errorContainer.style.padding = '0';
            errorContainer.style.marginTop = '0';
            errorContainer.style.overflow = 'hidden';
        }
        
        if (toggle) {
            toggle.textContent = '▶';
            toggle.style.transform = 'rotate(-90deg)';
        }
        
        thinkItem.setAttribute('data-collapsed', 'true');
    }

    /**
     * Toggle think item expand/collapse
     * 
     * @param {HTMLElement} thinkItem The think item element
     */
    function toggleThinkItem(thinkItem) {
        const promptTextEl = thinkItem.querySelector('.aithink-prompt-text');
        const errorContainer = thinkItem.querySelector('.aithink-error-container');
        const toggle = thinkItem.querySelector('.aithink-toggle');
        const isCollapsed = thinkItem.getAttribute('data-collapsed') === 'true';
        
        if (isCollapsed) {
            // Expand
            if (promptTextEl) {
                promptTextEl.style.maxHeight = 'none';
                promptTextEl.style.overflow = 'visible';
                promptTextEl.style.textOverflow = 'clip';
                promptTextEl.style.display = 'block';
                promptTextEl.style.webkitLineClamp = '';
                promptTextEl.style.webkitBoxOrient = '';
                promptTextEl.style.whiteSpace = 'pre-wrap'; // Restore original wrapping
            }
            
            if (errorContainer) {
                errorContainer.style.maxHeight = 'none';
                errorContainer.style.padding = '6px';
                errorContainer.style.marginTop = '6px';
                errorContainer.style.overflow = 'visible';
            }
            
            if (toggle) {
                toggle.textContent = '▼';
                toggle.style.transform = 'rotate(0deg)';
            }
            
            thinkItem.setAttribute('data-collapsed', 'false');
        } else {
            // Collapse
            collapseThinkItem(thinkItem);
        }
    }

    /**
     * Format elapsed time in seconds
     * 
     * @param {number} milliseconds Elapsed time in milliseconds
     * @returns {string} Formatted time string
     */
    function formatElapsedTime(milliseconds) {
        const seconds = (milliseconds / 1000).toFixed(1);
        return seconds + 's';
    }

    /**
     * Check if content contains valid HTML tags
     * 
     * @param {string} text Text to check
     * @returns {boolean} True if contains HTML tags
     */
    function containsHtml(text) {
        if (!text || typeof text !== 'string') return false;
        // Check for HTML tags pattern (opening and closing tags)
        const htmlTagPattern = /<[a-z][\s\S]*>/i;
        return htmlTagPattern.test(text);
    }

    /**
     * Escape HTML to prevent XSS
     * 
     * @param {string} text Text to escape
     * @returns {string} Escaped text
     */
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * Update sections progress indicator
     * 
     * @param {number} completed Number of completed sections
     * @param {number} total Total number of sections
     */
    function updateSectionsProgress(completed, total) {
        const footer = document.getElementById('agent-progress-footer');
        const progressText = document.getElementById('agent-progress-text');
        const progressBar = document.getElementById('agent-progress-bar');

        if (!footer || !progressText || !progressBar) return;

        if (total > 0) {
            footer.style.display = 'block';
            progressText.textContent = `${completed} / ${total}`;
            const percentage = (completed / total) * 100;
            progressBar.style.width = percentage + '%';

            // Update color based on progress
            if (percentage === 100) {
                progressBar.style.background = 'linear-gradient(90deg, #4caf50 0%, #8bc34a 100%)';
                progressText.style.color = '#4caf50';
            } else if (percentage >= 50) {
                progressBar.style.background = 'linear-gradient(90deg, #ff9800 0%, #ffc107 100%)';
                progressText.style.color = '#ff9800';
            } else {
                progressBar.style.background = 'linear-gradient(90deg, #2196f3 0%, #21cbf3 100%)';
                progressText.style.color = '#2196f3';
            }
        } else {
            footer.style.display = 'none';
        }
    }

    /**
     * Count sections from task list HTML or DOM
     * 
     * @param {string} html HTML content containing section-task-list (optional)
     * @returns {number} Number of sections found
     */
    function countSectionsFromTaskList(html) {
        // First try to count from DOM (more reliable after rendering)
        const statusDiv = document.getElementById('agent-status');
        if (statusDiv) {
            const domItems = statusDiv.querySelectorAll('[id^="section-task-"]');
            if (domItems.length > 0) {
                return domItems.length;
            }
        }

        // Fallback: count from HTML string if provided
        if (html && html.includes('section-task-list')) {
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = html;
            const sectionItems = tempDiv.querySelectorAll('[id^="section-task-"]');
            return sectionItems.length;
        }

        return 0;
    }

    /**
     * Count completed sections from task list
     * 
     * @returns {number} Number of completed sections
     */
    function countCompletedSections() {
        const statusDiv = document.getElementById('agent-status');
        if (!statusDiv) return 0;

        // Count all section-task elements that are completed
        const allTaskItems = statusDiv.querySelectorAll('[id^="section-task-"]');
        let completed = 0;

        allTaskItems.forEach(item => {
            const checkbox = item.querySelector('.task-checkbox');
            const taskName = item.querySelector('.task-name');

            // Check if task is completed
            // Method 1: Check checkbox has checkmark
            if (checkbox && checkbox.textContent.trim() === '✓') {
                completed++;
            }
            // Method 2: Check checkbox background color
            else if (checkbox) {
                const bgColor = window.getComputedStyle(checkbox).backgroundColor;
                if (bgColor === 'rgb(76, 175, 80)' || bgColor === '#4CAF50') {
                    completed++;
                }
            }
            // Method 3: Check task name is strikethrough or green
            else if (taskName) {
                const textDecoration = window.getComputedStyle(taskName).textDecoration;
                const textColor = window.getComputedStyle(taskName).color;
                if (textDecoration.includes('line-through') ||
                    textColor === 'rgb(76, 175, 80)' ||
                    textColor === '#4CAF50') {
                    completed++;
                }
            }
        });

        return completed;
    }

    /**
     * Format keywords output to readable content
     * Also handles section writing content as todo list
     * 
     * @param {string} content Keywords content or section writing content
     * @returns {string} Formatted HTML content
     */
    function formatKeywordsContent(content) {
        if (!content) return '';

        // Check if content is section writing (contains section-related patterns)
        // Exclude keywords content explicitly
        const hasKeywords = content.toLowerCase().includes('keyword') || 
                           content.toLowerCase().includes('main_keywords') ||
                           content.toLowerCase().includes('secondary_keywords') ||
                           content.toLowerCase().includes('lsi_keywords');
        
        const isSectionWriting = !hasKeywords && (
            content.includes('Writing section') || 
            (content.includes('Section') && content.length > 500) ||
            content.match(/^#+\s+[A-Z]/m) || // Markdown headers
            (content.split('\n').length > 10 && content.length > 1000 && !content.match(/^[\w\s,;]+$/)) // Long content with formatting, not just keywords
        );

        // If it's section writing, format as todo list item
        if (isSectionWriting && !content.includes('keywords') && !content.includes('keyword')) {
            return formatSectionWritingContent(content);
        }

        // Try to parse as JSON first
        let jsonData = null;
        let jsonMatch = content.match(/\{[\s\S]*\}/);

        if (jsonMatch) {
            try {
                jsonData = JSON.parse(jsonMatch[0]);
            } catch (e) {
                // Not JSON, continue with text parsing
            }
        }

        // If it's JSON with keywords array
        if (jsonData) {
            let html = '<div class="keywords-content" style="line-height: 1.6;">';

            // Main keywords
            if (jsonData.main_keywords && Array.isArray(jsonData.main_keywords)) {
                html += '<div style="margin-bottom: 12px;">';
                html += '<h4 style="margin: 0 0 8px 0; color: #1976d2; font-size: 13px; font-weight: 600;">🔑 Main Keywords</h4>';
                html += '<div style="display: flex; flex-wrap: wrap; gap: 6px;">';
                jsonData.main_keywords.forEach(keyword => {
                    html += `<span style="display: inline-block; padding: 6px 12px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; border-radius: 16px; font-size: 12px; font-weight: 500; box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);">${escapeHtml(keyword)}</span>`;
                });
                html += '</div></div>';
            }

            // Secondary keywords
            if (jsonData.secondary_keywords && Array.isArray(jsonData.secondary_keywords)) {
                html += '<div style="margin-bottom: 12px;">';
                html += '<h4 style="margin: 0 0 8px 0; color: #f57c00; font-size: 13px; font-weight: 600;">🔸 Secondary Keywords</h4>';
                html += '<div style="display: flex; flex-wrap: wrap; gap: 6px;">';
                jsonData.secondary_keywords.forEach(keyword => {
                    html += `<span style="display: inline-block; padding: 5px 10px; background: #fff3e0; color: #e65100; border: 1px solid #ffb74d; border-radius: 12px; font-size: 11px;">${escapeHtml(keyword)}</span>`;
                });
                html += '</div></div>';
            }

            // LSI keywords
            if (jsonData.lsi_keywords && Array.isArray(jsonData.lsi_keywords)) {
                html += '<div style="margin-bottom: 12px;">';
                html += '<h4 style="margin: 0 0 8px 0; color: #7b1fa2; font-size: 13px; font-weight: 600;">🔗 LSI Keywords</h4>';
                html += '<div style="display: flex; flex-wrap: wrap; gap: 6px;">';
                jsonData.lsi_keywords.forEach(keyword => {
                    html += `<span style="display: inline-block; padding: 4px 9px; background: #f3e5f5; color: #6a1b9a; border: 1px solid #ba68c8; border-radius: 10px; font-size: 11px;">${escapeHtml(keyword)}</span>`;
                });
                html += '</div></div>';
            }

            html += '</div>';
            return html;
        }

        // Parse text format keywords (comma, newline, or bullet separated)
        const keywords = [];
        const lines = content.split(/[\n,;]/);

        lines.forEach(line => {
            line = line.trim();
            // Remove bullet points, dashes, numbers
            line = line.replace(/^[•\-\d\.\)\s]+/, '').trim();
            if (line && line.length > 0 && !line.match(/^(keywords?|main|secondary|lsi):?$/i)) {
                keywords.push(line);
            }
        });

        if (keywords.length > 0) {
            let html = '<div class="keywords-content" style="line-height: 1.6;">';
            html += '<div style="margin-bottom: 12px;">';
           
            html += '<div style="">';

            keywords.forEach((keyword, index) => {
                // First few keywords as primary (larger, more prominent)
                if (index < 5) {
                    html += `<span style="">${escapeHtml(keyword)}</span>`;
                } else {
                    html += `<span style="">${escapeHtml(keyword)}</span>`;
                }
            });

            html += '</div></div></div>';
            return html;
        }

        // If no keywords found, return original content
        return content;
    }

    /**
     * Format section writing content as todo list item with result
     * 
     * @param {string} content Section writing content
     * @returns {string} Formatted HTML content
     */
    function formatSectionWritingContent(content) {
        // Try to parse as Markdown if marked is available
        let displayContent = content;
        if (typeof marked !== 'undefined') {
            try {
                displayContent = marked.parse(content);
            } catch (e) {
                console.error('Marked parsing error:', e);
                displayContent = '<pre style="white-space: pre-wrap; word-wrap: break-word; font-size: 13px; line-height: 1.6; color: #333;">' + escapeHtml(content) + '</pre>';
            }
        } else {
            displayContent = '<pre style="white-space: pre-wrap; word-wrap: break-word; font-size: 13px; line-height: 1.6; color: #333;">' + escapeHtml(content) + '</pre>';
        }

        // Create collapsible section result with checkmark
        const sectionResultId = 'section-result-' + Date.now();
        let html = '<div class="section-writing-result" style="margin: 12px 0; background: #f8f9fa; border-radius: 8px; border: 1px solid #e0e0e0; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">';
        html += '<div class="section-result-header" style="display: flex; align-items: center; padding: 12px 16px; background: linear-gradient(135deg, #4caf50 0%, #8bc34a 100%); cursor: pointer; user-select: none; transition: opacity 0.2s;">';
        html += '<span class="section-checkmark" style="display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; background: #fff; border-radius: 50%; margin-right: 12px; color: #4caf50; font-weight: bold; font-size: 16px; flex-shrink: 0;">✓</span>';
        html += '<span class="section-result-title" style="flex: 1; color: #fff; font-size: 14px; font-weight: 600;">Section đã hoàn thành</span>';
        html += '<span class="section-toggle" style="color: rgba(255,255,255,0.9); font-size: 12px; transition: transform 0.2s; margin-left: 8px;">▼</span>';
        html += '</div>';
        html += `<div class="section-result-content" id="${sectionResultId}" style="display: none; padding: 16px; background: #fff; border-top: 1px solid #e0e0e0; max-height: 400px; overflow-y: auto;">`;
        html += '<div class="markdown-body" style="font-size: 13px; line-height: 1.7; color: #333;">';
        html += displayContent;
        html += '</div>';
        html += '</div>';
        html += '</div>';

        // Add toggle functionality after DOM insertion
        setTimeout(() => {
            const resultDiv = document.getElementById(sectionResultId);
            if (resultDiv) {
                const header = resultDiv.parentElement.querySelector('.section-result-header');
                const toggle = resultDiv.parentElement.querySelector('.section-toggle');
                if (header && toggle) {
                    header.addEventListener('click', function() {
                        const isHidden = resultDiv.style.display === 'none';
                        resultDiv.style.display = isHidden ? 'block' : 'none';
                        toggle.textContent = isHidden ? '▼' : '▶';
                        toggle.style.transform = isHidden ? 'rotate(0deg)' : 'rotate(-90deg)';
                    });
                    header.addEventListener('mouseenter', function() {
                        this.style.opacity = '0.9';
                    });
                    header.addEventListener('mouseleave', function() {
                        this.style.opacity = '1';
                    });
                }
            }
        }, 50);

        return html;
    }

    /**
     * Format checklist JSON to readable content
     * 
     * @param {string|object} content Content that may contain JSON
     * @returns {string} Formatted HTML content
     */
    function formatChecklistContent(content) {
        if (!content) return '';

        let jsonData = null;

        // If content is already an object, use it directly
        if (typeof content === 'object') {
            jsonData = content;
        } else if (typeof content === 'string') {
            // Try to extract JSON from content string
            let jsonMatch = content.match(/\{[\s\S]*\}/);

            if (jsonMatch) {
                try {
                    jsonData = JSON.parse(jsonMatch[0]);
                } catch (e) {
                    // If JSON parsing fails, return original content
                    return content;
                }
            } else {
                // If no JSON found, return original content
                return content;
            }
        } else {
            return String(content);
        }

        // Format JSON to readable HTML
        let html = '<div class="checklist-content" style="line-height: 1.6;">';

        // User Intent
        if (jsonData.user_intent) {
            html += '<div style="margin-bottom: 16px; padding: 12px; background: #f0f7ff; border-left: 4px solid #2196f3; border-radius: 4px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #1976d2; font-size: 14px; font-weight: 600;">🎯 User Intent Analysis</h4>';
            if (jsonData.user_intent.what_they_want) {
                html += `<p style="margin: 6px 0; color: #333;"><strong>What they want:</strong> ${escapeHtml(jsonData.user_intent.what_they_want)}</p>`;
            }
            if (jsonData.user_intent.problems) {
                html += `<p style="margin: 6px 0; color: #333;"><strong>Problems to solve:</strong> ${escapeHtml(jsonData.user_intent.problems)}</p>`;
            }
            if (jsonData.user_intent.purpose) {
                html += `<p style="margin: 6px 0; color: #333;"><strong>Purpose:</strong> ${escapeHtml(jsonData.user_intent.purpose)}</p>`;
            }
            html += '</div>';
        }

        // Search Intent
        if (jsonData.search_intent) {
            html += '<div style="margin-bottom: 16px; padding: 12px; background: #fff3e0; border-left: 4px solid #ff9800; border-radius: 4px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #f57c00; font-size: 14px; font-weight: 600;">🔍 Search Intent Classification</h4>';
            if (jsonData.search_intent.type) {
                html += `<p style="margin: 6px 0; color: #333;"><strong>Type:</strong> ${escapeHtml(jsonData.search_intent.type)}</p>`;
            }
            if (jsonData.search_intent.reason) {
                html += `<p style="margin: 6px 0; color: #333;"><strong>Reason:</strong> ${escapeHtml(jsonData.search_intent.reason)}</p>`;
            }
            html += '</div>';
        }

        // User Expectations
        if (jsonData.user_expectations && Array.isArray(jsonData.user_expectations) && jsonData.user_expectations.length > 0) {
            html += '<div style="margin-bottom: 16px; padding: 12px; background: #f3e5f5; border-left: 4px solid #9c27b0; border-radius: 4px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #7b1fa2; font-size: 14px; font-weight: 600;">✨ What Users Expect</h4>';
            html += '<ul style="margin: 0; padding-left: 20px; color: #333;">';
            jsonData.user_expectations.forEach(expectation => {
                html += `<li style="margin: 4px 0;">${escapeHtml(expectation)}</li>`;
            });
            html += '</ul></div>';
        }

        // Content to Provide
        if (jsonData.content_to_provide) {
            html += '<div style="margin-bottom: 16px; padding: 12px; background: #e8f5e9; border-left: 4px solid #4caf50; border-radius: 4px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #2e7d32; font-size: 14px; font-weight: 600;">📝 What We Should Provide</h4>';

            if (jsonData.content_to_provide.required_sections && Array.isArray(jsonData.content_to_provide.required_sections) && jsonData.content_to_provide.required_sections.length > 0) {
                html += '<p style="margin: 6px 0; color: #333;"><strong>Required Sections:</strong></p>';
                html += '<ul style="margin: 4px 0; padding-left: 20px; color: #333;">';
                jsonData.content_to_provide.required_sections.forEach(section => {
                    html += `<li style="margin: 4px 0;">${escapeHtml(section)}</li>`;
                });
                html += '</ul>';
            }

            if (jsonData.content_to_provide.unique_insights) {
                html += `<p style="margin: 6px 0; color: #333;"><strong>Unique Insights:</strong> ${escapeHtml(jsonData.content_to_provide.unique_insights)}</p>`;
            }

            if (jsonData.content_to_provide.priorities) {
                html += `<p style="margin: 6px 0; color: #333;"><strong>Priorities:</strong> ${escapeHtml(jsonData.content_to_provide.priorities)}</p>`;
            }

            html += '</div>';
        }

        // SEO Opportunities
        if (jsonData.seo_opportunities) {
            html += '<div style="margin-bottom: 16px; padding: 12px; background: #fff9c4; border-left: 4px solid #fbc02d; border-radius: 4px;">';
            html += '<h4 style="margin: 0 0 10px 0; color: #f57f17; font-size: 14px; font-weight: 600;">🚀 SEO Opportunities</h4>';

            if (jsonData.seo_opportunities.lsi_keywords && Array.isArray(jsonData.seo_opportunities.lsi_keywords) && jsonData.seo_opportunities.lsi_keywords.length > 0) {
                html += '<p style="margin: 6px 0; color: #333;"><strong>LSI Keywords:</strong></p>';
                html += '<div style="margin: 4px 0; padding: 8px; background: #fff; border-radius: 4px;">';
                jsonData.seo_opportunities.lsi_keywords.forEach((keyword, index) => {
                    html += `<span style="display: inline-block; margin: 2px 4px; padding: 4px 8px; background: #f5f5f5; border-radius: 3px; font-size: 12px; color: #666;">${escapeHtml(keyword)}</span>`;
                });
                html += '</div>';
            }

            if (jsonData.seo_opportunities.schema) {
                html += `<p style="margin: 6px 0; color: #333;"><strong>Schema:</strong> ${escapeHtml(jsonData.seo_opportunities.schema)}</p>`;
            }

            if (jsonData.seo_opportunities.structure) {
                html += `<p style="margin: 6px 0; color: #333;"><strong>Structure:</strong> ${escapeHtml(jsonData.seo_opportunities.structure)}</p>`;
            }

            html += '</div>';
        }

        html += '</div>';
        return html;
    }

    /**
     * Add AI Agent button to existing interface (optional integration)
     */
    $(document).ready(function () {
        // You can add a button to trigger AI Agent here if needed
        // Example: Add to existing AI box
        if ($('.aiautotool_box1').length > 0) {
            // Find a place to add AI Agent button
            console.log('AI Agent JavaScript loaded');
        }
    });

})(jQuery);
