{% extends 'base.html' %}
{% block content %}
<div class="container-fluid mt-4">
    <div class="row mb-3">
        <div class="col-md-8">
            <h1 class="mb-0">{{ project.title }}</h1>
            <p class="text-muted mb-0">{{ project.industry }} | <strong>Goal:</strong> {{ project.goal }}</p>
        </div>
        <div class="col-md-4 text-end">
            <a href="{% url 'project_list' %}" class="btn btn-outline-secondary">Back to Projects</a>
        </div>
    </div>

    <div class="row">
        <!-- Mind Map Visualization Column -->
        <div class="col-md-8">
            <div class="card shadow-sm h-100">
                                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Interactive Mind Map</h5>
                    <div>
                        <form method="POST" action="{% url 'regenerate_mindmap' project.pk %}" class="d-inline" onsubmit="return confirm('Are you sure you want to regenerate the entire map? This will delete all current nodes.');">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-sm btn-outline-danger me-2">Regenerate</button>
                        </form>
                        <button class="btn btn-sm btn-outline-primary" onclick="fitNetwork()">Reset View</button>
                    </div>
                </div>
                                <div class="card-body p-0" style="height: 600px; position: relative;">
                    {% if not nodes %}
                        <div class="position-absolute w-100 h-100 d-flex flex-column justify-content-center align-items-center" style="z-index: 10; background: rgba(255,255,255,0.9);">
                            <h4 class="text-muted mb-3">The mind map is empty</h4>
                            <p class="text-muted mb-4">Something went wrong during generation, or the map was cleared.</p>
                            <form method="POST" action="{% url 'regenerate_mindmap' project.pk %}">
                                {% csrf_token %}
                                <button type="submit" class="btn btn-primary px-4 py-2">
                                    Generate Map Now
                                </button>
                            </form>
                        </div>
                    {% endif %}
                    <!-- The vis-network container -->
                    <div id="mynetwork" style="width: 100%; height: 100%;"></div>
                </div>
                </div>
            </div>
        </div>

        <!-- Sidebar for Node Details & AI Chat -->
        <div class="col-md-4 d-flex flex-column">
            <!-- Node Details Panel -->
            <div class="card shadow-sm mb-3" style="flex: 1;">
                <div class="card-header bg-white">
                    <h5 class="mb-0">Node Details</h5>
                </div>
                <div class="card-body" id="node-details">
                    <p class="text-muted">Click on a node or edge in the map to see its details here.</p>
                </div>
            </div>

            <!-- AI Chat Panel -->
            <div class="card shadow-sm" style="flex: 1;">
                <div class="card-header bg-white">
                    <h5 class="mb-0">Ask AI Assistant</h5>
                </div>
                <div class="card-body d-flex flex-column">
                    <div id="ai-response" class="bg-light p-3 rounded mb-3 flex-grow-1" style="min-height: 100px; max-height: 200px; overflow-y: auto;">
                        <span class="text-muted">Hello! I'm your AI business strategist. Ask me to expand on a node, brainstorm new ideas, or analyze the map. If you ask me to add nodes to the map, I will!</span>
                    </div>
                    <div class="mt-auto">
                        <textarea id="ai-input" class="form-control mb-2" rows="2" placeholder="e.g. Add 3 more nodes related to Marketing..."></textarea>
                        <button id="ai-submit" class="btn btn-primary w-100">Send to AI</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Load Vis Network library -->
<script type="text/javascript" src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>

<!-- Add custom styles for vis-network tooltip -->
<style type="text/css">
    .vis-tooltip {
        position: absolute;
        background-color: white;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        font-family: Arial, sans-serif;
        font-size: 14px;
        max-width: 300px;
        pointer-events: none;
        z-index: 10;
    }
</style>

