// Sample data for the graph visualization
const sampleData = {
    nodes: [
        { id: 1, name: "Deep Learning", type: "concept", description: "A subset of machine learning using neural networks with multiple layers." },
        { id: 2, name: "Attention Is All You Need", type: "paper", year: 2017, authors: ["Vaswani et al."], citations: 50000, description: "Introduces the Transformer architecture." },
        { id: 3, name: "Ashish Vaswani", type: "author", institution: "Google Brain", description: "Lead author of the Transformer paper." },
        { id: 4, name: "Google Brain", type: "institution", location: "Mountain View, CA", description: "Google's AI research organization." },
        { id: 5, name: "Transformers", type: "concept", description: "Neural network architecture based on self-attention mechanisms." },
        { id: 6, name: "BERT", type: "paper", year: 2018, authors: ["Devlin et al."], citations: 40000, description: "Bidirectional Encoder Representations from Transformers." },
        { id: 7, name: "Jacob Devlin", type: "author", institution: "Google AI", description: "Lead author of the BERT paper." },
        { id: 8, name: "Self-Attention", type: "concept", description: "Mechanism that learns relationships between different positions of a sequence." }
    ],
    links: [
        { source: 2, target: 1, type: "related_to" },
        { source: 2, target: 3, type: "authored_by" },
        { source: 3, target: 4, type: "affiliated_with" },
        { source: 2, target: 5, type: "introduces" },
        { source: 6, target: 5, type: "uses" },
        { source: 6, target: 7, type: "authored_by" },
        { source: 7, target: 4, type: "affiliated_with" },
        { source: 5, target: 8, type: "based_on" }
    ]
};

