$(document).ready(function() {
    
    function fetchPulse() {
        $.ajax({
            url: '/api/status',
            method: 'GET',
            success: function(data) {
                updateDashboard(data);
                $('#system-status').html('<span class="text-success">● System Online</span>');
            },
            error: function(err) {
                $('#system-status').html('<span class="text-danger">⚠️ Connection Lost</span>');
                $('.pulse-dot').css('background-color', 'red');
            }
        });
    }

    function updateDashboard(data) {
        // 1. Update Header Stats
        $('#total-agents').text(data.total);
        
        let healthColor = data.status === "stable" ? "text-healthy" : "text-down";
        $('#overall-health').html(`<span class="${healthColor}">${data.status.toUpperCase()}</span>`);

        let now = new Date();
        $('#last-update').text(now.toLocaleTimeString());
        
        // 2. Generate Grid HTML
        let gridHtml = '';
        data.eyes.forEach(agent => {
            let statusColor = agent.status === 'healthy' ? 'text-healthy' : 
                              agent.status === 'degraded' ? 'text-degraded' : 'text-down';
            
            let borderColor = `border-${agent.status}`; // references css class
            
            let icon = agent.status === 'healthy' ? '⚡' : '⚠️';
            if(agent.status === 'down') icon = '🛑';

            gridHtml += `
                <div class="col-md-4">
                    <div class="agent-card ${borderColor} p-4 h-100">
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <h5 class="fw-bold mb-0 text-white">${icon} ${agent.agent_id}</h5>
                            <span class="badge bg-dark border border-secondary">${agent.latency_ms} ms</span>
                        </div>
                        
                        <div class="text-center py-2">
                            <div class="vitality-number ${statusColor}">${agent.vitality_score}</div>
                            <small class="text-secondary text-uppercase tracking-wider">Vitality Score</small>
                        </div>

                        <div class="mt-3 pt-3 border-top border-secondary d-flex justify-content-between">
                            <small class="text-muted">STATUS</small>
                            <small class="fw-bold ${statusColor} text-uppercase">${agent.status}</small>
                        </div>
                    </div>
                </div>
            `;
        });

        // 3. Update DOM (Only if changed to prevent flicker, simplified here to direct replace)
        $('#agent-grid').html(gridHtml);
    }

    // Start Polling
    fetchPulse();
    setInterval(fetchPulse, 2000);
});