{% extends "base.html" %}
{% load static %}

{% block content %}
<style>
    .node-group { cursor: pointer; }
    .node-circle { stroke: #fff; stroke-width: 2px; }
    .node-text { font-size: 10px; pointer-events: none; fill: #555; }
    #loader { display: none; }
    #graphContainer { background: #1a1a1a; border-radius: 8px; }
    .link { stroke: #444; stroke-opacity: 0.6; }
</style>

<div class="container mt-5">
    <h1 class="mb-4">System Dashboard</h1>
    
    <div class="row">
        <div class="col-md-12 mb-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="card-title">Network Discovery</h5>
                    <form id="searchForm" class="input-group">
                        <input type="text" id="searchInput" class="form-control" placeholder="Search for a name to map their network...">
                        <button class="btn btn-primary" id="searchBtn" type="submit">
                            <span id="btnText">Discover</span>
                            <div id="loader" class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <div class="card shadow-sm">
                <div class="card-body p-0">
                    <div id="graphContainer" style="width: 100%; height: 700px; overflow: hidden;"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
document.getElementById('searchForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const query = document.getElementById('searchInput').value;
    const graphContainer = d3.select("#graphContainer");
    const searchBtn = document.getElementById('searchBtn');
    const btnText = document.getElementById('btnText');
    const loader = document.getElementById('loader');

    searchBtn.disabled = true;
    btnText.textContent = "Processing...";
    loader.style.display = "inline-block";
    
    // Fetch from new graph endpoint
    fetch(`{% url 'core:get_graph_data' %}?q=${encodeURIComponent(query)}`, { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            graphContainer.html('');
            renderGraph(data);
        })
        .catch(err => {
            console.error(err);
            graphContainer.html(`<p class="p-3 text-danger">Error: ${err.message}</p>`);
        })
        .finally(() => {
            searchBtn.disabled = false;
            btnText.textContent = "Discover";
            loader.style.display = "none";
        });
});

function renderGraph(data) {
    const container = document.getElementById('graphContainer');
    const width = container.clientWidth;
    const height = container.clientHeight;
    
    const svg = d3.select("#graphContainer")
                  .append("svg")
                  .attr("width", width)
                  .attr("height", height);

    const simulation = d3.forceSimulation(data.nodes)
        .force("link", d3.forceLink(data.links).id(d => d.id).distance(150))
        .force("charge", d3.forceManyBody().strength(-400))
        .force("center", d3.forceCenter(width / 2, height / 2))
        .force("collide", d3.forceCollide().radius(30));

    const link = svg.append("g")
        .selectAll("line")
        .data(data.links)
        .join("line")
        .attr("class", "link")
        .attr("stroke-width", d => Math.sqrt(d.value || 1));

    const node = svg.append("g")
        .selectAll("g")
        .data(data.nodes)
        .join("g")
        .attr("class", "node-group")
        .call(d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended));

    // Colors for types
    const color = d3.scaleOrdinal()
        .domain(["PERSON", "EMAIL", "ENTITY", "ORG"])
        .range(["#e74c3c", "#3498db", "#2ecc71", "#f1c40f"]);

    node.append("circle")
        .attr("r", 15)
        .attr("fill", d => color(d.type));

    node.append("text")
        .attr("dy", 25)
        .attr("text-anchor", "middle")
        .attr("class", "node-text")
        .text(d => d.name);

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

    function dragstarted(event) {
        if (!event.active) simulation.alphaTarget(0.3).restart();
        event.subject.fx = event.subject.x;
        event.subject.fy = event.subject.y;
    }
    function dragged(event) {
        event.subject.fx = event.x;
        event.subject.fy = event.y;
    }
    function dragended(event) {
        if (!event.active) simulation.alphaTarget(0);
        event.subject.fx = null;
        event.subject.fy = null;
    }
}
</script>
{% endblock %}