// ═══════════════════════════════════════════════════════
// CVC Dashboard — Hive Singularity UI (God-Level Cortex)
// 4-TIER NEURAL HIERARCHY WITH PAN/ZOOM
// ═══════════════════════════════════════════════════════

const HIVE_NODE_ID = "hive-mind-core";

const connectedAgents = new Map();
const squads = new Map(); // Prefix -> { captain: null, specialists: [] }
let totalPackets = 0;

let svg, zoomContainer, squadLayer, wireLayer, pulseLayer, robotLayer, brainLayer;
let centerX = 800, brainY = 100;
const VIEW_W = 1600;
const VIEW_H = 1000;
let isInitialized = false;

// Zoom & Pan State
let zoomScale = 1;
let panX = 0;
let panY = 0;
let isDragging = false;
let dragStartX = 0;
let dragStartY = 0;

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

    container.innerHTML = `<svg id="swarm-svg" width="100%" height="100%"></svg>`;
    svg = document.getElementById('swarm-svg');

    zoomContainer = document.createElementNS("http://www.w3.org/2000/svg", "g");
    zoomContainer.id = "zoom-container";
    svg.appendChild(zoomContainer);

    squadLayer = document.createElementNS("http://www.w3.org/2000/svg", "g");
    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");

    zoomContainer.appendChild(squadLayer);
    zoomContainer.appendChild(wireLayer);
    zoomContainer.appendChild(pulseLayer);
    zoomContainer.appendChild(robotLayer);
    zoomContainer.appendChild(brainLayer);

    setupInteractivity();

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

function setupInteractivity() {
    // Initial centering logic based on window size
    const rect = svg.getBoundingClientRect();
    if (rect.width > 0) {
        zoomScale = Math.min(rect.width / VIEW_W, rect.height / VIEW_H) * 0.9;
        panX = (rect.width - (VIEW_W * zoomScale)) / 2;
        panY = 20; 
        applyTransform();
    }

    svg.addEventListener('mousedown', (e) => {
        isDragging = true;
        dragStartX = e.clientX - panX;
        dragStartY = e.clientY - panY;
    });

    window.addEventListener('mousemove', (e) => {
        if (!isDragging) return;
        panX = e.clientX - dragStartX;
        panY = e.clientY - dragStartY;
        applyTransform();
    });

    window.addEventListener('mouseup', () => { isDragging = false; });
    svg.addEventListener('mouseleave', () => { isDragging = false; });

    svg.addEventListener('wheel', (e) => {
        e.preventDefault();
        const zoomSensitivity = -0.0015;
        const delta = e.deltaY * zoomSensitivity;
        let newScale = zoomScale * (1 + delta);
        newScale = Math.max(0.2, Math.min(newScale, 4));

        const rect = svg.getBoundingClientRect();
        const mouseX = e.clientX - rect.left;
        const mouseY = e.clientY - rect.top;

        panX = mouseX - (mouseX - panX) * (newScale / zoomScale);
        panY = mouseY - (mouseY - panY) * (newScale / zoomScale);
        zoomScale = newScale;

        applyTransform();
    }, { passive: false });
}

function applyTransform() {
    zoomContainer.setAttribute('transform', `translate(${panX}, ${panY}) scale(${zoomScale})`);
}

