/**
 * Floating Robot Widget – Cursor Agent Mode
 * AI di động thông minh trong WordPress Admin
 * Hiểu hệ thống, phân tích intent, thực thi tự động
 */

(function($) {
    'use strict';
    
    const FloatingRobot = {
        
        // State
        state: {
            position: { x: 100, y: 100 },
            targetPosition: { x: 100, y: 100 },
            velocity: { x: 0, y: 0 },
            isMoving: false,
            isAnalyzing: false,
            currentAnalysis: null,
            lastMoveTime: 0,
            mode: 'idle', // idle, roaming, analyzing, returning
            roamIntervalId: null,
            currentWorkflowNoTools: false, // Track if current workflow doesn't need tools
            minimized: false, // Track if robot is minimized to corner
            rippleIntervalId: null // Track ripple effect interval
        },
        
        // Configuration
        config: {
            speed: 1.5,
            analysisDuration: 3000,
            roamInterval: 8000,
            minX: 50,
            maxX: window.innerWidth - 100,
            minY: 50,
            maxY: window.innerHeight - 100,
            avoidanceDistance: 80,
        },
        
        // DOM elements
        $robot: null,
        $tooltip: null,
        $modal: null,
        $chatFrame: null,
        $hideBtn: null,
        
        // Page load time
        pageLoadTime: Date.now(),
        
        /**
         * Initialize
         */
        init: function() {
            this.$robot = $('#ai-floating-robot');
            this.$tooltip = $('#ai-floating-robot .robot-tooltip');
            this.$modal = $('#robot-chat-modal');
            this.$hideBtn = $('#ai-floating-robot .robot-hide-btn');
            
            if (!this.$robot.length) {
                return;
            }
            
            this.ensureCSSLoaded();
            this.loadMinimizedState();
            
            // Apply minimized state immediately if needed
            if (this.state.minimized) {
                this.applyMinimizedState();
            }
            
            this.initPosition();
            this.bindEvents();
            
            // Re-apply minimized state after a short delay to ensure DOM is ready and override any CSS
            const self = this;
            setTimeout(function() {
                if (self.state.minimized) {
                    self.applyMinimizedState();
                }
            }, 100);
            
            if (!this.state.minimized) {
                this.startRoaming();
            }
            this.updatePosition();
            this.loadBotName();
            this.monitorPageChanges();
            
            // Track user behavior
            this.initUserTracking();
        },
        
        /**
         * Initialize user behavior tracking
         */
        initUserTracking: function() {
            window.userMouseTrail = [];
            window.userClickedElements = [];
            
            $(document).on('mousemove', function(e) {
                if (window.userMouseTrail.length > 50) {
                    window.userMouseTrail.shift();
                }
                window.userMouseTrail.push({ x: e.pageX, y: e.pageY, t: Date.now() });
            });
            
            $(document).on('click', function(e) {
                const $target = $(e.target);
                const text = $target.text().substring(0, 50);
                const tag = $target.prop('tagName');
                const classes = $target.attr('class') || '';
                window.userClickedElements.push({
                    tag: tag,
                    text: text,
                    classes: classes,
                    time: new Date().toLocaleTimeString()
                });
                if (window.userClickedElements.length > 20) {
                    window.userClickedElements.shift();
                }
            });
        },
        
        /**
         * Ensure CSS is loaded
         */
        ensureCSSLoaded: function() {
            if (!$('#floating-robot-fallback-css').length) {
                this.addFallbackCSS();
            }
            this.applyCriticalStyles();
        },
        
        /**
         * Add fallback CSS
         */
        addFallbackCSS: function() {
            const fallbackCSS = `
                <style id="floating-robot-fallback-css">
                #ai-floating-robot {
                    position: fixed !important; width: 100px !important; height: 100px !important;
                    z-index: 999998 !important; cursor: pointer !important; user-select: none !important;
                    transition: transform 0.3s ease !important; pointer-events: all !important;
                }
                #ai-floating-robot:hover { transform: scale(1.1) !important; }
                .robot-container { position: relative !important; width: 100% !important; height: 100% !important;
                    animation: float 3s ease-in-out infinite !important; }
                .robot-icon { width: 100% !important; height: 100% !important; object-fit: contain !important;
                    filter: drop-shadow(0 4px 8px rgba(0,0,0,0.15)) !important; }
                @keyframes float { 0%,100% { transform: translateY(0px) !important; } 50% { transform: translateY(-10px) !important; } }
                .robot-glow { position: absolute !important; top: 50% !important; left: 50% !important;
                    transform: translate(-50%,-50%) !important; width: 80px !important; height: 80px !important;
                    background: radial-gradient(circle, rgba(102,126,234,0.3) 0%, transparent 70%) !important;
                    border-radius: 50% !important; animation: pulse-glow 2s ease-in-out infinite !important;
                    pointer-events: none !important; }
                @keyframes pulse-glow { 0%,100% { opacity: 0.5 !important; transform: translate(-50%,-50%) scale(1) !important; }
                    50% { opacity: 0.8 !important; transform: translate(-50%,-50%) scale(1.2) !important; } }
                .robot-tooltip { position: absolute !important; bottom: 80px !important; left: 50% !important;
                    transform: translateX(-50%) !important; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
                    color: white !important; padding: 12px 16px !important; border-radius: 12px !important;
                    box-shadow: 0 8px 24px rgba(0,0,0,0.3) !important; white-space: nowrap !important;
                    opacity: 0 !important; visibility: hidden !important; pointer-events: none !important;
                    transition: all 0.3s ease !important; font-size: 13px !important; min-width: 200px !important; }
                .robot-tooltip.visible { opacity: 1 !important; visibility: visible !important; bottom: 90px !important; }
                .robot-chat-modal { position: fixed !important; top: 0 !important; left: 0 !important;
                    width: 100% !important; height: 100% !important; background: rgba(0,0,0,0.7) !important;
                    z-index: 999999 !important; display: flex !important; align-items: center !important;
                    justify-content: center !important; opacity: 0 !important; visibility: hidden !important;
                    transition: all 0.3s ease !important; backdrop-filter: blur(5px) !important; }
                .robot-chat-modal.active { opacity: 1 !important; visibility: visible !important; }
                
                /* Todo List Styles */
                .todo-list-container { margin: 16px 0 !important; border: 1px solid #e5e7eb !important; border-radius: 8px !important; background: #f9fafb !important; }
                .todo-list-header { padding: 12px 16px !important; border-bottom: 1px solid #e5e7eb !important; background: #f3f4f6 !important; border-radius: 8px 8px 0 0 !important; }
                .todo-list-header h5 { margin: 0 !important; font-size: 14px !important; font-weight: 600 !important; color: #374151 !important; }
                .todo-list-items { padding: 8px !important; }
                .todo-item { margin-bottom: 8px !important; padding: 12px !important; background: white !important; border-radius: 6px !important; border: 1px solid #e5e7eb !important; transition: all 0.2s ease !important; }
                .todo-item:hover { box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important; }
                .todo-item-header { display: flex !important; justify-content: space-between !important; align-items: center !important; margin-bottom: 8px !important; }
                .todo-step-info { display: flex !important; align-items: center !important; gap: 8px !important; }
                .todo-step-number { background: #3b82f6 !important; color: white !important; width: 20px !important; height: 20px !important; border-radius: 50% !important; display: flex !important; align-items: center !important; justify-content: center !important; font-size: 11px !important; font-weight: 600 !important; }
                .todo-step-icon { font-size: 16px !important; }
                .todo-step-title { font-weight: 600 !important; color: #374151 !important; font-size: 14px !important; }
                .todo-step-status { display: flex !important; align-items: center !important; gap: 4px !important; font-size: 12px !important; font-weight: 500 !important; }
                .todo-step-status.pending { color: #6b7280 !important; }
                .todo-step-status.executing { color: #f59e0b !important; }
                .todo-step-status.completed { color: #059669 !important; }
                .todo-step-status.failed { color: #dc2626 !important; }
                .todo-item-content { margin-top: 8px !important; }
                .todo-step-description { color: #6b7280 !important; font-size: 13px !important; line-height: 1.4 !important; margin-bottom: 6px !important; }
                .todo-step-tool { font-size: 12px !important; color: #9ca3af !important; }
                .todo-result { margin-top: 8px !important; padding: 8px !important; border-radius: 4px !important; font-size: 12px !important; line-height: 1.4 !important; }
                .todo-result.completed { background: #ecfdf5 !important; border: 1px solid #a7f3d0 !important; color: #065f46 !important; }
                .todo-result.failed { background: #fef2f2 !important; border: 1px solid #fca5a5 !important; color: #991b1b !important; }
                
                /* Execution Progress Bar */
                .execution-progress-bar { margin-bottom: 16px !important; padding: 12px !important; background: #f8fafc !important; border-radius: 6px !important; border: 1px solid #e2e8f0 !important; }
                .progress-info { display: flex !important; justify-content: space-between !important; margin-bottom: 8px !important; }
                .progress-text { font-weight: 600 !important; color: #374151 !important; font-size: 13px !important; }
                .progress-counter { font-weight: 600 !important; color: #3b82f6 !important; font-size: 13px !important; }
                .progress-bar { height: 6px !important; background: #e5e7eb !important; border-radius: 3px !important; overflow: hidden !important; }
                .progress-fill { height: 100% !important; background: linear-gradient(90deg, #3b82f6, #1d4ed8) !important; transition: width 0.3s ease !important; }
                </style>
            `;
            $('head').append(fallbackCSS);
        },
        
        applyCriticalStyles: function() {
            if (this.$robot.length) {
                this.$robot.css({
                    'position': 'fixed', 'width': '100px', 'height': '100px',
                    'z-index': '999998', 'cursor': 'pointer', 'user-select': 'none',
                    'transition': 'transform 0.3s ease', 'pointer-events': 'all'
                });
            }
        },
        
        monitorPageChanges: function() {
            const self = this;
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'childList' && self.$robot.length && !self.$robot.css('position')) {
                        self.ensureCSSLoaded();
                    }
                });
            });
            observer.observe(document.body, { childList: true, subtree: true });
            setInterval(function() {
                if (self.$robot.length && !self.$robot.css('position')) {
                    self.ensureCSSLoaded();
                }
            }, 2000);
        },
        
        initPosition: function() {
            // Position is already set in moveToMinimizedPosition() if minimized
            // So only set random position if not minimized
            if (!this.state.minimized) {
                this.state.position.x = Math.random() * (window.innerWidth - 100) + 50;
                this.state.position.y = Math.random() * (window.innerHeight - 100) + 50;
                this.$robot.css({ 
                    left: this.state.position.x + 'px', 
                    top: this.state.position.y + 'px',
                    width: '100px',
                    height: '100px'
                });
            }
        },
        
        /**
         * Load minimized state from localStorage
         */
        loadMinimizedState: function() {
            try {
                const saved = localStorage.getItem('aiautotool_robot_minimized');
                if (saved === 'true') {
                    this.state.minimized = true;
                } else {
                    this.state.minimized = false;
                }
            } catch (e) {
                console.error('Error loading minimized state:', e);
                this.state.minimized = false;
            }
        },
        
        /**
         * Apply minimized state visually (called after DOM is ready)
         */
        applyMinimizedState: function() {
            if (this.state.minimized && this.$robot.length) {
                this.$robot.addClass('minimized');
                this.moveToMinimizedPosition();
                // Force update position immediately
                this.$robot.css({
                    left: 'auto',
                    right: '20px',
                    top: '20px',
                    width: '50px',
                    height: '50px',
                    transform: 'none'
                });
                // Start ripple effect
                this.startRippleEffect();
            }
        },
        
        /**
         * Save minimized state to localStorage
         */
        saveMinimizedState: function() {
            try {
                localStorage.setItem('aiautotool_robot_minimized', this.state.minimized ? 'true' : 'false');
            } catch (e) {
                console.error('Error saving minimized state:', e);
            }
        },
        
        /**
         * Minimize robot to top-right corner
         */
        minimizeRobot: function() {
            this.state.minimized = true;
            this.stopRoaming();
            this.state.isMoving = false;
            this.moveToMinimizedPosition();
            this.$robot.addClass('minimized');
            this.hideTooltip();
            this.saveMinimizedState();
            // Start ripple effect
            this.startRippleEffect();
        },
        
        /**
         * Restore robot from minimized state
         */
        restoreRobot: function() {
            this.state.minimized = false;
            this.$robot.removeClass('minimized');
            this.stopRippleEffect();
            // Move to a random position
            this.state.position.x = Math.random() * (window.innerWidth - 100) + 50;
            this.state.position.y = Math.random() * (window.innerHeight - 100) + 50;
            this.$robot.css({
                left: this.state.position.x + 'px',
                top: this.state.position.y + 'px',
                width: '100px',
                height: '100px',
                transform: 'none'
            });
            this.startRoaming();
            this.saveMinimizedState();
        },
        
        /**
         * Move robot to minimized position (top-right corner)
         */
        moveToMinimizedPosition: function() {
            const minimizedSize = 50; // Smaller size when minimized
            const margin = 20;
            
            // Calculate position for top-right corner
            const x = window.innerWidth - minimizedSize - margin;
            const y = margin;
            
            this.state.position.x = x;
            this.state.position.y = y;
            this.state.targetPosition.x = x;
            this.state.targetPosition.y = y;
            
            // Use right and top for better positioning in corner
            this.$robot.css({
                left: 'auto',
                right: margin + 'px',
                top: margin + 'px',
                width: minimizedSize + 'px',
                height: minimizedSize + 'px',
                transform: 'none'
            });
            
            // Start ripple effect when minimized and idle
            this.startRippleEffect();
        },
        
        bindEvents: function() {
            const self = this;
            // Handle robot click - if minimized, restore; otherwise open chat
            this.$robot.on('click', function(e) {
                e.stopPropagation();
                if (self.state.minimized) {
                    self.restoreRobot();
                } else {
                    self.openChatModal();
                }
            });
            this.$robot.on('mouseenter', () => {
                if (!self.state.minimized) {
                    self.showTooltip();
                }
            });
            this.$robot.on('mouseleave', () => {
                if (!self.state.minimized) {
                    self.hideTooltip();
                }
            });
            // Hide button click - minimize robot
            this.$hideBtn.on('click', function(e) {
                e.stopPropagation();
                self.minimizeRobot();
            });
            $(document).on('click', '.robot-chat-close', () => self.closeChatModal());
            this.$modal.on('click', function(e) {
                if ($(e.target).hasClass('robot-chat-modal')) self.closeChatModal();
            });
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape' && self.$modal.hasClass('active')) self.closeChatModal();
            });
            $(window).on('resize', () => {
                if (self.state.minimized) {
                    self.moveToMinimizedPosition();
                } else {
                    self.clampPosition();
                }
            });
            
            // Start ripple effect when minimized
            if (self.state.minimized) {
                self.startRippleEffect();
            }
            
            // Re-check and apply minimized state periodically (in case something overrides it)
            setInterval(function() {
                if (self.state.minimized && self.$robot.length && !self.$robot.hasClass('minimized')) {
                    self.applyMinimizedState();
                }
            }, 1000);
        },
        
        startRoaming: function() {
            if (this.state.minimized) {
                return; // Don't roam if minimized
            }
            const self = this;
            // Clear any existing interval
            if (this.state.roamIntervalId) {
                clearInterval(this.state.roamIntervalId);
            }
            const interval = setInterval(() => {
                if (!self.state.isAnalyzing && !self.state.minimized) {
                    self.moveToRandomPosition();
                }
            }, this.config.roamInterval);
            this.state.roamIntervalId = interval;
        },
        
        stopRoaming: function() {
            if (this.state.roamIntervalId) {
                clearInterval(this.state.roamIntervalId);
                this.state.roamIntervalId = null;
            }
        },
        
        moveToRandomPosition: function() {
            if (this.state.isMoving || this.state.isAnalyzing || this.state.minimized) return;
            this.state.mode = 'roaming';
            this.$robot.attr('data-state', 'moving');
            this.state.targetPosition = {
                x: Math.random() * (window.innerWidth - 150) + 75,
                y: Math.random() * (window.innerHeight - 150) + 75
            };
            this.clampTargetPosition();
            this.state.isMoving = true;
        },
        
        updatePosition: function() {
            const self = this;
            function animate() { self.tick(); requestAnimationFrame(animate); }
            animate();
        },
        
        tick: function() {
            // Don't move if minimized
            if (this.state.minimized) return;
            if (!this.state.isMoving) return;
            const dx = this.state.targetPosition.x - this.state.position.x;
            const dy = this.state.targetPosition.y - this.state.position.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            if (distance < 5) { this.onReachedTarget(); return; }
            const angle = Math.atan2(dy, dx);
            this.state.velocity.x = Math.cos(angle) * this.config.speed;
            this.state.velocity.y = Math.sin(angle) * this.config.speed;
            this.state.position.x += this.state.velocity.x;
            this.state.position.y += this.state.velocity.y;
            this.$robot.css({
                left: this.state.position.x + 'px',
                top: this.state.position.y + 'px',
                transform: 'rotate(' + (angle + Math.PI / 2) + 'rad)'
            });
        },
        
        onReachedTarget: function() {
            this.state.isMoving = false;
            this.state.mode = 'idle';
            this.$robot.attr('data-state', 'idle');
            setTimeout(() => this.analyzeCurrentLocation(), 1000);
        },
        
        analyzeCurrentLocation: function() {
            if (this.state.isAnalyzing) return;
            this.state.isAnalyzing = true;
            this.state.mode = 'analyzing';
            this.$robot.attr('data-state', 'analyzing');
            const nearby = this.findNearbyElements();
            this.updateTooltipAnalysis(nearby);
            this.showAnalysisEffect();
            setTimeout(() => {
                this.state.isAnalyzing = false;
                this.state.mode = 'idle';
                this.$robot.attr('data-state', 'idle');
                this.hideAnalysisEffect();
            }, this.config.analysisDuration);
        },
        
        findNearbyElements: function() {
            const robotX = this.state.position.x;
            const robotY = this.state.position.y;
            const radius = 200;
            const $elements = $('body *').filter(function() {
                const $el = $(this);
                const offset = $el.offset();
                if (!offset) return false;
                const elX = offset.left + $el.width() / 2;
                const elY = offset.top + $el.height() / 2;
                const distance = Math.sqrt(Math.pow(elX - robotX, 2) + Math.pow(elY - robotY, 2));
                return distance < radius && $el.is(':visible');
            });
            return this.analyzeElements($elements);
        },
        
        analyzeElements: function($elements) {
            const analysis = { found: [], suggestions: [] };
            $elements.each(function() {
                const $el = $(this);
                const tag = $el.prop('tagName');
                const id = $el.attr('id');
                const classes = $el.attr('class');
                const text = $el.text().substring(0, 30);
                if (tag === 'A' && id === 'toplevel_page_aiautotool-menu') {
                    analysis.found.push({ type: 'plugin_menu', name: 'AI Auto Tool Menu', suggestion: 'Khởi chạy các công cụ AI tại đây' });
                } else if (tag === 'BUTTON' && classes && classes.includes('button-primary')) {
                    analysis.found.push({ type: 'button', name: text || 'Button', suggestion: 'Đây là nút chính thực hiện hành động quan trọng' });
                } else if (tag === 'FORM') {
                    analysis.found.push({ type: 'form', name: 'Form', suggestion: 'Biểu mẫu nhập dữ liệu' });
                }
            });
            if (analysis.found.length === 0) {
                analysis.found.push({ type: 'general', name: 'Giao diện Admin', suggestion: 'Trang quản trị WordPress của bạn' });
            }
            return analysis;
        },
        
        updateTooltipAnalysis: function(analysis) {
            if (analysis.found.length > 0) {
                const suggestion = analysis.found[analysis.found.length - 1].suggestion;
                this.$tooltip.find('.robot-status').text(suggestion);
                this.showTooltip();
            }
        },
        
        showAnalysisEffect: function() { this.$robot.addClass('analyzing'); },
        hideAnalysisEffect: function() { this.$robot.removeClass('analyzing'); },
        
        clampPosition: function() {
            this.state.position.x = Math.max(this.config.minX, Math.min(this.state.position.x, window.innerWidth - 100));
            this.state.position.y = Math.max(this.config.minY, Math.min(this.state.position.y, window.innerHeight - 100));
        },
        
        clampTargetPosition: function() {
            this.state.targetPosition.x = Math.max(this.config.minX, Math.min(this.state.targetPosition.x, window.innerWidth - 100));
            this.state.targetPosition.y = Math.max(this.config.minY, Math.min(this.state.targetPosition.y, window.innerHeight - 100));
        },
        
        showTooltip: function() { if (this.$tooltip) this.$tooltip.addClass('visible'); },
        hideTooltip: function() { if (this.$tooltip) this.$tooltip.removeClass('visible'); },
        
        /**
         * Render standalone chat HTML using JavaScript
         */
        renderStandaloneChatHTML: function(data) {
            const assistantName = this.escapeHtml(data.assistant_name || 'AIAUTOTOOL');
            const roleIntro = data.role_intro || '';
            const hasAi = data.has_ai || false;
            const providerInfo = this.escapeHtml(data.provider_info || '');
            
            // Format welcome message
            let welcomeMsg = '';
            if (roleIntro) {
                welcomeMsg = roleIntro.replace(/\{\{assistant_name\}\}/g, assistantName);
            } else {
                welcomeMsg = `Xin chào! Tôi là ${assistantName}, AI Assistant của bạn! 😊`;
            }
            
            const html = `
                <div class="cursor-chat-container" style="height: 100%; border-radius: 0;">
                    <!-- Chat Header -->
                    <div class="cursor-chat-header">
                        <div class="chat-header-left">
                            <h1 class="chat-title">${assistantName}</h1>
                            <p class="chat-subtitle">AI Assistant</p>
                        </div>
                        <div class="chat-header-right">
                            <div class="status-indicator">
                                <div class="status-dot" style="background: ${hasAi ? 'var(--success-color)' : 'var(--warning-color)'};"></div>
                                <span>${hasAi ? 'AI Online' : 'Basic Mode'}</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Chat Messages -->
                    <div class="cursor-chat-messages" id="cursorChatMessages-standalone">
                        <div class="welcome-message">
                            <div class="bot-avatar">🤖</div>
                            <div class="bot-message-content">
                                <p>${this.formatMultiline(welcomeMsg)}</p>
                                ${!roleIntro ? '<p>Tôi có thể giúp bạn:</p>' : ''}
                                <ul>
                                    <li>📊 Phân tích và thống kê nội dung</li>
                                    <li>🔍 Tìm kiếm và tìm nội dung</li>
                                    <li>⚠️ Cảnh báo sức khỏe website</li>
                                    <li>🤖 Giám sát AI tools</li>
                                    <li>💡 Gợi ý thông minh & hành động tự động</li>
                                </ul>
                                <div style="margin-top: 15px;">
                                    <button class="query-suggestion-btn" data-query="Show me query suggestions" style="
                                        background: var(--accent-primary);
                                        color: white;
                                        border: none;
                                        padding: 8px 16px;
                                        border-radius: 20px;
                                        cursor: pointer;
                                        font-size: 13px;
                                        transition: all 0.3s ease;
                                    ">
                                        💡 Xem những gì tôi có thể hỏi
                                    </button>
                                </div>
                                <div class="message-status" style="margin-top: 8px; font-size: 12px; color: var(--text-muted);">
                                    ${hasAi ? `🤖 ${providerInfo}` : '⚡ Basic Mode'}
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Chat Input -->
                    <div class="cursor-chat-input-container">
                        <div class="chat-input-wrapper">
                            <textarea 
                                class="cursor-chat-input" 
                                id="cursorChatInput-standalone" 
                                placeholder="Hỏi AI Assistant..."
                                rows="1"
                            ></textarea>
                            
                            <button class="send-button" id="cursorSendButton-standalone" title="Gửi tin nhắn">
                                <svg width="18" height="18" 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-standalone">0%</span>
                            </div>
                            <div class="status-item">
                                <span class="status-icon">⏱️</span>
                                <span id="executionTime-standalone">0.0s</span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            return html;
        },
        
        /**
         * Format multiline text (convert newlines to <br>)
         */
        formatMultiline: function(text) {
            if (!text) return '';
            return this.escapeHtml(text).replace(/\n/g, '<br>');
        },
        
        openChatModal: function() {
            console.log('Opening chat modal...');
            this.$modal.addClass('active');
            $('body').addClass('robot-modal-open');
            this.$modal.find('.robot-chat-loading').show();
            this.$modal.find('.robot-chat-content').hide();
            
            // Get chat info and render immediately with JS
            $.ajax({
                url: floatingRobotData.ajaxurl,
                type: 'POST',
                data: { action: 'get_standalone_chat_info', nonce: floatingRobotData.nonce },
                success: (response) => {
                    if (response.success && response.data) {
                        // Render HTML immediately using JS
                        const html = this.renderStandaloneChatHTML(response.data);
                        this.$modal.find('.robot-chat-loading').hide();
                        const $content = this.$modal.find('.robot-chat-content');
                        $content.html(html).fadeIn(300);
                        
                        // Initialize standalone chat
                        if (typeof CursorChat !== 'undefined') {
                            CursorChat.config.standaloneMode = true;
                            CursorChat.config.messageContainerId = 'cursorChatMessages-standalone';
                            CursorChat.config.inputId = 'cursorChatInput-standalone';
                            CursorChat.config.sendButtonId = 'cursorSendButton-standalone';
                            CursorChat.initStandalone();
                        }
                        
                        this.initStandaloneChat();
                        console.log('Chat content rendered, checking for input elements...');
                        console.log('Input found:', $('#cursorChatInput-standalone').length);
                        console.log('Send button found:', $('#cursorSendButton-standalone').length);
                    } else {
                        this.$modal.find('.robot-chat-loading').html('<p style="color:#ef4444;">Error loading chat info.</p>');
                    }
                },
                error: () => {
                    this.$modal.find('.robot-chat-loading').html('<p style="color:#ef4444;">Network error.</p>');
                }
            });
        },
        
        closeChatModal: function() {
            this.$modal.removeClass('active');
            $('body').removeClass('robot-modal-open');
        },
        
        loadBotName: function() {
            // Show typing indicator in tooltip if available
            const $tooltip = this.$tooltip;
            if ($tooltip && $tooltip.length) {
                $tooltip.find('.robot-status').text('Đang tải tên bot...');
                this.showTooltip();
            }
            
            $.ajax({
                url: floatingRobotData.ajaxurl,
                type: 'POST',
                data: { action: 'get_bot_name', nonce: floatingRobotData.nonce },
                success: (response) => {
                    if (response.success && response.data.bot_name) {
                        this.updateBotName(response.data.bot_name);
                        // Update tooltip with bot name
                        if ($tooltip && $tooltip.length) {
                            $tooltip.find('.robot-status').text(`Bot: ${response.data.bot_name}`);
                        }
                    } else {
                        // Reset tooltip on error
                        if ($tooltip && $tooltip.length) {
                            $tooltip.find('.robot-status').text('AI Assistant');
                        }
                    }
                },
                error: () => {
                    // Reset tooltip on error
                    if ($tooltip && $tooltip.length) {
                        $tooltip.find('.robot-status').text('AI Assistant');
                    }
                }
            });
        },
        
        updateBotName: function(name) {
            $('.bot-name-display, .bot-name-header').text(name);
        },
        
        initStandaloneChat: function() {
            const $input = $('#cursorChatInput-standalone');
            const $send = $('#cursorSendButton-standalone');
            const $messages = $('#cursorChatMessages-standalone');
            
            // Auto-resize textarea
            $input.off('input').on('input', function() {
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 200) + 'px';
            });
            
            $send.off('click').on('click', (e) => { e.preventDefault(); this.sendStandaloneMessage(); });
            $input.off('keypress keydown').on('keypress', (e) => {
                if (e.which === 13 && !e.shiftKey) { e.preventDefault(); this.sendStandaloneMessage(); }
            }).on('keydown', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); this.sendStandaloneMessage(); }
            });
            
            $('.query-suggestion-btn').off('click').on('click', (e) => {
                e.preventDefault();
                const query = $(e.currentTarget).data('query');
                if (query) { $input.val(query); $send.trigger('click'); }
            });
            
            $('.quick-action').off('click').on('click', (e) => {
                e.preventDefault();
                const query = $(e.currentTarget).data('query');
                if (query) { $input.val(query); $send.trigger('click'); }
            });
            
            $('.action-confirm').off('click').on('click', (e) => {
                e.preventDefault();
                const actionDataStr = $(e.currentTarget).attr('data-action');
                try {
                    const decoded = actionDataStr.replace(/&quot;/g, '"');
                    const actionData = JSON.parse(decoded);
                    this.executeAction(actionData, $(e.currentTarget).closest('.action-message'));
                } catch (err) { console.error('Parse error:', err); }
            });
            
            $('.action-cancel').off('click').on('click', (e) => {
                e.preventDefault();
                const $msg = $(e.currentTarget).closest('.action-message');
                $msg.find('.action-buttons').hide();
                $msg.append('<p class="action-cancelled" style="color:#999; font-style:italic;">Action cancelled.</p>');
            });
        },
        
        sendStandaloneMessage: function() {
            const $input = $('#cursorChatInput-standalone');
            const message = $input.val()?.trim();
            if (!message) return;
            $input.val('');
            const $messages = $('#cursorChatMessages-standalone');
            const time = new Date().toLocaleTimeString();
            $messages.append(`
                <div class="user-message">
                    <div class="message-content"><p>${this.escapeHtml(message)}</p><div class="message-time">${time}</div></div>
                    <div class="user-avatar">U</div>
                </div>
            `);
            this.startAgenticWorkflow(message, $messages);
        },
        
        
        
        
        
        
        
        /**
         * Agentic Workflow - Simplified: Direct response or SQL query
         */
        startAgenticWorkflow: function(userQuery, $messages) {
            // Reset workflow state
            this.state.currentWorkflowNoTools = false;
            
            this.scrollToBottom();
            
            // Show typing indicator
            const $typingIndicator = this.showTypingIndicator($messages, 'Đang xử lý yêu cầu...');
            
            // Call agentic_start once
            const postData = {
                action: 'bot_assistant_agentic_start',
                nonce: botAssistantData.nonce,
                query: userQuery
            };
            
            $.ajax({
                url: botAssistantData.ajaxurl,
                type: 'POST',
                data: postData,
                success: (response) => {
                    // Hide typing indicator
                    this.hideTypingIndicator($typingIndicator);
                    
                    if (response.success) {
                        this.handleAgenticResponse(response.data, $messages);
                    } else {
                        this.showAnalysisError(response.data?.message || 'Xử lý yêu cầu thất bại', $messages);
                    }
                },
                error: () => {
                    // Hide typing indicator
                    this.hideTypingIndicator($typingIndicator);
                    this.showAnalysisError('Lỗi kết nối khi xử lý yêu cầu', $messages);
                }
            });
        },
        
        handleAgenticResponse: function(responseData, $messages) {
            const { step, response, has_sql, sql_query, sql_result, session_id } = responseData;
            
            // Handle new simplified format with step: 'complete'
            if (step === 'complete') {
                this.showAgenticCompleteResult(responseData, $messages);
                return;
            }
            
            // Fallback: Handle old format (plan/execute/reflect) for backward compatibility
            const { next, data, execution_results, no_tools_needed } = responseData;
            
            // Track if this workflow doesn't need tools (from plan step)
            if (step === 'plan' && no_tools_needed) {
                this.state.currentWorkflowNoTools = true;
            }
            
            // Show step result (include execution_results for reflect step)
            if (step === 'reflect' && execution_results) {
                this.showAgenticStepResult(step, { ...data, execution_results: execution_results }, $messages);
            } else {
                // Pass no_tools_needed flag to step result display for better UX
                this.showAgenticStepResult(step, { ...data, no_tools_needed: no_tools_needed }, $messages);
            }
            
            // Continue to next step if not done
            if (next && next !== 'done') {
                setTimeout(() => {
                    this.agenticStep(next, { session_id: session_id }, $messages);
                }, 1000);
            } else {
                // Only show "Workflow Complete" if tools were actually used
                if (!this.state.currentWorkflowNoTools) {
                    this.showAgenticFinalResult(data, $messages);
                }
                // Reset flag for next workflow
                this.state.currentWorkflowNoTools = false;
            }
        },
        
        showAgenticCompleteResult: function(responseData, $messages) {
            const { response, has_sql, sql_query, sql_result } = responseData;
            
            let html = '';
            
            // Main response content
            if (response) {
                html += `
                    <div class="bot-message agentic-complete">
                        <div class="bot-avatar">💬</div>
                        <div class="message-content">
                            <div style="line-height: 1.6; font-size: 14px; word-wrap: break-word;">
                                ${this.formatStepResult(response)}
                            </div>
                        </div>
                    </div>
                `;
            }
            
            // Show SQL information if SQL was used
            if (has_sql && sql_query) {
                let sqlInfoHtml = `
                    <div class="bot-message agentic-sql-info">
                        <div class="bot-avatar">🔍</div>
                        <div class="message-content">
                            <h4 style="margin-bottom: 10px; color: #495057;">Thông tin truy vấn SQL</h4>
                            <div style="margin-bottom: 10px;">
                                <strong style="color: #6c757d; font-size: 13px;">SQL Query:</strong>
                                <pre style="background: #f8f9fa; padding: 10px; border-radius: 5px; overflow-x: auto; font-size: 12px; margin: 5px 0;">${this.escapeHtml(sql_query)}</pre>
                            </div>
                `;
                
                // Show SQL result if available
                if (sql_result) {
                    if (sql_result.success) {
                        sqlInfoHtml += `
                            <div style="margin-top: 10px; padding: 10px; background: #d4edda; border-left: 4px solid #28a745; border-radius: 5px;">
                                <strong style="color: #155724;">✅ Kết quả thành công</strong>
                        `;
                        
                        if (sql_result.message) {
                            sqlInfoHtml += `
                                <div style="margin-top: 8px; color: #155724;">${this.escapeHtml(sql_result.message)}</div>
                            `;
                        }
                        
                        if (sql_result.data) {
                            let dataStr = '';
                            if (typeof sql_result.data === 'string') {
                                dataStr = sql_result.data;
                            } else if (typeof sql_result.data === 'object') {
                                dataStr = JSON.stringify(sql_result.data, null, 2);
                            } else {
                                dataStr = String(sql_result.data);
                            }
                            
                            sqlInfoHtml += `
                                <div style="margin-top: 10px;">
                                    <strong style="color: #155724; font-size: 13px;">Dữ liệu:</strong>
                                    <pre style="background: #ffffff; padding: 10px; border-radius: 5px; overflow-x: auto; font-size: 12px; margin: 5px 0; max-height: 300px; overflow-y: auto;">${this.escapeHtml(dataStr)}</pre>
                                </div>
                            `;
                        }
                        
                        sqlInfoHtml += `</div>`;
                    } else {
                        sqlInfoHtml += `
                            <div style="margin-top: 10px; padding: 10px; background: #f8d7da; border-left: 4px solid #dc3545; border-radius: 5px;">
                                <strong style="color: #721c24;">❌ Lỗi thực thi SQL</strong>
                                <div style="margin-top: 8px; color: #721c24;">${this.escapeHtml(sql_result.error || 'Unknown error')}</div>
                            </div>
                        `;
                    }
                }
                
                sqlInfoHtml += `</div></div>`;
                html += sqlInfoHtml;
            }
            
            if (html) {
                $messages.append(html);
                this.scrollToBottom();
            }
        },
        
        // Keep old agenticStep for backward compatibility
        agenticStep: function(step, data, $messages) {
            // Map step names to correct action names
            const actionMap = {
                'start': 'bot_assistant_agentic_start',
                'execute': 'bot_assistant_agentic_execute', 
                'reflect': 'bot_assistant_agentic_reflect'
            };
            
            const action = actionMap[step];
            if (!action) {
                this.showAnalysisError(`Unknown step: ${step}`, $messages);
                return;
            }
            
            // Show typing indicator with step-specific message
            const stepMessages = {
                'start': 'Đang khởi tạo workflow...',
                'execute': 'Đang thực thi các bước...',
                'reflect': 'Đang phân tích kết quả...'
            };
            const $typingIndicator = this.showTypingIndicator($messages, stepMessages[step] || 'Đang xử lý...');
            
            const postData = {
                action: action,
                nonce: botAssistantData.nonce,
                ...data
            };
            
            $.ajax({
                url: botAssistantData.ajaxurl,
                type: 'POST',
                data: postData,
                success: (response) => {
                    // Hide typing indicator
                    this.hideTypingIndicator($typingIndicator);
                    
                    if (response.success) {
                        this.handleAgenticResponse(response.data, $messages);
                    } else {
                        this.showAnalysisError(response.data?.message || `${step} failed`, $messages);
                    }
                },
                error: () => {
                    // Hide typing indicator
                    this.hideTypingIndicator($typingIndicator);
                    this.showAnalysisError(`Network error during ${step}`, $messages);
                }
            });
        },
        
        showAgenticStepResult: function(step, data, $messages) {
            let stepTitle, stepIcon, stepContent;
            
            switch (step) {
                case 'plan':
                    stepTitle = '📋 Planning';
                    stepIcon = '📋';
                    
                    // If no tools needed, skip showing plan step details
                    if (data.no_tools_needed) {
                        stepTitle = '';
                        stepIcon = '';
                        stepContent = '';
                    } else {
                        stepContent = `
                            <strong>Analysis:</strong> ${data.analysis || 'N/A'}<br>
                            <strong>Tools:</strong> ${(data.tools_needed || []).join(', ') || 'Không có'}<br>
                            <strong>Steps:</strong> ${(data.steps || []).length} bước<br>
                            <strong>Time:</strong> ${data.estimated_time || 'N/A'}
                        `;
                    }
                    break;
                    
                case 'execute':
                    stepTitle = '⚙️ Executing';
                    stepIcon = '⚙️';
                    // Ensure data is an array
                    const executionData = Array.isArray(data) ? data : (data?.execution_results || []);
                    stepContent = `
                        <strong>Executed Steps:</strong><br>
                        ${executionData.length > 0 ? executionData.map(result => {
                            const successIcon = result.result?.success ? '✅' : '❌';
                            const resultData = result.result?.data ? JSON.stringify(result.result.data, null, 2) : '';
                            const resultMessage = result.result?.message || '';
                            const argsData = result.args ? JSON.stringify(result.args, null, 2) : '{}';
                            const errorData = result.result?.error ? JSON.stringify(result.result.error, null, 2) : '';
                            
                            return `
                                <div style="margin: 15px 0; padding: 15px;  border-radius: 8px; border-left: 4px solid ${result.result?.success ? '#28a745' : '#dc3545'};">
                                    <div style="display: flex; align-items: center; margin-bottom: 10px;">
                                        <strong style="font-size: 16px;">Step ${result.step}: ${result.action}</strong>
                                        <span style="margin-left: 10px; font-size: 18px;">${successIcon}</span>
                                    </div>
                                    
                                    <div style="margin-bottom: 10px;">
                                        <strong style="color: #6c757d;">📝 Description:</strong><br>
                                        <em style="color: #495057;">${result.description}</em>
                                    </div>
                                    
                                    <div style="margin-bottom: 10px;">
                                        <strong style="color: #6c757d;">🔧 Arguments:</strong><br>
                                        <pre style="  font-size: 12px; overflow-x: auto; margin: 5px 0; ">${argsData}</pre>
                                    </div>
                                    
                                    ${resultMessage ? `
                                        <div style="margin-bottom: 10px;">
                                            <strong style="color: #6c757d;">💬 Message:</strong><br>
                                            <div style="color: ${result.result?.success ? '#28a745' : '#dc3545'}; font-weight: 500; margin: 5px 0;">${resultMessage}</div>
                                        </div>
                                    ` : ''}
                                    
                                    ${resultData ? `
                                        <div style="margin-bottom: 10px;">
                                            <strong style="color: #6c757d;">📊 Result Data:</strong><br>
                                            <pre style=" border-radius: 4px; font-size: 12px; overflow-x: auto; margin: 5px 0; ">${resultData}</pre>
                                        </div>
                                    ` : ''}
                                    
                                    ${errorData ? `
                                        <div style="margin-bottom: 10px;">
                                            <strong style="color: #6c757d;">❌ Error:</strong><br>
                                            <pre style=" border-radius: 4px; font-size: 12px; overflow-x: auto; margin: 5px 0;  color: #721c24;">${errorData}</pre>
                                        </div>
                                    ` : ''}
                                    
                                    <div style="margin-top: 10px; padding-top: 10px; border-top: 1px solid #dee2e6;">
                                        <small style="color: #6c757d;">
                                            <strong>Status:</strong> ${result.result?.success ? 'Success' : 'Failed'} | 
                                            <strong>Timestamp:</strong> ${new Date().toLocaleTimeString()}
                                        </small>
                                    </div>
                                </div>
                            `;
                        }).join('') : '<em style="color: #6c757d;">Không có bước nào được thực thi.</em>'}
                    `;
                    break;
                    
                case 'reflect':
                    // If no execution results, this is a direct AI response (no tools needed)
                    const hasExecutionResults = data.execution_results && Array.isArray(data.execution_results) && data.execution_results.length > 0;
                    
                    if (!hasExecutionResults && data.analysis) {
                        // Direct AI response - simple and clean
                        stepTitle = '';
                        stepIcon = '';
                        stepContent = `
                            <div style="line-height: 1.6; font-size: 14px;  word-wrap: break-word;">
                                ${this.formatStepResult(data.analysis)}
                            </div>
                        `;
                    } else {
                        // Show execution results with analysis
                        stepTitle = '✅ Kết quả';
                        stepIcon = '✅';
                        
                        // Hiển thị kết quả thực thi từ tools
                        let executionResultsHtml = '';
                        if (hasExecutionResults) {
                            executionResultsHtml = data.execution_results.map(result => {
                                const successIcon = result.result?.success ? '✅' : '❌';
                                const resultData = result.result?.data;
                                const resultMessage = result.result?.message || '';
                                const errorData = result.result?.error;
                                
                                // Format kết quả data
                                let formattedData = '';
                                if (resultData) {
                                    if (typeof resultData === 'string') {
                                        formattedData = resultData;
                                    } else if (typeof resultData === 'object') {
                                        // Hiển thị data dễ đọc hơn
                                        if (resultData.message) {
                                            formattedData = resultData.message;
                                        } else if (resultData.details) {
                                            formattedData = resultData.details;
                                        } else {
                                            formattedData = JSON.stringify(resultData, null, 2);
                                        }
                                    }
                                }
                                
                                // Format error data
                                let formattedError = '';
                                if (errorData) {
                                    if (typeof errorData === 'string') {
                                        formattedError = errorData;
                                    } else if (typeof errorData === 'object') {
                                        formattedError = JSON.stringify(errorData, null, 2);
                                    } else {
                                        formattedError = String(errorData);
                                    }
                                }
                                
                                return `
                                    <div style="margin: 10px 0; padding: 12px; background: ${result.result?.success ? '' : '#f8d7da'}; border-radius: 6px; border-left: 4px solid ${result.result?.success ? '#28a745' : '#dc3545'};">
                                        <div style="display: flex; align-items: center; margin-bottom: 8px;">
                                            <span style="font-size: 18px; margin-right: 8px;">${successIcon}</span>
                                            <strong>${result.action || 'Tool'}</strong>
                                        </div>
                                        ${result.description ? `<div style="margin-bottom: 6px; color: #6c757d; font-size: 13px;">${result.description}</div>` : ''}
                                        ${resultMessage ? `<div style="margin-bottom: 6px; color: ${result.result?.success ? '#155724' : '#721c24'};"><strong>${resultMessage}</strong></div>` : ''}
                                        ${formattedData ? `<div style="margin-top: 8px; padding: 8px;  border-radius: 4px; font-size: 13px;  word-wrap: break-word;">${this.escapeHtml(formattedData)}</div>` : ''}
                                        ${formattedError ? `<div style="margin-top: 8px; padding: 8px;  border-radius: 4px; color: #856404; font-size: 13px;"><strong>Lỗi:</strong> ${this.escapeHtml(formattedError)}</div>` : ''}
                                    </div>
                                `;
                            }).join('');
                        }
                        
                        stepContent = `
                            ${executionResultsHtml ? `
                                <div style="margin-bottom: 15px;">
                                    <strong style="color: #495057; font-size: 14px;">Kết quả thực thi:</strong>
                                    ${executionResultsHtml}
                                </div>
                            ` : ''}
                            
                            <div style="margin-top: 15px; padding-top: 15px; border-top: 2px solid #dee2e6;">
                                <div style="margin-bottom: 10px;">
                                    <strong style="color: #495057;">Trạng thái:</strong> 
                                    <span style="font-size: 16px; font-weight: bold; color: ${data.result_ok ? '#28a745' : '#dc3545'};">
                                        ${data.result_ok ? '✅ Thành công' : '❌ Cần cải thiện'}
                                    </span>
                                </div>
                                ${data.analysis ? `
                                    <div style="margin-top: 10px; padding: 10px; border-radius: 5px; border-left: 4px solid #007bff;">
                                        <strong style="color: #495057; font-size: 13px;">Đánh giá:</strong><br>
                                        <div style="margin-top: 5px; font-size: 13px; line-height: 1.5; word-wrap: break-word;">${this.formatStepResult(data.analysis)}</div>
                                    </div>
                                ` : ''}
                            </div>
                        `;
                    }
                    break;
            }
            
            // Only show message if there's content
            if (stepContent || stepTitle) {
                // If no title and icon, it's a simple direct response - remove padding and background
                const isSimpleResponse = !stepTitle && !stepIcon;
                const messageContentStyle = isSimpleResponse 
                    ? 'style="padding: 0 !important; background: transparent !important; box-shadow: none !important; border-radius: 0 !important;"'
                    : '';
                const botMessageStyle = isSimpleResponse
                    ? 'style="margin-bottom: 10px !important;"'
                    : '';
                const botMessageClass = isSimpleResponse
                    ? 'bot-message agentic-step simple-response'
                    : 'bot-message agentic-step';
                
                const html = `
                    <div class="${botMessageClass}" ${botMessageStyle}>
                        ${stepIcon ? `<div class="bot-avatar">${stepIcon}</div>` : ''}
                        <div class="message-content" ${messageContentStyle}>
                            ${stepTitle ? `<h4>${stepTitle}</h4>` : ''}
                            ${stepContent ? stepContent : ''}
                        </div>
                    </div>
                `;
                $messages.append(html);
                this.scrollToBottom();
            }
        },
        
        showAgenticFinalResult: function(data, $messages) {
            const html = `
                <div class="bot-message agentic-final">
                    <div class="bot-avatar">🎯</div>
                    <div class="message-content">
                        <h4>Workflow Complete</h4>
                        <p><strong>Final Result:</strong> ${data.result_ok ? '✅ Thành công' : '❌ Cần cải thiện'}</p>
                        <p><strong>Success Rate:</strong> ${data.success_rate?.toFixed(1) || 0}%</p>
                        ${data.recommendations && data.recommendations.length > 0 ? 
                            `<p><strong>Recommendations:</strong><br>${data.recommendations.join('<br>')}</p>` : ''
                        }
                    </div>
                </div>
            `;
            $messages.append(html);
            this.scrollToBottom();
        },
        
        showToolResult: function(data, $messages) {
            const html = `
                <div class="bot-message tool-result">
                    <div class="bot-avatar">✅</div>
                    <div class="message-content">
                        <h4>Tool Execution Result</h4>
                        <div class="result-content">
                            ${data.success ? 
                                `<p style="color: #10b981;"><strong>✅ Success:</strong> ${data.message || 'Tool executed successfully'}</p>` :
                                `<p style="color: #ef4444;"><strong>❌ Error:</strong> ${data.error || 'Tool execution failed'}</p>`
                            }
                            ${data.data ? `<pre style="background: #f3f4f6; padding: 10px; border-radius: 5px; overflow-x: auto;">${JSON.stringify(data.data, null, 2)}</pre>` : ''}
                        </div>
                    </div>
                </div>
            `;
            $messages.append(html);
            this.scrollToBottom();
        },
        
        executeDirectTool: function(toolName, toolArgs, $messages) {
            // Show direct execution message
            const html = `
                <div class="bot-message direct-execution">
                    <div class="bot-avatar">⚡</div>
                    <div class="message-content">
                        <h4>Thực thi trực tiếp</h4>
                        <p>Đang gọi tool: <strong>${toolName}</strong></p>
                    </div>
                </div>
            `;
            $messages.append(html);
            this.scrollToBottom();
            
            // Show typing indicator
            const $typingIndicator = this.showTypingIndicator($messages, `Đang thực thi tool: ${toolName}...`);
            
            // Execute tool directly
            $.ajax({
                url: botAssistantData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'bot_assistant_execute_tool',
                    nonce: botAssistantData.nonce,
                    function_name: toolName,
                    arguments: JSON.stringify(toolArgs || {})
                },
                success: (response) => {
                    // Hide typing indicator
                    this.hideTypingIndicator($typingIndicator);
                    
                    if (response.success) {
                        this.showToolResult(response.data, $messages);
                    } else {
                        this.showAnalysisError(response.data?.message || 'Tool execution failed', $messages);
                    }
                },
                error: () => {
                    // Hide typing indicator
                    this.hideTypingIndicator($typingIndicator);
                    this.showAnalysisError('Network error during tool execution', $messages);
                }
            });
        },
        
        
        
        
        
        getChatHistory: function() {
            const messages = [];
            $('.user-message, .bot-message').each(function() {
                const $msg = $(this);
                const isUser = $msg.hasClass('user-message');
                const content = $msg.find('.message-content p').text().trim();
                const time = $msg.find('.message-time').text();
                if (content) messages.push({ role: isUser ? 'user' : 'bot', content, timestamp: time });
            });
            return messages.slice(-15);
        },
        
        getAvailableTools: function() {
            return ['create_post','scan_malware','analyze_content','generate_images','optimize_seo','backup_site','update_plugins','check_security'];
        },
        
        getWebsiteResources: function() {
            return {
                wp_version: $('meta[name="wp-version"]').attr('content') || 'unknown',
                php_version: window.floatingRobotData?.php_version || 'unknown',
                memory_limit: window.floatingRobotData?.memory_limit || 'unknown',
                max_upload_size: window.floatingRobotData?.max_upload_size || 'unknown',
                posts_count: this.getCount('.post-count'),
                pages_count: this.getCount('.page-count'),
                media_count: this.getCount('.media-count'),
                users_count: this.getCount('.user-count'),
                active_plugins: this.getActivePlugins(),
                active_theme: this.getActiveTheme(),
                last_backup: $('.last-backup').text() || 'Chưa có',
                security_status: this.getSecurityStatus(),
                current_screen: this.getCurrentAdminScreen(),
                current_url: window.location.href,
                visible_elements: this.getVisibleElementSummary()
            };
        },
        
        getCount: function(selector) {
            const text = $(selector).text();
            return text ? parseInt(text.replace(/\D/g, '')) || 0 : 0;
        },
        
        getActivePlugins: function() {
            return Array.from($('.plugin-card .plugin-name')).map(el => $(el).text().trim()).slice(0, 20);
        },
        
        getActiveTheme: function() { return $('.theme-active .theme-name').text() || 'unknown'; },
        
        getSecurityStatus: function() {
            const issues = [];
            if ($('.health-check-failed').length) issues.push('health-check');
            if ($('.update-nag').length) issues.push('updates-pending');
            return issues.length > 0 ? issues : ['good'];
        },
        
        getCurrentAdminScreen: function() {
            const classes = $('body').attr('class') || '';
            const match = classes.match(/wp-admin|post-php|edit-php|dashboard|toplevel_page_[^ ]+/g);
            return match ? match.join(', ') : 'unknown';
        },
        
        getVisibleElementSummary: function() {
            const elements = {};
            $('h1, h2, button, .button-primary, form, .notice').each(function() {
                const $el = $(this);
                const tag = $el.prop('tagName').toLowerCase();
                const text = $el.text().substring(0, 50);
                if (!elements[tag]) elements[tag] = [];
                elements[tag].push(text);
            });
            return elements;
        },
        
        getUserBehaviorContext: function() {
            return {
                time_on_page: Math.round((Date.now() - this.pageLoadTime) / 1000),
                scroll_depth: window.scrollY / (document.body.scrollHeight - window.innerHeight),
                mouse_movements: window.userMouseTrail?.length || 0,
                clicked_elements: window.userClickedElements || []
            };
        },
        
        showAnalysisError: function(msg, $messages) {
            const html = `
                <div class="bot-message analysis-error">
                    <div class="bot-avatar">Cross</div>
                    <div class="message-content">
                        <h4>Error</h4><p>${this.escapeHtml(msg)}</p>
                        <button class="button retry-analysis-btn">Retry</button>
                    </div>
                </div>
            `;
            $messages.append(html); this.scrollToBottom();
            $('.retry-analysis-btn').off('click').on('click', () => {
                $('.analysis-error').fadeOut(300, function() { $(this).remove(); });
                const lastQuery = $('.user-message').last().find('.message-content p').text().trim();
                this.startAgenticWorkflow(lastQuery, $messages);
            });
        },
        
        
        
        
        
        
        formatStepResult: function(text) {
            if (!text) return '';
            text = String(text);
            text = this.escapeHtml(text);
            text = text.replace(/\\n/g, '<br>').replace(/\n/g, '<br>');
            text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
            text = text.replace(/^• (.+)$/gm, '<div style="margin-left:12px;margin-top:4px;">• $1</div>');
            return text;
        },
        
        
        scrollToBottom: function() {
            const $m = $('#cursorChatMessages-standalone');
            if ($m.length) $m.animate({scrollTop: $m[0].scrollHeight}, 300);
        },
        
        escapeHtml: function(text) {
            if (!text) return '';
            const map = {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'};
            return String(text).replace(/[&<>"']/g, m => map[m]);
        },
        
        /**
         * Show typing indicator
         */
        showTypingIndicator: function($messages, message = 'Đang xử lý...') {
            const html = `
                <div class="bot-message typing-indicator">
                    <div class="bot-avatar typing">🤖</div>
                    <div class="message-content">
                        <div class="typing-animation">
                            <div class="typing-dots">
                                <span class="typing-dot"></span>
                                <span class="typing-dot"></span>
                                <span class="typing-dot"></span>
                            </div>
                            <span class="typing-text">${message}</span>
                        </div>
                    </div>
                </div>
            `;
            $messages.append(html);
            this.scrollToBottom();
            return $messages.find('.typing-indicator').last();
        },
        
        /**
         * Hide typing indicator
         */
        hideTypingIndicator: function($typingIndicator) {
            if ($typingIndicator && $typingIndicator.length) {
                $typingIndicator.fadeOut(300, function() {
                    $(this).remove();
                });
            }
        },
        
        /**
         * Start ripple effect when robot is minimized and idle
         */
        startRippleEffect: function() {
            if (!this.state.minimized || !this.$robot.length) {
                return;
            }
            
            // Stop any existing ripple effect first
            this.stopRippleEffect();
            
            // Create ripple container
            const $rippleContainer = $('<div class="robot-ripple-container"></div>');
            this.$robot.append($rippleContainer);
            
            // Create center pulse glow
            const $pulseGlow = $('<div class="robot-ripple-pulse"></div>');
            $rippleContainer.append($pulseGlow);
            
            // Create multiple ripple waves (always present, animated via CSS)
            const self = this;
            
            // Create 3 permanent ripple waves that will animate continuously
            for (let i = 0; i < 3; i++) {
                const $ripple = $('<div class="robot-ripple-wave"></div>');
                $rippleContainer.append($ripple);
            }
            
            // Continuously check if still minimized
            this.state.rippleIntervalId = setInterval(function() {
                if (!self.state.minimized || !self.$robot.length) {
                    self.stopRippleEffect();
                }
            }, 1000);
        },
        
        /**
         * Stop ripple effect
         */
        stopRippleEffect: function() {
            if (this.state.rippleIntervalId) {
                clearInterval(this.state.rippleIntervalId);
                this.state.rippleIntervalId = null;
            }
            if (this.$robot.length) {
                this.$robot.find('.robot-ripple-container').remove();
            }
        }
    };
    
    $(document).ready(function() { FloatingRobot.init(); });
    window.FloatingRobot = FloatingRobot;
    
})(jQuery);