// ═══════════════════════════════════════════════════════
// CVC Dashboard — Hive Singularity UI (Sci-Fi Command Center)
// ZERO-LAG SVG ARCHITECTURE
// ═══════════════════════════════════════════════════════

const HIVE_NODE_ID = "hive-mind-core";

const connectedAgents = new Map();
let totalPackets = 0;

let svg, wireLayer, pulseLayer, robotLayer, brainLayer;
let centerX = 500, brainY = 120;
let isInitialized = false;

function initSwarmGraph() {
    if (isInitialized) return;
    svg = document.getElementById('swarm-svg');
    if (!svg) return;

    // Create Layers (back to front)
    wireLayer = document.createElementNS("http://www.w3.org/2000/svg", "g");
    pulseLayer = document.createElementNS("http://www.w3.org/2000/svg", "g");
    robotLayer = document.createElementNS("http://www.w3.org/2000/svg", "g");
    brainLayer = document.createElementNS("http://www.w3.org/2000/svg", "g");

    svg.appendChild(wireLayer);
    svg.appendChild(pulseLayer);
    svg.appendChild(robotLayer);
    svg.appendChild(brainLayer);

    updateDimensions();
    window.addEventListener('resize', () => {
        updateDimensions();
        recalculateLayout();
    });

    drawSuperbrain();
    recalculateLayout();
    isInitialized = true;
}

function updateDimensions() {
    const rect = svg.parentElement.getBoundingClientRect();
    if (rect.width > 0) {
        centerX = rect.width / 2;
    }
}

function drawSuperbrain() {
    brainLayer.innerHTML = '';
    const group = document.createElementNS("http://www.w3.org/2000/svg", "g");
    group.id = 'superbrain-node';
    group.style.transform = `translate(${centerX}px, ${brainY}px)`;

    group.innerHTML = `
        <circle class="brain-pulse" cx="0" cy="0" r="65"></circle>
        <circle class="brain-core" cx="0" cy="0" r="50"></circle>
        <circle class="brain-inner" cx="0" cy="0" r="35"></circle>
        <circle class="brain-inner-rev" cx="0" cy="0" r="25"></circle>
        <path d="M-20,0 Q0,-25 20,0 T-20,0" fill="none" stroke="#00ffff" stroke-width="2" opacity="0.6"/>
        <path d="M-30,15 Q0,-20 30,15" fill="none" stroke="#00ffff" stroke-width="1.5" opacity="0.4"/>
        <text class="brain-label" x="0" y="90">SINGULARITY</text>
    `;
    brainLayer.appendChild(group);
}

function createRobotSVG(agentId) {
    const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
    g.setAttribute('class', 'robot-avatar');
    g.id = `robot-${agentId}`;

    const isCap = agentId.includes('CAP');
    const color = isCap ? '#00ffff' : '#ffaa00';
    const bodyWidth = isCap ? 32 : 40;
    const eyeY = isCap ? -16 : -14;

    g.innerHTML = `
        <!-- Head -->
        <rect x="-14" y="-24" width="28" height="20" rx="4" class="robot-head"></rect>
        <rect x="-8" y="${eyeY}" width="16" height="4" rx="2" class="robot-visor" style="fill: ${color}; box-shadow: 0 0 5px ${color};"></rect>
        <!-- Body -->
        <path d="M-${bodyWidth/2},0 L${bodyWidth/2},0 L${bodyWidth/2-4},20 L-${bodyWidth/2-4},20 Z" class="robot-body"></path>
        <circle cx="0" cy="10" r="4" fill="${color}" opacity="0.5"></circle>
        <!-- Arms -->
        <path d="M-${bodyWidth/2},5 Q-${bodyWidth/2+10},15 -${bodyWidth/2+5},25" fill="none" class="robot-limb" stroke="${color}"></path>
        <path d="M${bodyWidth/2},5 Q${bodyWidth/2+10},15 ${bodyWidth/2+5},25" fill="none" class="robot-limb" stroke="${color}"></path>
        <!-- Legs -->
        <line x1="-8" y1="20" x2="-12" y2="35" class="robot-limb" stroke="${color}"></line>
        <line x1="8" y1="20" x2="12" y2="35" class="robot-limb" stroke="${color}"></line>
        <!-- Label -->
        <rect x="-30" y="42" width="60" height="14" rx="2" fill="rgba(0,0,0,0.6)" stroke="${color}" stroke-width="0.5"></rect>
        <text class="robot-label" x="0" y="52">${agentId}</text>
    `;
    return g;
}

function ensureAgentExists(agentId) {
    if (connectedAgents.has(agentId)) return;

    const robot = createRobotSVG(agentId);
    robotLayer.appendChild(robot);

    const wire = document.createElementNS("http://www.w3.org/2000/svg", "path");
    wire.setAttribute('class', 'neural-wire');
    wire.id = `wire-${agentId}`;
    wireLayer.appendChild(wire);

    // Initial position off-screen
    robot.style.transform = `translate(${centerX}px, 1000px)`;

    connectedAgents.set(agentId, { robot, wire });

    const listEl = document.getElementById('swarm-agent-list');
    if (listEl) {
        const li = document.createElement('div');
        li.className = 'agent-item';
        li.innerHTML = `<span class="agent-icon" style="color:${agentId.includes('CAP')?'#00ffff':'#ffaa00'}">⬡</span> ${agentId}`;
        listEl.appendChild(li);
    }

    recalculateLayout();
}

