// Side panel logic
class SurfAIExtension {
    constructor() {
        this.backendUrl = 'http://localhost:8000';
        this.history = [];
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.checkConnection();
        this.loadHistory();
        
        // Check connection every 5 seconds
        setInterval(() => this.checkConnection(), 5000);
    }
    
    bindEvents() {
        document.getElementById('executeBtn').addEventListener('click', () => this.executeCommand());
        document.getElementById('screenshotBtn').addEventListener('click', () => this.takeScreenshot());
        document.getElementById('clearBtn').addEventListener('click', () => this.clearHistory());
        document.getElementById('settingsBtn').addEventListener('click', () => this.openSettings());
        
        // Enter key to execute
        document.getElementById('commandInput').addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && e.ctrlKey) {
                this.executeCommand();
            }
        });
    }
    
    async checkConnection() {
        try {
            // Use background script to check connection
            const response = await chrome.runtime.sendMessage({ type: 'CHECK_CONNECTION' });
            
            if (response && response.connected) {
                this.setStatus(true);
            } else {
                this.setStatus(false);
            }
        } catch (error) {
            this.setStatus(false);
        }
    }
    
    setStatus(connected) {
        const dot = document.getElementById('statusDot');
        const text = document.getElementById('statusText');
        
        if (connected) {
            dot.classList.add('connected');
            text.textContent = '已连接';
        } else {
            dot.classList.remove('connected');
            text.textContent = '未连接';
        }
    }
    
    async executeCommand() {
        const input = document.getElementById('commandInput');
        const command = input.value.trim();
        
        if (!command) {
            this.showNotification('请输入指令', 'error');
            return;
        }
        
        // Add to history
        const historyItem = {
            id: Date.now(),
            command: command,
            status: 'running',
            result: '',
            time: new Date().toLocaleTimeString(),
        };
        
        this.addHistoryItem(historyItem);
        input.value = '';
        
        try {
            // Use background script to execute
            const response = await chrome.runtime.sendMessage({
                type: 'EXECUTE_COMMAND',
                command: command,
            });
            
            if (response && response.success) {
                const data = response.data;
                if (data.success) {
                    this.updateHistoryItem(historyItem.id, {
                        status: 'success',
                        result: `执行成功: ${data.actions_executed?.length || 0} 个动作`,
                    });
                } else {
                    this.updateHistoryItem(historyItem.id, {
                        status: 'error',
                        result: data.error || '执行失败',
                    });
                }
            } else {
                this.updateHistoryItem(historyItem.id, {
                    status: 'error',
                    result: response?.error || '无法连接到后端服务',
                });
            }
        } catch (error) {
            this.updateHistoryItem(historyItem.id, {
                status: 'error',
                result: '无法连接到后端服务',
            });
        }
    }
    
    async takeScreenshot() {
        const historyItem = {
            id: Date.now(),
            command: '截图',
            status: 'running',
            result: '',
            time: new Date().toLocaleTimeString(),
        };
        
        this.addHistoryItem(historyItem);
        
        try {
            // Use background script to take screenshot
            const response = await chrome.runtime.sendMessage({
                type: 'TAKE_SCREENSHOT',
            });
            
            if (response && response.success) {
                const data = response.data;
                if (data.success) {
                    this.updateHistoryItem(historyItem.id, {
                        status: 'success',
                        result: `截图保存: ${data.path} (${data.size_kb} KB)`,
                    });
                    
                    // Show screenshot preview
                    this.showScreenshotPreview(data.path);
                } else {
                    this.updateHistoryItem(historyItem.id, {
                        status: 'error',
                        result: data.error || '截图失败',
                    });
                }
            } else {
                this.updateHistoryItem(historyItem.id, {
                    status: 'error',
                    result: response?.error || '无法连接到后端服务',
                });
            }
        } catch (error) {
            this.updateHistoryItem(historyItem.id, {
                status: 'error',
                result: '无法连接到后端服务',
            });
        }
    }
    
    showScreenshotPreview(path) {
        // Create a temporary notification for screenshot
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: white;
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1000;
            max-width: 300px;
        `;
        notification.innerHTML = `
            <div style="font-size: 13px; color: #333; margin-bottom: 8px;">📸 截图已保存</div>
            <div style="font-size: 11px; color: #666; word-break: break-all;">${path}</div>
        `;
        
        document.body.appendChild(notification);
        
        // Auto remove after 5 seconds
        setTimeout(() => {
            notification.remove();
        }, 5000);
    }
    
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${type === 'error' ? '#f44336' : '#4caf50'};
            color: white;
            border-radius: 8px;
            padding: 12px 16px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1000;
            font-size: 13px;
        `;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
    
    addHistoryItem(item) {
        this.history.unshift(item);
        this.renderHistory();
        this.saveHistory();
    }
    
    updateHistoryItem(id, updates) {
        const item = this.history.find(h => h.id === id);
        if (item) {
            Object.assign(item, updates);
            this.renderHistory();
            this.saveHistory();
        }
    }
    
    renderHistory() {
        const list = document.getElementById('historyList');
        
        if (this.history.length === 0) {
            list.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">📝</div>
                    <div>暂无执行记录</div>
                </div>
            `;
            return;
        }
        
        list.innerHTML = this.history.map(item => `
            <div class="history-item ${item.status}">
                <div class="history-command">${this.escapeHtml(item.command)}</div>
                <div class="history-result">${this.escapeHtml(item.result)}</div>
                <div class="history-time">${item.time}</div>
            </div>
        `).join('');
    }
    
    clearHistory() {
        this.history = [];
        this.renderHistory();
        this.saveHistory();
    }
    
    saveHistory() {
        chrome.storage.local.set({ surfai_history: this.history });
    }
    
    async loadHistory() {
        const result = await chrome.storage.local.get('surfai_history');
        if (result.surfai_history) {
            this.history = result.surfai_history;
            this.renderHistory();
        }
    }
    
    openSettings() {
        // For now, just show a notification
        this.showNotification('设置功能开发中...', 'info');
    }
    
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// Initialize
new SurfAIExtension();