function initGraphVisualization() {
    const container = document.getElementById('graph-container');
    const width = container.clientWidth;
    const height = container.clientHeight;

    // Create SVG
    const svg = d3.select('#graph-container')
        .append('svg')
        .attr('width', width)
        .attr('height', height)
        .call(d3.zoom().on('zoom', (event) => {
            g.attr('transform', event.transform);
        }))
        .append('g');

    // Create a group for the graph
    const g = svg.append('g');

    // Simulation setup
    const simulation = d3.forceSimulation(sampleData.nodes)
        .force('link', d3.forceLink(sampleData.links).id(d => d.id).distance(100))
        .force('charge', d3.forceManyBody().strength(-300))
        .force('center', d3.forceCenter(width / 2, height / 2))
        .force('collision', d3.forceCollide().radius(40));

    // Create links
    const link = g.append('g')
        .selectAll('line')
        .data(sampleData.links)
        .enter()
        .append('line')
        .attr('class', 'link')
        .attr('stroke-width', 2);

    // Create nodes
    const node = g.append('g')
        .selectAll('.node')
        .data(sampleData.nodes)
        .enter()
        .append('g')
        .attr('class', 'node')
        .call(d3.drag()
            .on('start', dragstarted)
            .on('drag', dragged)
            .on('end', dragended));
    node.append('circle')
        .attr('r', d => {
            if (d.type === 'paper') return 18;
            if (d.type === 'author') return 14;
            if (d.type === 'institution') return 16;
            return 12;
        })
        .attr('class', d => `node-${d.type}`)
        .attr('stroke-width', 1.5);
    node.append('text')
        .attr('dy', d => {
            if (d.type === 'paper') return 26;
            if (d.type === 'author') return 22;
            if (d.type === 'institution') return 24;
            return 20;
        })
        .text(d => d.name)
        .attr('class', 'node-label')
        .attr('font-size', '0.75rem')
        .attr('font-weight', '500');
// Update simulation on tick
    simulation.on('tick', () => {
        link
            .attr('x1', d => d.source.x)
            .attr('y1', d => d.source.y)
            .attr('x2', d => d.target.x)
            .attr('y2', d => d.target.y);

        node
            .attr('transform', d => `translate(${d.x},${d.y})`);
    });

    // Node click handler
    node.on('click', (event, d) => {
        // Remove previous selection
        d3.selectAll('.node.selected').classed('selected', false);
        
        // Select current node
        d3.select(event.currentTarget).classed('selected', true);
        
        // Show node details
        showNodeDetails(d);
    });

    // Zoom controls
    document.getElementById('zoom-in').addEventListener('click', () => {
        svg.transition().call(d3.zoom().scaleBy, 1.2);
    });

    document.getElementById('zoom-out').addEventListener('click', () => {
        svg.transition().call(d3.zoom().scaleBy, 0.8);
    });

    document.getElementById('reset-view').addEventListener('click', () => {
        svg.transition()
            .duration(750)
            .call(d3.zoom().transform, d3.zoomIdentity);
    });

    // Close details panel
    document.getElementById('close-details').addEventListener('click', () => {
        document.getElementById('default-details').classList.remove('hidden');
        document.getElementById('node-details').classList.add('hidden');
        d3.selectAll('.node.selected').classed('selected', false);
    });

    // Drag functions
    function dragstarted(event, d) {
        if (!event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
    }

    function dragged(event, d) {
        d.fx = event.x;
        d.fy = event.y;
    }

    function dragended(event, d) {
        if (!event.active) simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
    }
}

function showNodeDetails(node) {
    const detailsPanel = document.getElementById('node-details');
    const defaultPanel = document.getElementById('default-details');
    
    // Hide default panel and show details
    defaultPanel.classList.add('hidden');
    detailsPanel.classList.remove('hidden');
    
    // Set node title
    document.getElementById('node-title').textContent = node.name;
    
    // Set node type badge
    const typeBadge = document.getElementById('node-type');
    typeBadge.textContent = node.type.charAt(0).toUpperCase() + node.type.slice(1);
    typeBadge.className = `inline-block px-3 py-1 rounded-full text-xs font-semibold mb-4 ${getTypeBadgeClass(node.type)}`;
    
    // Set description
    document.getElementById('node-description').textContent = node.description || 'No description available.';
    
    // Set connections
    const connectionsContainer = document.getElementById('node-connections');
    connectionsContainer.innerHTML = '';
    
    const connectedNodes = getConnectedNodes(node.id);
    if (connectedNodes.length === 0) {
        connectionsContainer.innerHTML = '<p class="text-gray-500 dark:text-gray-400">No connections found.</p>';
    } else {
        connectedNodes.forEach(connection => {
            const connectionEl = document.createElement('div');
            connectionEl.className = 'flex items-center p-2 rounded-lg bg-gray-50 dark:bg-gray-700';
            connectionEl.innerHTML = `
                <div class="w-3 h-3 rounded-full mr-3 ${getTypeBadgeClass(connection.node.type)}"></div>
                <span class="text-sm text-gray-700 dark:text-gray-200">${connection.node.name}</span>
                <span class="ml-auto text-xs text-gray-500 dark:text-gray-400">${connection.relationship}</span>
            `;
            connectionsContainer.appendChild(connectionEl);
        });
    }
    
    // Set metadata
    const metadataContainer = document.getElementById('node-metadata');
    metadataContainer.innerHTML = '';
    
    const metadata = getNodeMetadata(node);
    Object.entries(metadata).forEach(([key, value]) => {
        const keyEl = document.createElement('div');
        keyEl.className = 'text-gray-500 dark:text-gray-400 font-medium';
        keyEl.textContent = key.replace(/_/g, ' ');
        
        const valueEl = document.createElement('div');
        valueEl.className = 'text-gray-700 dark:text-gray-200';
        valueEl.textContent = value || 'N/A';
        
        metadataContainer.appendChild(keyEl);
        metadataContainer.appendChild(valueEl);
    });
    
    // Set external link if available
    const linkEl = document.getElementById('node-link');
    if (node.type === 'paper') {
        linkEl.href = `https://scholar.google.com/scholar?q=${encodeURIComponent(node.name)}`;
        linkEl.classList.remove('hidden');
    } else {
        linkEl.classList.add('hidden');
    }
}

function getConnectedNodes(nodeId) {
    const connections = [];
    
    sampleData.links.forEach(link => {
        if (link.source.id === nodeId || link.target.id === nodeId) {
            const otherNodeId = link.source.id === nodeId ? link.target.id : link.source.id;
            const otherNode = sampleData.nodes.find(n => n.id === otherNodeId);
            const relationship = link.source.id === nodeId ? 
                (link.type === 'authored_by' ? 'Author' : 
                 link.type === 'affiliated_with' ? 'Affiliation' : 
                 link.type.replace(/_/g, ' ')) : 
                (link.type === 'authored_by' ? 'Paper' : 
                 link.type === 'affiliated_with' ? 'Member' : 
                 link.type.replace(/_/g, ' '));
            
            connections.push({
                node: otherNode,
                relationship: relationship.charAt(0).toUpperCase() + relationship.slice(1)
            });
        }
    });
    
    return connections;
}

function getNodeMetadata(node) {
    const metadata = {};
    
    if (node.type === 'paper') {
        metadata['Year'] = node.year;
        metadata['Authors'] = node.authors?.join(', ');
        metadata['Citations'] = node.citations?.toLocaleString();
    } else if (node.type === 'author') {
        metadata['Institution'] = node.institution;
    } else if (node.type === 'institution') {
        metadata['Location'] = node.location;
    }
    
    return metadata;
}
function getTypeBadgeClass(type) {
    switch(type) {
        case 'paper': return 'bg-blue-500 bg-opacity-20 text-blue-200';
        case 'author': return 'bg-green-500 bg-opacity-20 text-green-200';
        case 'institution': return 'bg-yellow-500 bg-opacity-20 text-yellow-200';
        case 'concept': return 'bg-purple-500 bg-opacity-20 text-purple-200';
        default: return 'bg-gray-500 bg-opacity-20 text-gray-200';
    }
}

// Add starfield background
function createStarfield() {
    const container = document.getElementById('graph-container');
    const starCount = 300;
    
    for (let i = 0; i < starCount; i++) {
        const star = document.createElement('div');
        star.style.position = 'absolute';
        const size = Math.random() * 2;
        star.style.width = `${size}px`;
        star.style.height = `${size}px`;
        star.style.backgroundColor = 'white';
        star.style.borderRadius = '50%';
        star.style.left = `${Math.random() * 100}%`;
        star.style.top = `${Math.random() * 100}%`;
        star.style.opacity = Math.random() * 0.8 + 0.2;
        star.style.animation = `pulse ${2 + Math.random() * 3}s infinite alternate`;
        star.style.zIndex = '-1';
        container.appendChild(star);
    }

    // Add some animated lines for cyber effect
    for (let i = 0; i < 5; i++) {
        const line = document.createElement('div');
        line.style.position = 'absolute';
        line.style.width = `${Math.random() * 100}%`;
        line.style.height = '1px';
        line.style.backgroundColor = `rgba(0, 240, 255, ${Math.random() * 0.1 + 0.05})`;
        line.style.left = '0';
        line.style.top = `${Math.random() * 100}%`;
        line.style.transform = `rotate(${Math.random() * 360}deg)`;
        line.style.animation = `scanline ${10 + Math.random() * 20}s linear infinite`;
        container.appendChild(line);
    }
}

// Add scanline animation
const style = document.createElement('style');
style.textContent = `
@keyframes scanline {
    0% { transform: rotate(0deg) translateX(-100%); }
    100% { transform: rotate(0deg) translateX(100%); }
}
`;
document.head.appendChild(style);
// Call this in initGraphVisualization
createStarfield();