function recalculateLayout() {
    const brainNode = document.getElementById('superbrain-node');
    if (brainNode) brainNode.style.transform = `translate(${centerX}px, ${brainY}px)`;

    const agents = Array.from(connectedAgents.entries());
    const total = agents.length;
    if (total === 0) return;

    // Distribute robots in cascading curved rows (amphitheater style)
    let unplaced = total;
    let index = 0;
    let row = 0;

    while (unplaced > 0) {
        const capacity = 12 + row * 6;
        const countInRow = Math.min(unplaced, capacity);
        const R = 220 + row * 120;
        
        // Arc from 150 deg to 30 deg
        const startAngle = 150 * Math.PI / 180;
        const endAngle = 30 * Math.PI / 180;
        const angleStep = countInRow > 1 ? (endAngle - startAngle) / (countInRow - 1) : 0;

        for (let i = 0; i < countInRow; i++) {
            const angle = countInRow === 1 ? Math.PI/2 : startAngle + i * angleStep;
            const x = centerX + R * Math.cos(angle);
            const y = brainY + R * Math.sin(angle);

            const [agentId, data] = agents[index];
            
            // Move robot
            data.robot.style.transform = `translate(${x}px, ${y}px)`;
            
            // Draw curved wire
            const startX = centerX;
            const startY = brainY + 55; // bottom of brain
            const endX = x;
            const endY = y - 24; // top of robot head
            
            const cp1X = startX;
            const cp1Y = startY + (endY - startY) * 0.4;
            const cp2X = endX;
            const cp2Y = startY + (endY - startY) * 0.8;

            const d = `M ${startX} ${startY} C ${cp1X} ${cp1Y}, ${cp2X} ${cp2Y}, ${endX} ${endY}`;
            data.wire.setAttribute('d', d);

            index++;
        }
        
        unplaced -= countInRow;
        row++;
    }
}

function updateUI(agentId, action, category) {
    totalPackets++;
    const ac = document.getElementById('swarm-agent-count'); if(ac) ac.innerText = connectedAgents.size;
    const lc = document.getElementById('swarm-link-count'); if(lc) lc.innerText = connectedAgents.size;
    const pc = document.getElementById('swarm-packet-count'); if(pc) pc.innerText = totalPackets;

    const logEl = document.getElementById('swarm-terminal-log');
    if (logEl) {
        const time = new Date().toLocaleTimeString('en-US', { hour12: false });
        const entry = document.createElement('div');
        entry.className = 'log-entry';
        entry.innerHTML = `
            <span class="log-time">[${time}]</span>
            <span class="log-agent">${agentId}</span> 
            <span class="log-action" style="color: ${action==='write'?'#ffaa00':'#00ffff'}">>> ${action.toUpperCase()}</span> 
            <span style="color:rgba(255,255,255,0.4)">(${category || 'data'})</span>
        `;
        logEl.prepend(entry);
        if (logEl.children.length > 50) logEl.removeChild(logEl.lastChild);
    }
}

function handleTelemetryEvent(payload) {
    if (!payload || !payload.agent_id) return;
    const agentId = payload.agent_id;
    const action = payload.action || 'read'; 
    const category = payload.category || 'general';

    ensureAgentExists(agentId);
    updateUI(agentId, action, category);

    const data = connectedAgents.get(agentId);
    if (!data || !data.wire) return;

    // Robot "Thinking" animation trigger
    data.robot.classList.add('thinking');
    setTimeout(() => data.robot.classList.remove('thinking'), 500);

    // Brain flash trigger
    const brain = document.querySelector('.brain-core');
    if (brain) {
        brain.classList.add('flash');
        setTimeout(() => brain.classList.remove('flash'), 200);
    }

    // Animate the Data Packet along the SVG Path
    const wire = data.wire;
    const length = wire.getTotalLength();
    if (length === 0) return;

    const packet = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    packet.setAttribute('r', action === 'write' ? '4' : '3');
    packet.setAttribute('class', action === 'write' ? 'pulse-write' : 'pulse-read');
    pulseLayer.appendChild(packet);

    const duration = 600; 
    let startTime = null;

    function animatePulse(time) {
        if (!startTime) startTime = time;
        let progress = (time - startTime) / duration;
        
        if (progress > 1) {
            packet.remove();
            return;
        }
        
        // Easing (ease-in-out)
        let ease = progress < 0.5 ? 2 * progress * progress : 1 - Math.pow(-2 * progress + 2, 2) / 2;
        
        // READ: Brain -> Agent (t = 0 to 1)
        // WRITE: Agent -> Brain (t = 1 to 0)
        let t = action === 'write' ? 1 - ease : ease;
        
        const point = wire.getPointAtLength(t * length);
        packet.setAttribute('cx', point.x);
        packet.setAttribute('cy', point.y);
        
        requestAnimationFrame(animatePulse);
    }
    
    requestAnimationFrame(animatePulse);
}

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.nav-link').forEach(link => {
        link.addEventListener('click', (e) => {
            const tabId = e.currentTarget.getAttribute('data-tab');
            if (tabId === 'swarm') {
                setTimeout(initSwarmGraph, 50);
            }
        });
    });
});

window.handleSwarmTelemetry = handleTelemetryEvent;
