<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multi-Agent Debate Platform</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: #2c3e50;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            color: #2c3e50;
            font-weight: 700;
        }

        .header p {
            font-size: 1.2rem;
            color: #7f8c8d;
        }

        .control-panel {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        .form-group input, .form-group textarea, .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus, .form-group textarea:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }

        .btn {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .status-indicator {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }

        .status-indicator.connected {
            background: #d4edda;
            color: #155724;
        }

        .status-indicator.disconnected {
            background: #f8d7da;
            color: #721c24;
        }

        .status-indicator.debating {
            background: #fff3cd;
            color: #856404;
        }

        .debate-container {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            margin-bottom: 20px;
        }

        .debate-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .debate-title {
            font-size: 1.5rem;
            font-weight: 700;
            color: #333;
        }

        .debate-status {
            font-size: 1rem;
            color: #666;
        }

        .messages-container {
            max-height: 500px;
            overflow-y: auto;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .message {
            margin-bottom: 15px;
            padding: 15px;
            border-radius: 10px;
            animation: slideIn 0.3s ease;
        }

        .message.alice {
            background: linear-gradient(135deg, #e8f4fd 0%, #d1ecf1 100%);
            border-left: 4px solid #3498db;
            margin-left: 20px;
        }

        .message.bob {
            background: linear-gradient(135deg, #f0f9ff 0%, #e1f5fe 100%);
            border-left: 4px solid #2ecc71;
            margin-right: 20px;
        }

        .message.system {
            background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
            color: white;
            text-align: center;
        }

        .message-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 8px;
        }

        .message-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
        }

        .message-avatar.alice {
            background: #3498db;
        }

        .message-avatar.bob {
            background: #2ecc71;
        }

        .message-avatar.system {
            background: #95a5a6;
        }

        .message-author {
            font-weight: 600;
            font-size: 14px;
        }

        .message-time {
            font-size: 12px;
            opacity: 0.7;
            margin-left: auto;
        }

        .message-content {
            line-height: 1.6;
            white-space: pre-wrap;
        }

        .loading {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
            margin-bottom: 15px;
        }

        .spinner {
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: #3498db;
        }

        .stat-label {
            color: #666;
            font-size: 0.9rem;
            margin-top: 5px;
        }

        .hidden {
            display: none;
        }

        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .message {
                margin-left: 0;
                margin-right: 0;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-comments"></i> Multi-Agent Debate Platform</h1>
            <p>Real-time AI-powered debate visualization</p>
        </div>

        <div class="control-panel">
            <div class="form-group">
                <label for="topic">Debate Topic:</label>
                <textarea id="topic" placeholder="Enter a debate topic...">Let's debate about the stock of AAPL. Is it a good investment?</textarea>
            </div>
            
            <div class="form-group">
                <label for="agents">Participants:</label>
                <select id="agents" multiple>
                    <option value="alice" selected>Alice (Finance Expert)</option>
                    <option value="bob" selected>Bob (Mathematics Expert)</option>
                </select>
            </div>
            
            <div style="display: flex; gap: 15px; align-items: center;">
                <button id="startBtn" class="btn">
                    <i class="fas fa-play"></i> Start Debate
                </button>
                <button id="clearBtn" class="btn" style="background: #6c757d;">
                    <i class="fas fa-trash"></i> Clear
                </button>
                <div id="statusIndicator" class="status-indicator disconnected">
                    <i class="fas fa-circle"></i> Disconnected
                </div>
            </div>
        </div>

        <div class="debate-container">
            <div class="debate-header">
                <div class="debate-title">Live Debate</div>
                <div class="debate-status" id="debateStatus">Ready to start</div>
            </div>
            
            <div class="messages-container" id="messagesContainer">
                <div class="message system">
                    <div class="message-header">
                        <div class="message-avatar system">
                            <i class="fas fa-robot"></i>
                        </div>
                        <div class="message-author">System</div>
                    </div>
                    <div class="message-content">Welcome to the Multi-Agent Debate Platform! Start a debate to see AI agents discuss topics in real-time.</div>
                </div>
            </div>
            
            <div id="loadingIndicator" class="loading hidden">
                <div class="spinner"></div>
                <span>Debate in progress...</span>
            </div>
        </div>

        <div class="stats">
            <div class="stat-card">
                <div class="stat-number" id="messageCount">0</div>
                <div class="stat-label">Messages</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="debateRounds">0</div>
                <div class="stat-label">Rounds</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="participantCount">0</div>
                <div class="stat-label">Participants</div>
            </div>
        </div>
    </div>

    <script>
        // Initialize Socket.IO connection
        const socket = io();
        
        // DOM elements
        const startBtn = document.getElementById('startBtn');
        const clearBtn = document.getElementById('clearBtn');
        const topicInput = document.getElementById('topic');
        const agentsSelect = document.getElementById('agents');
        const messagesContainer = document.getElementById('messagesContainer');
        const statusIndicator = document.getElementById('statusIndicator');
        const debateStatus = document.getElementById('debateStatus');
        const loadingIndicator = document.getElementById('loadingIndicator');
        
        // Stats elements
        const messageCount = document.getElementById('messageCount');
        const debateRounds = document.getElementById('debateRounds');
        const participantCount = document.getElementById('participantCount');
        
        // State
        let isDebating = false;
        let messageCounter = 0;
        let roundCounter = 0;
        
        // Socket event handlers
        socket.on('connect', function() {
            console.log('Connected to server');
            updateStatus('connected', 'Connected');
        });
        
        socket.on('disconnect', function() {
            console.log('Disconnected from server');
            updateStatus('disconnected', 'Disconnected');
        });
        
        socket.on('connected', function(data) {
            console.log('Server response:', data.message);
        });
        
        socket.on('debate_started', function(data) {
            console.log('Debate started:', data);
            isDebating = true;
            updateStatus('debating', 'Debate in progress...');
            showLoading(true);
            addSystemMessage(`Debate started on: "${data.topic}"`);
            addSystemMessage(`Participants: ${data.agents.join(', ')}`);
            roundCounter = 0;
            updateStats();
        });
        
        socket.on('debate_completed', function(data) {
            console.log('Debate completed:', data);
            isDebating = false;
            updateStatus('connected', 'Debate completed');
            showLoading(false);
            addSystemMessage('Debate completed!');
            updateStats();
        });
        
        socket.on('debate_error', function(data) {
            console.error('Debate error:', data);
            isDebating = false;
            updateStatus('disconnected', 'Error occurred');
            showLoading(false);
            addSystemMessage(`Error: ${data.error}`);
        });
        
        // Real-time agent events
        socket.on('agent_thinking', function(data) {
            console.log('Agent thinking:', data);
            addSystemMessage(`${data.agent} is thinking...`);
        });
        
        socket.on('agent_response', function(data) {
            console.log('Agent response:', data);
            addMessage(data.agent, data.content, 'agent');
        });
        
        socket.on('agent_decline', function(data) {
            console.log('Agent decline:', data);
            addSystemMessage(`${data.agent} decided not to respond`);
        });
        
        socket.on('agent_exit', function(data) {
            console.log('Agent exit:', data);
            addSystemMessage(`${data.agent} has left the debate`);
        });
        
        socket.on('agent_error', function(data) {
            console.error('Agent error:', data);
            addSystemMessage(`Error with ${data.agent}: ${data.content}`);
        });
        
        // Event listeners
        startBtn.addEventListener('click', function() {
            if (isDebating) return;
            
            const topic = topicInput.value.trim();
            if (!topic) {
                alert('Please enter a debate topic');
                return;
            }
            
            const agents = Array.from(agentsSelect.selectedOptions).map(option => option.value);
            if (agents.length === 0) {
                alert('Please select at least one participant');
                return;
            }
            
            startDebate(topic, agents);
        });
        
        clearBtn.addEventListener('click', function() {
            messagesContainer.innerHTML = '';
            messageCounter = 0;
            roundCounter = 0;
            updateStats();
            addSystemMessage('Chat cleared');
        });
        
        // Functions
        function startDebate(topic, agents) {
            fetch('/api/start_debate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    topic: topic,
                    agents: agents
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'started') {
                    console.log('Debate started successfully');
                } else {
                    console.error('Failed to start debate:', data.error);
                    alert('Failed to start debate: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error starting debate:', error);
                alert('Error starting debate: ' + error.message);
            });
        }
        
        function addMessage(author, content, type = 'agent') {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            
            const now = new Date();
            const timeStr = now.toLocaleTimeString();
            
            messageDiv.innerHTML = `
                <div class="message-header">
                    <div class="message-avatar ${author.toLowerCase()}">
                        ${author.charAt(0).toUpperCase()}
                    </div>
                    <div class="message-author">${author}</div>
                    <div class="message-time">${timeStr}</div>
                </div>
                <div class="message-content">${content}</div>
            `;
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            
            if (type === 'agent') {
                messageCounter++;
                roundCounter++;
                updateStats();
            }
        }
        
        function addSystemMessage(content) {
            addMessage('System', content, 'system');
        }
        
        function updateStatus(status, text) {
            statusIndicator.className = `status-indicator ${status}`;
            statusIndicator.innerHTML = `<i class="fas fa-circle"></i> ${text}`;
            debateStatus.textContent = text;
        }
        
        function showLoading(show) {
            loadingIndicator.classList.toggle('hidden', !show);
        }
        
        function updateStats() {
            messageCount.textContent = messageCounter;
            debateRounds.textContent = roundCounter;
            participantCount.textContent = agentsSelect.selectedOptions.length;
        }
        
        // Initialize
        updateStats();
    </script>
</body>
</html>