<script>
    // Colors for different categories
    const categoryColors = {
        'Strategy': '#e1bee7',   // Purple
        'Product': '#bbdefb',    // Blue
        'Market': '#c8e6c9',     // Green
        'Operations': '#ffcc80', // Orange
        'Finance': '#ffcdd2',    // Red
        'General': '#f5f5f5'     // Grey
    };

    function getNodeColor(category) {
        let cat = category || 'General';
        let color = '#e0e0e0'; // Default light grey
        for (let key in categoryColors) {
            if (cat.toLowerCase().includes(key.toLowerCase())) {
                color = categoryColors[key];
                break;
            }
        }
        return {
            background: color,
            border: '#9e9e9e',
            highlight: { background: '#ffffff', border: '#42a5f5' }
        };
    }

    // Prepare data from Django context
    const nodesArray = [
        {% for node in nodes %}
        {
            id: {{ node.pk }},
            label: "{{ node.title|escapejs }}",
            title: "<strong>{{ node.title|escapejs }}</strong><br>{{ node.summary|escapejs }}<br><em>Category: {{ node.category|escapejs }}</em>",
            summary: "{{ node.summary|escapejs }}",
            category: "{{ node.category|escapejs }}",
            color: getNodeColor("{{ node.category|escapejs }}"),
            shape: 'box',
            font: { size: 16, face: 'Arial', color: '#333' },
            margin: 10
        },
        {% endfor %}
    ];

    const edgesArray = [
        {% for conn in connections %}
        {
            from: {{ conn.source.pk }},
            to: {{ conn.target.pk }},
            label: "{{ conn.how|escapejs }}",
            title: "<strong>Why:</strong> {{ conn.why|escapejs }}",
            arrows: "to",
            why: "{{ conn.why|escapejs }}",
            how: "{{ conn.how|escapejs }}"
        },
        {% endfor %}
    ];

    const container = document.getElementById("mynetwork");
    const data = {
        nodes: new vis.DataSet(nodesArray),
        edges: new vis.DataSet(edgesArray)
    };
    
    const options = {
        layout: {
            improvedLayout: true
        },
        physics: {
            solver: 'forceAtlas2Based',
            forceAtlas2Based: {
                gravitationalConstant: -100,
                centralGravity: 0.01,
                springLength: 150,
                springConstant: 0.08
            },
            maxVelocity: 50,
            minVelocity: 0.1,
            timestep: 0.5,
            stabilization: { iterations: 150 }
        },
        interaction: {
            tooltipDelay: 200,
            hover: true
        },
        edges: {
            font: { size: 12, align: 'top' },
            color: { color: '#848484', highlight: '#42a5f5' },
            smooth: { type: 'continuous' }
        }
    };

    const network = new vis.Network(container, data, options);

    function fitNetwork() {
        network.fit({ animation: { duration: 1000, easingFunction: 'easeInOutQuad' } });
    }

    // Handle clicks to show details in the sidebar
    network.on("click", function (params) {
        const detailsPanel = document.getElementById('node-details');
        
        if (params.nodes.length > 0) {
            // Node clicked
            const nodeId = params.nodes[0];
            const node = data.nodes.get(nodeId);
            detailsPanel.innerHTML = `
                <h4 class="mb-2">${node.label}</h4>
                <span class="badge bg-secondary mb-3">${node.category}</span>
                <p><strong>Summary:</strong><br>${node.summary}</p>
            `;
        } else if (params.edges.length > 0) {
            // Edge clicked
            const edgeId = params.edges[0];
            const edge = data.edges.get(edgeId);
            const fromNode = data.nodes.get(edge.from);
            const toNode = data.nodes.get(edge.to);
            detailsPanel.innerHTML = `
                <h5 class="mb-3">Connection Details</h5>
                <p><strong>From:</strong> ${fromNode.label}</p>
                <p><strong>To:</strong> ${toNode.label}</p>
                <hr>
                <p><strong>How:</strong><br>${edge.how || 'N/A'}</p>
                <p><strong>Why:</strong><br>${edge.why || 'N/A'}</p>
            `;
        } else {
            // Clicked empty space
            detailsPanel.innerHTML = '<p class="text-muted">Click on a node or edge in the map to see its details here.</p>';
        }
    });

    // AI Chat Handler
    document.getElementById('ai-submit').addEventListener('click', function() {
        const inputField = document.getElementById('ai-input');
        const message = inputField.value.trim();
        if (!message) return;
        
        const responseDiv = document.getElementById('ai-response');
        
        // Append user message
        responseDiv.innerHTML += `<div class="mb-2 text-end"><strong>You:</strong> ${message}</div>`;
        inputField.value = '';
        
        // Show loading state
        const loadingId = 'loading-' + Date.now();
        responseDiv.innerHTML += `<div id="${loadingId}" class="mb-2 text-primary"><em>AI is thinking...</em></div>`;
        responseDiv.scrollTop = responseDiv.scrollHeight;

        fetch("{% url 'ai_chat' project.pk %}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify({ message: message })
        })
        .then(response => response.json())
        .then(apiData => {
            document.getElementById(loadingId).remove();
            
            // Handle chat response
            if (apiData.response) {
                responseDiv.innerHTML += `<div class="mb-2"><strong>AI:</strong> ${apiData.response}</div>`;
            }
            
            // Check for new nodes and add them to the map
            let mapUpdated = false;
            
            if (apiData.added_nodes && apiData.added_nodes.length > 0) {
                apiData.added_nodes.forEach(node => {
                    data.nodes.add({
                        id: node.id,
                        label: node.title,
                        title: "<strong>" + node.title + "</strong><br>" + node.summary + "<br><em>Category: " + node.category + "</em>",
                        summary: node.summary,
                        category: node.category,
                        color: getNodeColor(node.category),
                        shape: 'box',
                        font: { size: 16, face: 'Arial', color: '#333' },
                        margin: 10
                    });
                });
                mapUpdated = true;
            }
            
            if (apiData.added_connections && apiData.added_connections.length > 0) {
                apiData.added_connections.forEach(conn => {
                    data.edges.add({
                        id: conn.id,
                        from: conn.source_id,
                        to: conn.target_id,
                        label: conn.how,
                        title: "<strong>Why:</strong> " + conn.why,
                        arrows: "to",
                        why: conn.why,
                        how: conn.how
                    });
                });
                mapUpdated = true;
            }
            
            if (mapUpdated) {
                // Stabilize and adjust view
                network.stabilize();
                setTimeout(fitNetwork, 500); // Fit network smoothly after a slight delay
                responseDiv.innerHTML += `<div class="mb-2 text-success small"><em><i class="bi bi-check-circle"></i> Successfully added new items to the map!</em></div>`;
            }

            responseDiv.scrollTop = responseDiv.scrollHeight;
        })
        .catch(err => {
            document.getElementById(loadingId).remove();
            responseDiv.innerHTML += `<div class="mb-2 text-danger"><strong>Error:</strong> Failed to get response from AI.</div>`;
            console.error(err);
        });
    });
</script>
{% endblock %}