/**
 * Cursor-Style Chat Interface JavaScript
 * Handles the new dark theme chat interface with step display
 */

(function($) {
    'use strict';
    
    const CursorChat = {
        
        // Configuration
        config: {
            typingDelay: 1000,
            stepAnimationDelay: 300,
            maxMessageHistory: 100,
            standaloneMode: false,
            messageContainerId: 'cursorChatMessages',
            inputId: 'cursorChatInput',
            sendButtonId: 'cursorSendButton',
        },
        
        // State
        state: {
            isTyping: false,
            currentSteps: [],
            stepCounter: 0,
            messageHistory: [],
            isStepExpanded: true,
        },
        
        /**
         * Initialize Cursor Chat
         */
        init: function() {
            this.createChatInterface();
            this.bindEvents();
            // Don't load message history - start fresh each time
            this.clearMessageHistory();
            this.scrollToBottom();
        },
        
        /**
         * Initialize standalone mode (for modal)
         */
        initStandalone: function() {
            this.bindEvents();
            // Don't load message history - start fresh each time
            this.clearMessageHistory();
            this.scrollToBottom();
        },
        
        /**
         * Create the chat interface HTML
         */
        createChatInterface: function() {
            const chatHTML = `
                <div class="cursor-chat-container">
                    <!-- Chat Header -->
                    <div class="cursor-chat-header">
                        <div class="chat-header-left">
                            <h1 class="chat-title">AI Assistant</h1>
                            <p class="chat-subtitle">Powered by AI Auto Tool</p>
                        </div>
                        <div class="chat-header-right">
                            <div class="status-indicator">
                                <div class="status-dot"></div>
                                <span>Online</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Chat Messages -->
                    <div class="cursor-chat-messages" id="cursorChatMessages">
                        <div class="welcome-message">
                            <div class="bot-avatar">🤖</div>
                            <div class="bot-message-content">
                                <p>Xin chào! Tôi là AI Assistant. Tôi có thể giúp bạn:</p>
                                <ul>
                                    <li>Tạo nội dung tự động</li>
                                    <li>Quản lý bài viết</li>
                                    <li>Phân tích dữ liệu</li>
                                    <li>Và nhiều hơn nữa...</li>
                                </ul>
                                <p>Hãy cho tôi biết bạn cần gì!</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Chat Input -->
                    <div class="cursor-chat-input-container">
                        <div class="chat-input-wrapper">
                            <textarea 
                                class="cursor-chat-input" 
                                id="cursorChatInput" 
                                placeholder="Nhập tin nhắn của bạn..."
                                rows="1"
                            ></textarea>
                            <button class="send-button" id="cursorSendButton">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Status Bar -->
                    <div class="status-bar">
                        <div class="status-right">
                            <div class="status-item">
                                <span class="status-icon">📊</span>
                                <span id="progressPercentage">0%</span>
                            </div>
                            <div class="status-item">
                                <span class="status-icon">⏱️</span>
                                <span id="executionTime">0.0s</span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Replace existing chat or append to container
            const $existingChat = $('.bot-chat-section');
            if ($existingChat.length) {
                $existingChat.html(chatHTML);
            } else {
                $('.bot-assistant-container').prepend(`<div class="bot-chat-section">${chatHTML}</div>`);
            }
        },
        
        /**
         * Bind events
         */
        bindEvents: function() {
            const self = this;
            
            // Get element IDs based on mode
            const sendButtonId = this.config.sendButtonId;
            const inputId = this.config.inputId;
            const messageContainerId = this.config.messageContainerId;
            
            // Send message on button click
            $('#' + sendButtonId).on('click', function(e) {
                e.preventDefault();
                self.sendMessage();
            });
            
            // Send message on Enter key (Shift+Enter for new line)
            $('#' + inputId).on('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    self.sendMessage();
                }
            });
            
            // Auto-resize textarea
            $('#' + inputId).on('input', function() {
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 120) + 'px';
            });
            
            // Step toggle
            $(document).on('click', '.step-toggle', function() {
                self.toggleStepDisplay();
            });
            
            // File actions
            $(document).on('click', '.file-action', function() {
                const action = $(this).data('action');
                const fileId = $(this).data('file-id');
                self.handleFileAction(action, fileId);
            });
            
            // Query suggestion buttons
            $(document).on('click', '.query-suggestion-btn', function() {
                const query = $(this).data('query');
                $('#' + inputId).val(query);
                self.sendMessage();
            });
        },
        
        /**
         * Send message
         */
        sendMessage: function() {
            const input = $('#' + this.config.inputId);
            const message = input.val().trim();
            
            if (!message || this.state.isTyping) {
                return;
            }
            
            // Add user message
            this.addMessage('user', message);
            
            // Clear input
            input.val('');
            input.css('height', 'auto');
            
            // Show typing indicator
            this.showTypingIndicator();
            
            // Send to server
            this.queryBot(message);
            
            // Save to history
            this.state.messageHistory.push({
                role: 'user',
                content: message,
                timestamp: Date.now()
            });
        },
        
        /**
         * Query bot via AJAX
         */
        queryBot: function(query) {
            const self = this;
            
            // Get recent conversation history
            const recentHistory = this.state.messageHistory.slice(-10).map(function(msg) {
                return {
                    role: msg.role,
                    content: msg.content
                };
            });
            
            $.ajax({
                url: botAssistantData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'bot_assistant_query',
                    nonce: botAssistantData.nonce,
                    query: query,
                    history: JSON.stringify(recentHistory)
                },
                success: function(response) {
                    self.hideTypingIndicator();
                    
                    if (response.success) {
                        // Handle step-by-step execution
                        if (response.data.step_by_step && response.data.todo_list) {
                            self.handleStepByStepExecution(response.data.todo_list, response.data);
                            return;
                        }
                        
                        // Regular response
                        self.addMessage('bot', response.data.response, response.data.source || 'ai', response.data.debug || {});
                        
                        // Save to history
                        self.state.messageHistory.push({
                            role: 'bot',
                            content: response.data.response,
                            source: response.data.source || 'ai',
                            debug: response.data.debug || {},
                            timestamp: Date.now()
                        });
                    } else {
                        self.addMessage('bot', 'Xin lỗi, tôi gặp lỗi. Vui lòng thử lại.', 'error');
                    }
                },
                error: function() {
                    self.hideTypingIndicator();
                    self.addMessage('bot', 'Không thể xử lý yêu cầu của bạn lúc này.', 'error');
                }
            });
        },
        
        /**
         * Handle step-by-step execution
         */
        handleStepByStepExecution: function(todoList, data) {
            const self = this;
            
            console.log('🔄 Starting step-by-step execution:', todoList);
            
            // Store agent result for completion summary
            self.currentAgentResult = data;
            
            // Show initial message
            const initMessage = data.response || 'Bắt đầu thực hiện...';
            self.addMessage('bot', initMessage, 'execution');
            
            // Create step container
            const stepContainer = self.createStepContainer(todoList);
            $('#' + self.config.messageContainerId).append(stepContainer);
            self.scrollToBottom();
            
            // Execute steps
            self.executeSteps(todoList);
        },
        
        /**
         * Create step container
         */
        createStepContainer: function(todoList) {
            const self = this;
            const stepId = 'steps-' + Date.now();
            
            let stepItemsHTML = '';
            todoList.forEach((todo, index) => {
                const stepNum = index + 1;
                stepItemsHTML += `
                    <div class="step-item" data-step="${index}" data-status="pending">
                        <div class="step-icon pending">${stepNum}</div>
                        <div class="step-content">
                            <p class="step-text">${self.escapeHtml(todo.title || todo.message || `Bước ${stepNum}`)}</p>
                            ${todo.description ? `<p class="step-description">${self.escapeHtml(todo.description)}</p>` : ''}
                        </div>
                    </div>
                `;
            });
            
            return `
                <div class="cursor-step-container" id="${stepId}">
                    <div class="step-header">
                        <div class="step-title">
                            <span>📋 To-dos ${todoList.length}</span>
                        </div>
                        <div class="step-counter">0/${todoList.length}</div>
                        <button class="step-toggle expanded" data-target="${stepId}">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/>
                            </svg>
                        </button>
                    </div>
                    <div class="step-progress">
                        <div class="progress-bar-container">
                            <div class="progress-bar-fill" style="width: 0%"></div>
                        </div>
                        <div class="progress-text">
                            <span>Tiến độ</span>
                            <span id="progressPercentage">0%</span>
                        </div>
                    </div>
                    <div class="step-items">
                        ${stepItemsHTML}
                    </div>
                </div>
            `;
        },
        
        /**
         * Execute steps with animation
         */
        executeSteps: function(todoList) {
            const self = this;
            let currentStep = 0;
            
            const executeNextStep = function() {
                if (currentStep >= todoList.length) {
                    // All done
                    self.updateStepProgress(todoList.length, todoList.length, 100);
                    self.showStepCompletion(self.currentAgentResult);
                    return;
                }
                
                const todo = todoList[currentStep];
                const stepNum = currentStep + 1;
                
                console.log(`📝 Executing step ${stepNum}/${todoList.length}: ${todo.title}`);
                
                // Update current step
                self.updateCurrentStep(currentStep);
                
                // Execute step via AJAX
                $.ajax({
                    url: botAssistantData.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'bot_assistant_execute_tool',
                        nonce: botAssistantData.nonce,
                        function_name: todo.tool,
                        arguments: JSON.stringify(todo.args || {})
                    },
                    success: function(response) {
                        console.log(`✅ Step ${stepNum} completed:`, response);
                        
                        // Update step status
                        self.completeStep(currentStep, response, self);
                        
                        // Update progress
                        const progress = Math.round(((currentStep + 1) / todoList.length) * 100);
                        self.updateStepProgress(currentStep + 1, todoList.length, progress);
                        
                        // Move to next step
                        currentStep++;
                        setTimeout(executeNextStep, self.config.stepAnimationDelay);
                    },
                    error: function() {
                        console.error(`❌ Step ${stepNum} failed`);
                        self.failStep(currentStep);
                        currentStep++;
                        setTimeout(executeNextStep, self.config.stepAnimationDelay);
                    }
                });
            };
            
            // Start execution
            executeNextStep();
        },
        
        /**
         * Update current step
         */
        updateCurrentStep: function(stepIndex) {
            const $stepItem = $(`.step-item[data-step="${stepIndex}"]`);
            $stepItem.removeClass('completed').addClass('current');
            $stepItem.find('.step-icon').removeClass('pending').addClass('current');
        },
        
        /**
         * Complete step
         */
        completeStep: function(stepIndex, response, context) {
            const $stepItem = $(`.step-item[data-step="${stepIndex}"]`);
            $stepItem.removeClass('current').addClass('completed');
            $stepItem.find('.step-icon').removeClass('current').addClass('completed').html('✓');
            
            // Use the provided context or this
            const ctx = context || this;
            
            // Store result in current agent result
            if (this.currentAgentResult && this.currentAgentResult.todos && this.currentAgentResult.todos[stepIndex]) {
                this.currentAgentResult.todos[stepIndex].status = 'completed';
                if (response.success && response.data.message) {
                    this.currentAgentResult.todos[stepIndex].result = {
                        message: response.data.message,
                        success: true
                    };
                }
            }
            
            // Add result if available
            if (response.success && response.data.message) {
                // Preserve line breaks from the message
                const message = response.data.message.replace(/\n/g, '<br>');
                $stepItem.find('.step-content').append(`
                    <div class="step-result" style="margin-top: 8px; color: var(--success-color); font-size: 13px; white-space: pre-line;">
                        ✓ ${ctx.escapeHtml(message)}
                    </div>
                `);
            }
        },
        
        /**
         * Fail step
         */
        failStep: function(stepIndex) {
            const $stepItem = $(`.step-item[data-step="${stepIndex}"]`);
            $stepItem.removeClass('current').addClass('failed');
            $stepItem.find('.step-icon').removeClass('current').addClass('failed').html('✗');
            
            // Store failed status in current agent result
            if (this.currentAgentResult && this.currentAgentResult.todos && this.currentAgentResult.todos[stepIndex]) {
                this.currentAgentResult.todos[stepIndex].status = 'failed';
            }
        },
        
        /**
         * Update step progress
         */
        updateStepProgress: function(completed, total, percentage) {
            $(`.step-counter`).text(`${completed}/${total}`);
            $(`.progress-bar-fill`).css('width', percentage + '%');
            $(`#progressPercentage`).text(percentage + '%');
        },
        
        /**
         * Show step completion with detailed results
         */
        showStepCompletion: function(agentResult = null) {
            let completionMessage = `
                <div class="bot-message-content message-success">
                    <p>🎉 <strong>Hoàn thành!</strong></p>
                    <p>Tất cả các bước đã được thực hiện thành công.</p>
            `;
            
            // Add detailed results if available
            if (agentResult && agentResult.todos) {
                completionMessage += `
                    <div class="completion-summary" style="margin-top: 20px;">
                        <h4 style="color: var(--success-color); margin-bottom: 15px;">📋 Tóm tắt kết quả:</h4>
                        <div class="todo-results">
                `;
                
                agentResult.todos.forEach((todo, index) => {
                    const statusIcon = todo.status === 'completed' ? '✅' : 
                                     todo.status === 'failed' ? '❌' : 
                                     todo.status === 'skipped' ? '⏭️' : '⏳';
                    
                    completionMessage += `
                        <div class="todo-result-item" style="margin-bottom: 12px; padding: 10px; background: var(--bg-secondary); border-radius: 8px; border-left: 3px solid var(--success-color);">
                            <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 5px;">
                                <span style="font-size: 16px;">${statusIcon}</span>
                                <strong style="color: var(--text-primary);">${index + 1}. ${todo.description}</strong>
                            </div>
                    `;
                    
                    if (todo.result && todo.result.message) {
                        completionMessage += `
                            <div style="margin-left: 24px; color: var(--text-secondary); font-size: 13px; white-space: pre-line;">
                                ${this.escapeHtml(todo.result.message)}
                            </div>
                        `;
                    }
                    
                    completionMessage += `</div>`;
                });
                
                completionMessage += `
                        </div>
                    </div>
                `;
            }
            
            completionMessage += `</div>`;
            
            $('#cursorChatMessages').append(completionMessage);
            this.scrollToBottom();
        },
        
        /**
         * Toggle step display
         */
        toggleStepDisplay: function() {
            const $toggle = $('.step-toggle');
            const $stepItems = $('.step-items');
            
            if (this.state.isStepExpanded) {
                $stepItems.slideUp(300);
                $toggle.removeClass('expanded');
                this.state.isStepExpanded = false;
            } else {
                $stepItems.slideDown(300);
                $toggle.addClass('expanded');
                this.state.isStepExpanded = true;
            }
        },
        
        /**
         * Add message to chat
         */
        addMessage: function(type, content, source, debug) {
            const timestamp = new Date().toLocaleTimeString();
            let messageHTML = '';
            
            if (type === 'user') {
                messageHTML = `
                    <div class="cursor-message user">
                        <div class="user-message-content">
                            <p>${this.escapeHtml(content)}</p>
                        </div>
                    </div>
                `;
            } else {
                // Format bot message
                const formattedContent = this.formatBotMessage(content);
                
                // Debug info
                let debugInfo = '';
                if (debug && debug.mode) {
                    const modeIcon = source === 'ai' ? '🤖' : '⚡';
                    debugInfo = `
                        <div class="message-status" style="margin-top: 8px; font-size: 12px; color: var(--text-muted);">
                            ${modeIcon} ${debug.mode}
                        </div>
                    `;
                }
                
                messageHTML = `
                    <div class="cursor-message bot">
                        <div class="bot-avatar">🤖</div>
                        <div class="bot-message-content ${this.getMessageTypeClass(source)}">
                            ${formattedContent}
                            ${debugInfo}
                        </div>
                    </div>
                `;
            }
            
            $('#' + this.config.messageContainerId).append(messageHTML);
            this.scrollToBottom();
        },
        
        /**
         * Format bot message
         */
        formatBotMessage: function(content) {
            // Escape HTML first
            content = this.escapeHtml(content);
            
            // Convert line breaks to <br>
            content = content.replace(/\n/g, '<br>');
            
            // Convert bullet points
            content = content.replace(/^• /gm, '<li>');
            
            // Wrap lists
            if (content.includes('<li>')) {
                content = content.replace(/(<li>.*?<br>)+/g, '<ul>$&</ul>');
                content = content.replace(/<li>(.*?)<br>/g, '<li>$1</li>');
            }
            
            return `<p>${content}</p>`;
        },
        
        /**
         * Get message type class
         */
        getMessageTypeClass: function(source) {
            switch(source) {
                case 'success': return 'message-success';
                case 'error': return 'message-error';
                case 'warning': return 'message-warning';
                default: return '';
            }
        },
        
        /**
         * Show typing indicator
         */
        showTypingIndicator: function() {
            this.state.isTyping = true;
            
            const indicator = `
                <div class="cursor-message bot typing-indicator">
                    <div class="bot-avatar">🤔</div>
                    <div class="typing-indicator">
                        <div class="typing-dots">
                            <div class="typing-dot"></div>
                            <div class="typing-dot"></div>
                            <div class="typing-dot"></div>
                        </div>
                    </div>
                </div>
            `;
            
            $('#' + this.config.messageContainerId).append(indicator);
            this.scrollToBottom();
        },
        
        /**
         * Hide typing indicator
         */
        hideTypingIndicator: function() {
            this.state.isTyping = false;
            $('.typing-indicator').remove();
        },
        
        /**
         * Handle file action
         */
        handleFileAction: function(action, fileId) {
            switch(action) {
                case 'copy':
                    this.copyToClipboard(fileId);
                    break;
                case 'expand':
                    this.expandFile(fileId);
                    break;
            }
        },
        
        /**
         * Copy to clipboard
         */
        copyToClipboard: function(text) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(text).then(() => {
                    this.showNotification('Đã copy!', 'success');
                });
            }
        },
        
        /**
         * Show notification
         */
        showNotification: function(message, type) {
            const $notification = $(`
                <div class="notification notification-${type}" style="
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: var(--bg-tertiary);
                    color: var(--text-primary);
                    padding: 12px 16px;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px var(--shadow-medium);
                    z-index: 1000;
                    animation: slideIn 0.3s ease-out;
                ">
                    ${message}
                </div>
            `);
            
            $('body').append($notification);
            
            setTimeout(() => {
                $notification.fadeOut(300, function() {
                    $(this).remove();
                });
            }, 3000);
        },
        
        /**
         * Scroll to bottom
         */
        scrollToBottom: function() {
            const $messages = $('#' + this.config.messageContainerId);
            $messages.animate({
                scrollTop: $messages[0].scrollHeight
            }, 300);
        },
        
        /**
         * Load message history
         */
        loadMessageHistory: function() {
            const saved = localStorage.getItem('cursor_chat_history');
            if (saved) {
                try {
                    this.state.messageHistory = JSON.parse(saved);
                } catch(e) {
                    console.error('Failed to load message history', e);
                }
            }
        },
        
        /**
         * Clear message history and start fresh
         */
        clearMessageHistory: function() {
            this.state.messageHistory = [];
            localStorage.removeItem('cursor_chat_history');
            console.log('Cursor chat history cleared - starting fresh session');
        },
        
        /**
         * Save message history
         */
        saveMessageHistory: function() {
            if (this.state.messageHistory.length > this.config.maxMessageHistory) {
                this.state.messageHistory = this.state.messageHistory.slice(-this.config.maxMessageHistory);
            }
            
            localStorage.setItem(
                'cursor_chat_history',
                JSON.stringify(this.state.messageHistory)
            );
        },
        
        /**
         * Escape HTML
         */
        escapeHtml: function(text) {
            if (text === null || text === undefined) {
                return '';
            }
            
            text = String(text);
            
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, function(m) { return map[m]; });
        }
    };
    
    // Initialize when document is ready
    $(document).ready(function() {
        // Only initialize if we're on the bot assistant page
        if ($('.bot-assistant-wrap').length) {
            CursorChat.init();
        }
    });
    
    // Save message history before leaving
    $(window).on('beforeunload', function() {
        if (typeof CursorChat.saveMessageHistory === 'function') {
            CursorChat.saveMessageHistory();
        }
    });
    
    // Make CursorChat globally accessible
    window.CursorChat = CursorChat;
    
})(jQuery);