function parseAgentInfo(agentId) {
    const idU = agentId.toUpperCase();
    if (idU === 'MC-01' || idU.includes('ZEUS') || idU === 'SYSTEM') {
        return { type: 'zeus', squad: 'COMMAND' };
    }
    
    // FIX: Parse squad name correctly (e.g. SP-AEG-01 -> AEG)
    const parts = agentId.split('-');
    let squad = 'DEFAULT';
    if (parts.length >= 2) {
        squad = parts[1]; // Correctly grabs the middle team name
    }
    
    if (idU.startsWith('CAP-')) {
        return { type: 'captain', squad };
    }
    return { type: 'specialist', squad };
}

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)`;

    // Literal brain hemispheres
    group.innerHTML = `
        <g class="brain-core" id="brain-core">
            <path d="M 0,-50 C -60,-60 -100,-20 -80,30 C -60,80 -20,60 0,60 Z" />
            <path d="M 0,-50 C 60,-60 100,-20 80,30 C 60,80 20,60 0,60 Z" />
            <path d="M -20,-40 Q -40,-20 -20,10 T -40,40" class="brain-sulcus" />
            <path d="M 20,-40 Q 40,-20 20,10 T 40,40" class="brain-sulcus" />
            <path d="M -50,-10 Q -80,10 -50,30" class="brain-sulcus" />
            <path d="M 50,-10 Q 80,10 50,30" class="brain-sulcus" />
            <path d="M -10,10 Q 0,-20 10,10" class="brain-sulcus" />
        </g>
        <text class="brain-label" x="0" y="90">SINGULARITY</text>
    `;
    brainLayer.appendChild(group);
}

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

    let color;
    
    if (type === 'zeus') {
        color = '#ffffff';
        g.innerHTML = `
            <rect x="-24" y="-36" width="48" height="30" rx="6" class="robot-head" stroke="${color}"></rect>
            <!-- Crown Visor -->
            <path d="M-18,-24 L-12,-16 L0,-24 L12,-16 L18,-24" fill="none" stroke="#ffd700" stroke-width="3" filter="drop-shadow(0 0 5px #ffd700)"></path>
            <!-- Heavy Body -->
            <path d="M-30,-2 L30,-2 L20,28 L-20,28 Z" class="robot-body" stroke="${color}"></path>
            <circle cx="0" cy="12" r="8" fill="#ffd700" opacity="0.8"></circle>
            <!-- Arms & Legs -->
            <path d="M-30,5 Q-45,15 -35,35" fill="none" class="robot-limb" stroke="${color}"></path>
            <path d="M30,5 Q45,15 35,35" fill="none" class="robot-limb" stroke="${color}"></path>
            <line x1="-12" y1="28" x2="-18" y2="48" class="robot-limb" stroke="${color}"></line>
            <line x1="12" y1="28" x2="18" y2="48" class="robot-limb" stroke="${color}"></line>
            <!-- Label -->
            <text class="robot-label" x="0" y="65">${agentId}</text>
            <text class="robot-sub" x="0" y="75">SYSTEM COMMAND</text>
        `;
    } else if (type === 'captain') {
        color = '#d06262';
        g.innerHTML = `
            <rect x="-16" y="-24" width="32" height="20" rx="3" class="robot-head" stroke="${color}"></rect>
            <!-- Sharp Visor -->
            <rect x="-10" y="-16" width="20" height="4" rx="2" fill="${color}" filter="drop-shadow(0 0 5px ${color})"></rect>
            <!-- Aggressive Body -->
            <path d="M-20,0 L20,0 L12,22 L-12,22 Z" class="robot-body" stroke="${color}"></path>
            <path d="M-20,5 Q-30,15 -22,30" fill="none" class="robot-limb" stroke="${color}"></path>
            <path d="M20,5 Q30,15 22,30" fill="none" class="robot-limb" stroke="${color}"></path>
            <line x1="-8" y1="22" x2="-12" y2="40" class="robot-limb" stroke="${color}"></line>
            <line x1="8" y1="22" x2="12" y2="40" class="robot-limb" stroke="${color}"></line>
            <!-- Label -->
            <text class="robot-label" x="0" y="55">${agentId}</text>
            <text class="robot-sub" x="0" y="65">CAPTAIN</text>
        `;
    } else {
        color = '#ffaa00';
        g.innerHTML = `
            <rect x="-12" y="-18" width="24" height="16" rx="4" class="robot-head" stroke="${color}"></rect>
            <!-- Dual Eye Visor -->
            <circle cx="-5" cy="-10" r="2" fill="${color}" filter="drop-shadow(0 0 3px ${color})"></circle>
            <circle cx="5" cy="-10" r="2" fill="${color}" filter="drop-shadow(0 0 3px ${color})"></circle>
            <!-- Compact Body -->
            <rect x="-14" y="-2" width="28" height="18" rx="2" class="robot-body" stroke="${color}"></rect>
            <path d="M-14,4 Q-22,12 -16,22" fill="none" class="robot-limb" stroke="${color}"></path>
            <path d="M14,4 Q22,12 16,22" fill="none" class="robot-limb" stroke="${color}"></path>
            <line x1="-6" y1="16" x2="-8" y2="30" class="robot-limb" stroke="${color}"></line>
            <line x1="6" y1="16" x2="8" y2="30" class="robot-limb" stroke="${color}"></line>
            <!-- Label -->
            <text class="robot-label" x="0" y="45">${agentId}</text>
        `;
    }
    return g;
}

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

    const info = parseAgentInfo(agentId);
    
    if (!squads.has(info.squad)) {
        squads.set(info.squad, { zeus: null, captain: null, specialists: [] });
    }
    const sq = squads.get(info.squad);
    if (info.type === 'zeus') sq.zeus = agentId;
    else if (info.type === 'captain') sq.captain = agentId;
    else sq.specialists.push(agentId);

    const robot = createRobotSVG(agentId, info.type, info.squad);
    robotLayer.appendChild(robot);

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

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

    const listEl = document.getElementById('swarm-agent-list');
    if (listEl) {
        let color = info.type === 'zeus' ? '#fff' : (info.type === 'captain' ? '#d06262' : '#ffaa00');
        const li = document.createElement('div');
        li.className = 'agent-item';
        li.innerHTML = `<span class="agent-icon" style="color:${color}">⬡</span> ${agentId}`;
        listEl.appendChild(li);
    }

    recalculateLayout();
}

function recalculateLayout() {
    squadLayer.innerHTML = '';
    
    const cmdKeys = Array.from(squads.keys()).filter(k => k === 'COMMAND');
    const stdKeys = Array.from(squads.keys()).filter(k => k !== 'COMMAND').sort();

    // Verticle Spacing
    const zeusY = brainY + 250; 
    const captY = brainY + 480; 

    // 1. Position Zeus
    if (cmdKeys.length > 0) {
        const sq = squads.get('COMMAND');
        if (sq.zeus) {
            positionAgent(sq.zeus, centerX, zeusY);
        }
    }

    // 2. Position Standard Squadrons
    const squadCount = stdKeys.length || 1;
    const colsPerSquad = 3;
    const spSpacingX = 85;
    const spSpacingY = 85;
    const boxWidth = (colsPerSquad - 1) * spSpacingX + 110; 
    const squadSpacing = 70;
    const totalW = squadCount * boxWidth + (squadCount - 1) * squadSpacing;
    let currentX = centerX - (totalW / 2) + (boxWidth / 2);

    stdKeys.forEach((key) => {
        const sq = squads.get(key);
        const sqX = currentX;
        const topY = captY;

        // Draw Squad Bounding Box
        const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
        rect.setAttribute('class', 'squad-box');
        rect.setAttribute('x', sqX - (boxWidth/2));
        rect.setAttribute('y', topY - 70);
        rect.setAttribute('width', boxWidth);
        
        let boxHeight = 150;

        // Position Captain
        if (sq.captain) {
            positionAgent(sq.captain, sqX, topY);
        }

        // Position Specialists in 3x3 Grid
        sq.specialists.forEach((spId, idx) => {
            const col = idx % colsPerSquad;
            const row = Math.floor(idx / colsPerSquad);
            
            const spX = sqX - (spSpacingX * (colsPerSquad-1) / 2) + (col * spSpacingX);
            const spY = topY + 140 + (row * spSpacingY);
            
            positionAgent(spId, spX, spY);
            boxHeight = Math.max(boxHeight, (spY - topY) + 110);
        });

        rect.setAttribute('height', boxHeight);
        
        // Add Squad Label
        const txt = document.createElementNS("http://www.w3.org/2000/svg", "text");
        txt.setAttribute('x', sqX);
        txt.setAttribute('y', topY - 40);
        txt.setAttribute('fill', 'rgba(0, 255, 204, 0.5)');
        txt.setAttribute('font-size', '14px');
        txt.setAttribute('text-anchor', 'middle');
        txt.setAttribute('font-weight', 'bold');
        txt.textContent = `SQUAD: ${key}`;

        squadLayer.appendChild(rect);
        squadLayer.appendChild(txt);

        currentX += boxWidth + squadSpacing;
    });
}

function positionAgent(agentId, x, y) {
    const data = connectedAgents.get(agentId);
    if (!data) return;

    // First time spawn animation
    if (!data.spawned) {
        data.robot.style.transform = `translate(${centerX}px, ${brainY + 50}px) scale(0)`;
        data.robot.style.opacity = '0';
        
        // Trigger reflow
        void data.robot.offsetWidth;
        
        data.robot.style.transition = 'transform 0.8s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.8s ease-out';
        data.robot.style.opacity = '1';
        data.robot.style.transform = `translate(${x}px, ${y}px) scale(1)`;
        
        data.spawned = true;
    } else {
        data.robot.style.transform = `translate(${x}px, ${y}px) scale(1)`;
    }

    const startX = centerX;
    const startY = brainY + 50; 
    const endX = x;
    let endY = y - 24;
    if (data.info.type === 'zeus') endY -= 15;
    
    // Smooth wire curving behind agents
    const cp1X = startX;
    const cp1Y = startY + (endY - startY) * 0.2;
    const cp2X = endX;
    const cp2Y = startY + (endY - startY) * 0.8;

    const d = `M ${startX} ${startY} C ${cp1X} ${cp1Y}, ${cp2X} ${cp2Y}, ${endX} ${endY}`;
    
    // Animate wire growth on spawn
    if (!data.wireSpawned) {
        data.wire.setAttribute('d', d);
        const length = data.wire.getTotalLength();
        if (length > 0) {
            data.wire.style.strokeDasharray = length;
            data.wire.style.strokeDashoffset = length;
            void data.wire.offsetWidth;
            data.wire.style.transition = 'stroke-dashoffset 0.8s ease-out';
            data.wire.style.strokeDashoffset = '0';
            
            // Clean up transition after animation so flow animation works
            setTimeout(() => {
                data.wire.style.transition = '';
                data.wire.style.strokeDasharray = '';
                data.wire.style.strokeDashoffset = '';
            }, 800);
        }
        data.wireSpawned = true;
    } else {
        data.wire.setAttribute('d', d);
    }
}

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 ${action}">>> ${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;

    // The Physical Robot Interaction (Glowing)
    const rb = data.robot;
    if (rb.timeoutId) clearTimeout(rb.timeoutId);
    rb.classList.remove('active-read', 'active-write');
    void rb.offsetWidth; 
    rb.classList.add(action === 'write' ? 'active-write' : 'active-read');
    rb.timeoutId = setTimeout(() => {
        rb.classList.remove('active-read', 'active-write');
    }, 500);

    // Superbrain Core Flash
    const brain = document.getElementById('brain-core');
    if (brain) {
        if (brain.timeoutId) clearTimeout(brain.timeoutId);
        brain.classList.remove('flash-read', 'flash-write');
        void brain.offsetWidth;
        brain.classList.add(action === 'write' ? 'flash-write' : 'flash-read');
        brain.timeoutId = setTimeout(() => {
            brain.classList.remove('flash-read', 'flash-write');
        }, 250);
    }

    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' ? '6' : '5');
    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;
        }
        
        let ease = progress < 0.5 ? 2 * progress * progress : 1 - Math.pow(-2 * progress + 2, 2) / 2;
        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) => {
            if (e.currentTarget.getAttribute('data-tab') === 'swarm') {
                setTimeout(initSwarmGraph, 50);
            }
        });
    });
});

window.handleSwarmTelemetry = handleTelemetryEvent;
