<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ExaAi Mission Control</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { background-color: #0f172a; color: #e2e8f0; font-family: 'Courier New', Courier, monospace; }
        .neon-text { text-shadow: 0 0 5px #3b82f6, 0 0 10px #3b82f6; }
        .neon-border { box-shadow: 0 0 5px #3b82f6; border-color: #3b82f6; }
        .agent-card { transition: all 0.3s ease; }
        .agent-card:hover { transform: translateY(-2px); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); }
        .vuln-critical { border-left: 4px solid #ef4444; background: rgba(239, 68, 68, 0.1); }
        .vuln-high { border-left: 4px solid #f97316; background: rgba(249, 115, 22, 0.1); }
        .vuln-medium { border-left: 4px solid #eab308; background: rgba(234, 179, 8, 0.1); }
        ::-webkit-scrollbar { width: 8px; }
        ::-webkit-scrollbar-track { background: #1e293b; }
        ::-webkit-scrollbar-thumb { background: #475569; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: #64748b; }
    </style>
</head>
<body class="h-screen flex flex-col overflow-hidden">
    <!-- Header -->
    <header class="bg-slate-900 border-b border-slate-700 p-4 flex justify-between items-center shadow-lg z-10">
        <div class="flex items-center gap-3">
            <div class="w-3 h-3 rounded-full bg-green-500 animate-pulse"></div>
            <h1 class="text-2xl font-bold tracking-wider text-blue-400 neon-text">EXAAI <span class="text-white">MISSION CONTROL</span></h1>
        </div>
        <div class="flex gap-6 text-sm">
            <div class="flex flex-col items-end">
                <span class="text-slate-400">STATUS</span>
                <span class="text-green-400 font-bold">ONLINE</span>
            </div>
            <div class="flex flex-col items-end">
                <span class="text-slate-400">AGENTS</span>
                <span id="total-agents" class="text-blue-400 font-bold">0</span>
            </div>
            <div class="flex flex-col items-end">
                <span class="text-slate-400">VULNERABILITIES</span>
                <span id="total-vulns" class="text-red-500 font-bold neon-text">0</span>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="flex-1 flex overflow-hidden">
        <!-- Sidebar: Agent Tree -->
        <aside class="w-1/4 bg-slate-900 border-r border-slate-700 flex flex-col">
            <div class="p-3 border-b border-slate-700 bg-slate-800">
                <h2 class="font-bold text-slate-300 flex items-center gap-2">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
                    Active Operations
                </h2>
            </div>
            <div id="agent-list" class="flex-1 overflow-y-auto p-3 space-y-2">
                <!-- Agents injected here -->
            </div>
        </aside>

        <!-- Center: Live Feed & Stats -->
        <section class="flex-1 flex flex-col bg-slate-900/50 relative">
            <!-- Matrix Rain Background Effect (Optional/Subtle) -->
            <div class="absolute inset-0 pointer-events-none opacity-5 bg-[url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPgo8cmVjdCB3aWR0aD0iNCIgaGVpZ2h0PSI0IiBmaWxsPSIjMWUyOTNiIi8+CjxyZWN0IHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9IiMzMzQxNTUiLz4KPC9zdmc+')]"></div>

            <div class="h-1/2 border-b border-slate-700 flex">
                <!-- Live Terminal Log -->
                <div class="w-2/3 border-r border-slate-700 flex flex-col">
                    <div class="p-2 bg-slate-800 border-b border-slate-700 flex justify-between">
                        <span class="text-xs font-mono text-slate-400">>_ SYSTEM LOGS</span>
                        <span class="text-xs text-green-500">● LIVE</span>
                    </div>
                    <div id="console-logs" class="flex-1 overflow-y-auto p-4 font-mono text-xs text-slate-300 space-y-1 bg-black/40">
                        <!-- Logs injected here -->
                    </div>
                </div>
                
                <!-- Quick Stats Chart -->
                <div class="w-1/3 p-4 bg-slate-800/30 flex flex-col items-center justify-center">
                    <canvas id="statusChart"></canvas>
                </div>
            </div>

            <!-- Vulnerabilities Panel -->
            <div class="h-1/2 flex flex-col bg-slate-900">
                <div class="p-3 border-b border-slate-700 bg-slate-800 flex justify-between items-center">
                    <h2 class="font-bold text-red-400 flex items-center gap-2">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
                        Detected Vulnerabilities
                    </h2>
                    <span class="text-xs text-slate-500">Auto-refreshing...</span>
                </div>
                <div id="vuln-list" class="flex-1 overflow-y-auto p-4 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <!-- Vulns injected here -->
                </div>
            </div>
        </section>
    </main>

    <script>
        const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const socket = new WebSocket(`${wsProtocol}//${window.location.host}/ws`);
        
        // Chart setup
        const ctx = document.getElementById('statusChart').getContext('2d');
        const statusChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['Active', 'Completed', 'Failed'],
                datasets: [{
                    data: [0, 0, 0],
                    backgroundColor: ['#3b82f6', '#22c55e', '#ef4444'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { position: 'bottom', labels: { color: '#94a3b8' } }
                },
                cutout: '70%'
            }
        });

        socket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            updateDashboard(data);
        };

        function updateDashboard(data) {
            // Update Headers
            document.getElementById('total-agents').textContent = Object.keys(data.agents).length;
            
            // Update Agent List
            const agentList = document.getElementById('agent-list');
            agentList.innerHTML = '';
            
            Object.values(data.agents).forEach(agent => {
                const div = document.createElement('div');
                div.className = `agent-card p-3 rounded bg-slate-800 border border-slate-700 ${agent.status === 'running' ? 'border-l-4 border-l-blue-500' : ''}`;
                div.innerHTML = `
                    <div class="flex justify-between items-start mb-1">
                        <span class="font-bold text-xs text-slate-200 truncate" title="${agent.name}">${agent.name}</span>
                        <span class="text-[10px] px-1.5 py-0.5 rounded ${getStatusColor(agent.status)}">${agent.status}</span>
                    </div>
                    <div class="text-[10px] text-slate-500 truncate">${agent.id.substring(0, 8)}...</div>
                    <div class="text-[11px] text-slate-400 mt-1 line-clamp-2">${agent.task || 'No task description'}</div>
                `;
                agentList.appendChild(div);
            });

            // Update Logs
            const logContainer = document.getElementById('console-logs');
            logContainer.innerHTML = '';
            data.recent_logs.forEach(log => {
                const div = document.createElement('div');
                const time = new Date(log.timestamp * 1000).toLocaleTimeString();
                const color = log.role === 'assistant' ? 'text-blue-400' : 'text-slate-400';
                div.innerHTML = `<span class="text-slate-600">[${time}]</span> <span class="${color}">${log.role.toUpperCase()}:</span> <span class="text-slate-300">${escapeHtml(log.content.substring(0, 150))}...</span>`;
                logContainer.appendChild(div);
            });

            // Update Chart
            statusChart.data.datasets[0].data = [
                data.stats.active,
                data.stats.completed,
                data.stats.failed
            ];
            statusChart.update();

            // Update Vulns (Fetching separately or from WS if included)
            fetchVulns();
        }

        async function fetchVulns() {
            try {
                const response = await fetch('/api/vulnerabilities');
                const vulns = await response.json();
                document.getElementById('total-vulns').textContent = vulns.length;
                
                const container = document.getElementById('vuln-list');
                container.innerHTML = '';
                
                if (vulns.length === 0) {
                    container.innerHTML = '<div class="col-span-full text-center text-slate-500 py-10">No vulnerabilities detected... yet.</div>';
                    return;
                }

                vulns.forEach(v => {
                    const div = document.createElement('div');
                    const severityClass = `vuln-${v.severity.toLowerCase()}`;
                    div.className = `p-4 rounded bg-slate-800 border border-slate-700 ${severityClass}`;
                    div.innerHTML = `
                        <div class="flex justify-between items-center mb-2">
                            <h3 class="font-bold text-sm text-white">${v.title}</h3>
                            <span class="text-[10px] font-bold uppercase tracking-wider px-2 py-1 bg-black/30 rounded text-white">${v.severity}</span>
                        </div>
                        <p class="text-xs text-slate-400 line-clamp-3 mb-2">${v.content}</p>
                        <div class="text-[10px] text-slate-500">ID: ${v.report_id}</div>
                    `;
                    container.appendChild(div);
                });
            } catch (e) {
                console.error("Failed to fetch vulns", e);
            }
        }

        function getStatusColor(status) {
            switch(status) {
                case 'running': return 'bg-blue-900 text-blue-300';
                case 'completed': return 'bg-green-900 text-green-300';
                case 'failed': return 'bg-red-900 text-red-300';
                default: return 'bg-slate-700 text-slate-300';
            }
        }

        function escapeHtml(text) {
            if (!text) return "";
            return text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // Initial load
        fetchVulns();
    </script>
</body>
</html>
