// people_profile_connections.js — Connections tab for People Profile (Phase 3)
// Shows: Top interaction partners, Vis.js graph centered on person

var PeopleProfileConnections = (function() {
    'use strict';

    let rendered = false;
    let currentSkoolId = null;
    let network = null;

    function render(skoolId, profileData) {
        if (rendered && currentSkoolId === skoolId) return;
        rendered = true;
        currentSkoolId = skoolId;

        const container = document.getElementById('profile-connections-container');
        if (!container) return;

        container.innerHTML = '<div style="color:var(--color-text-secondary);padding:var(--space-3);">Loading connections...</div>';

        loadAndRender(container, skoolId, profileData);
    }

    async function loadAndRender(container, skoolId, profileData) {
        // Load top interactions
        let interactions = [];
        try {
            const res = await get('/api/user/' + skoolId + '/top-interactions');
            if (res.ok && res.data && res.data.interactions) {
                interactions = res.data.interactions;
            }
        } catch (e) {
            console.warn('[Connections] Failed to load top interactions:', e);
        }

        let html = '';

        html += '<div class="pp-connections-layout">';

        // ========== Interaction Graph ==========
        html += '<div class="pp-section pp-connections-graph">';
        html += '<div class="pp-section__title">Interaction Graph</div>';
        html += '<div id="pp-graph-container" style="flex:1;min-height:0;border:1px solid var(--color-border);border-radius:var(--radius-md);position:relative;"></div>';
        html += '</div>';

        html += '</div>'; // close pp-connections-layout

        container.innerHTML = html;

        // Render graph async
        renderGraph(skoolId, interactions);
    }

    // ========== Graph ==========

    async function renderGraph(skoolId, interactions) {
        const graphDiv = document.getElementById('pp-graph-container');
        if (!graphDiv) return;

        // Build member list: this person + top interaction partners
        const partnerIds = interactions.slice(0, 15).map(function(ix) { return ix.skool_id; });
        const allIds = [skoolId].concat(partnerIds);

        try {
            const cc = await ConfigEntry.get("current_community");
            const res = await post('/api/graph/interactions', {
                skool_ids: allIds,
                community: cc
            });

            if (!res.ok || !res.data) {
                graphDiv.innerHTML = '<div style="padding:20px;color:var(--color-text-disabled);">Could not load graph data.</div>';
                return;
            }

            const { nodes, like_edges, comment_edges } = res.data;

            if (nodes.length === 0) {
                graphDiv.innerHTML = '<div style="padding:20px;color:var(--color-text-disabled);">No graph data available.</div>';
                return;
            }

            const visNodes = nodes.map(function(n) {
                const node = {
                    id: n.id,
                    label: n.name,
                    size: n.id === skoolId ? 35 : 22,
                    title: '@' + n.name,
                    borderWidth: n.id === skoolId ? 3 : 2
                };
                if (n.id) {
                    node.shape = 'circularImage';
                    node.image = '/api/image/' + n.id;
                } else {
                    node.shape = 'dot';
                }
                // Highlight central person
                if (n.id === skoolId) {
                    node.color = { border: 'var(--brand-primary)', background: '#fff' };
                }
                return node;
            });

            const visEdges = [
                ...like_edges.map(function(e) {
                    return {
                        from: e.source,
                        to: e.target,
                        value: e.weight || 1,
                        color: { color: '#e74c3c', highlight: '#c0392b' },
                        title: (e.weight || 1) + ' Like' + ((e.weight || 1) > 1 ? 's' : ''),
                        arrows: 'to'
                    };
                }),
                ...comment_edges.map(function(e) {
                    return {
                        from: e.source,
                        to: e.target,
                        value: e.weight || 1,
                        color: { color: '#3498db', highlight: '#2980b9' },
                        title: (e.weight || 1) + ' Comment' + ((e.weight || 1) > 1 ? 's' : ''),
                        arrows: 'to'
                    };
                })
            ];

            // Legend
            const legend = document.createElement('div');
            legend.style.cssText = 'position:absolute;top:5px;right:10px;background:var(--color-bg-primary);padding:4px 8px;border-radius:var(--radius-sm);z-index:10;font-size:10px;line-height:1.6;border:1px solid var(--color-border);pointer-events:none;';
            legend.innerHTML = '<span style="color:#e74c3c;">&mdash;</span> Likes &nbsp; <span style="color:#3498db;">&mdash;</span> Comments';
            graphDiv.appendChild(legend);

            if (typeof vis !== 'undefined' && vis.Network) {
                if (network) { network.destroy(); network = null; }

                network = new vis.Network(graphDiv, { nodes: visNodes, edges: visEdges }, {
                    nodes: { font: { size: 11 }, scaling: { min: 18, max: 40 } },
                    edges: { smooth: { type: 'continuous' }, scaling: { min: 1, max: 6 } },
                    physics: {
                        enabled: true,
                        stabilization: { iterations: 40, fit: true },
                        barnesHut: { gravitationalConstant: -2500, springLength: 200 }
                    }
                });

                network.once('stabilizationIterationsDone', function() {
                    network.setOptions({ physics: { enabled: false } });
                });

                // Click on node -> select that person
                network.on('click', function(params) {
                    if (params.nodes.length > 0) {
                        const clickedId = params.nodes[0];
                        if (clickedId !== skoolId) {
                            selectPerson(clickedId);
                        }
                    }
                });
            } else {
                graphDiv.innerHTML = '<div style="padding:20px;color:var(--color-text-disabled);">Vis.js not loaded. Graph unavailable.</div>';
            }
        } catch (e) {
            console.error('[Connections] Graph error:', e);
            graphDiv.innerHTML = '<div style="padding:20px;color:var(--color-error);">Error loading graph.</div>';
        }
    }

    function reset() {
        rendered = false;
        currentSkoolId = null;
        if (network) { network.destroy(); network = null; }
    }

    return {
        render: render,
        reset: reset
    };
})();
