// Network Tree Visualization using D3.js
window.NetworkTreeViewer = {
    instance: null,
    dotNetRef: null,
    
    setDotNetReference: function(dotNetReference) {
        this.dotNetRef = dotNetReference;
    },
    
    initialize: function(elementId, data) {
        const container = document.getElementById(elementId);
        if (!container) {
            console.error('Container not found:', elementId);
            return;
        }

        // Clear previous content
        container.innerHTML = '';

        // Set dimensions - responsive to container
        const containerRect = container.getBoundingClientRect();
        const width = containerRect.width || 1200;
        const height = Math.max(containerRect.height, 800);

        // Create SVG with viewBox for responsiveness
        const svg = d3.select(`#${elementId}`)
            .append('svg')
            .attr('width', '100%')
            .attr('height', '100%')
            .attr('viewBox', `0 0 ${width} ${height}`)
            .attr('preserveAspectRatio', 'xMidYMid meet')
            .style('background-color', '#fafafa')
            .call(d3.zoom()
                .scaleExtent([0.1, 3])
                .on('zoom', (event) => {
                    g.attr('transform', event.transform);
                }));

        const g = svg.append('g')
            .attr('transform', 'translate(40,0)');

        // Create tree layout
        const tree = d3.tree()
            .size([height - 100, width - 300])
            .separation((a, b) => a.parent === b.parent ? 1.5 : 2);

        // Convert flat data to hierarchy
        const root = this.buildHierarchy(data);
        
        if (!root) {
            container.innerHTML = '<div style="padding: 20px; text-align: center; color: #666;">درخت خالی است</div>';
            return;
        }

        // Generate tree layout
        const treeData = tree(root);

        // Add zoom reset button
        const resetButton = svg.append('g')
            .attr('transform', 'translate(20, 20)')
            .style('cursor', 'pointer')
            .on('click', () => {
                svg.transition()
                    .duration(750)
                    .call(d3.zoom().transform, d3.zoomIdentity);
            });

        resetButton.append('rect')
            .attr('width', 80)
            .attr('height', 30)
            .attr('rx', 5)
            .style('fill', '#2196F3')
            .style('opacity', 0.8);

        resetButton.append('text')
            .attr('x', 40)
            .attr('y', 20)
            .attr('text-anchor', 'middle')
            .style('fill', 'white')
            .style('font-size', '12px')
            .text('بازنشانی');

        // Create links (edges)
        const link = g.selectAll('.link')
            .data(treeData.links())
            .enter().append('path')
            .attr('class', 'link')
            .attr('d', d3.linkHorizontal()
                .x(d => d.y)
                .y(d => d.x))
            .style('fill', 'none')
            .style('stroke', '#ccc')
            .style('stroke-width', 2);

        // Create nodes
        const node = g.selectAll('.node')
            .data(treeData.descendants())
            .enter().append('g')
            .attr('class', 'node')
            .attr('transform', d => `translate(${d.y},${d.x})`);

        // Add circles for nodes
        node.append('circle')
            .attr('r', 8)
            .style('fill', d => {
                // اگر هفته‌ای انتخاب نشده، همه سبز
                if (!d.data.activationWeekNumber || d.data.activationWeekNumber === '') {
                    return '#4caf50';
                }
                // اگر در هفته هدف فعال شده، سبز، وگرنه قرمز
                return d.data.isActivatedInTargetWeek ? '#4caf50' : '#f44336';
            })
            .style('stroke', '#fff')
            .style('stroke-width', 2)
            .style('cursor', 'pointer')
            .on('click', (event, d) => {
                if (window.NetworkTreeViewer.dotNetRef) {
                    window.NetworkTreeViewer.dotNetRef.invokeMethodAsync('OnNodeClicked', d.data.userId);
                }
            });

        // Add user info labels
        node.append('text')
            .attr('dy', -15)
            .attr('text-anchor', 'middle')
            .style('font-size', '12px')
            .style('font-weight', 'bold')
            .style('fill', d => d.data.isClubActive ? '#424242' : '#9e9e9e')
            .text(d => d.data.userName || `User ${d.data.userId}`);

        // Add level info
        node.append('text')
            .attr('dy', 20)
            .attr('text-anchor', 'middle')
            .style('font-size', '10px')
            .style('fill', '#666')
            .text(d => `سطح ${d.data.level}`);

        // Add leg indicator (Left/Right)
        node.append('text')
            .attr('dy', 32)
            .attr('text-anchor', 'middle')
            .style('font-size', '9px')
            .style('fill', d => d.data.networkLeg === 0 ? '#4caf50' : '#ff9800')
            .text(d => d.data.networkLeg === 0 ? 'چپ' : 'راست');

        // Enhanced tooltip with club info
        node.append('title')
            .text(d => {
                let tooltip = `نام: ${d.data.userName || 'User ' + d.data.userId}\nسطح: ${d.data.level}\nپایه: ${d.data.networkLeg === 0 ? 'چپ' : 'راست'}`;
                
                if (d.data.userCreated) {
                    tooltip += `\nتاریخ ثبت‌نام: ${d.data.userCreated}`;
                }
                
                tooltip += `\nوضعیت باشگاه: ${d.data.isClubActive ? 'فعال' : 'غیرفعال'}`;
                
                if (d.data.clubActivatedAt) {
                    tooltip += `\nتاریخ فعالسازی باشگاه: ${d.data.clubActivatedAt}`;
                }
                
                if (d.data.activationWeekNumber) {
                    tooltip += `\nهفته فعالسازی: ${d.data.activationWeekNumber}`;
                }
                
                return tooltip;
            });

        // Add legend
        const legend = svg.append('g')
            .attr('transform', `translate(${width - 180}, 20)`);

        // Legend for title colors (club status)
        legend.append('text')
            .attr('x', 0)
            .attr('y', 0)
            .style('font-size', '12px')
            .style('font-weight', 'bold')
            .style('fill', '#424242')
            .text('باشگاه فعال');

        legend.append('text')
            .attr('x', 0)
            .attr('y', 20)
            .style('font-size', '12px')
            .style('font-weight', 'bold')
            .style('fill', '#9e9e9e')
            .text('باشگاه غیرفعال');

        // Legend for circles (week status)
        legend.append('circle')
            .attr('cx', 0)
            .attr('cy', 50)
            .attr('r', 6)
            .style('fill', '#4caf50');
        
        legend.append('text')
            .attr('x', 12)
            .attr('y', 54)
            .style('font-size', '12px')
            .text('فعال در هفته هدف');

        legend.append('circle')
            .attr('cx', 0)
            .attr('cy', 75)
            .attr('r', 6)
            .style('fill', '#f44336');
        
        legend.append('text')
            .attr('x', 12)
            .attr('y', 79)
            .style('font-size', '12px')
            .text('خارج از هفته هدف');
    },

    buildHierarchy: function(nodes) {
        if (!nodes || nodes.length === 0) return null;

        // Find root (parent with no parent or lowest level)
        const root = nodes.find(n => !n.parentId || n.parentId === 0) || nodes[0];

        const nodeMap = new Map();
        nodes.forEach(node => {
            nodeMap.set(node.userId, {
                userId: node.userId,
                userName: node.userName,
                parentId: node.parentId,
                level: node.networkLevel,
                networkLeg: node.networkLeg,
                isActive: node.isActive,
                isClubActive: node.isClubActive,
                isActivatedInTargetWeek: node.isActivatedInTargetWeek,
                activationWeekNumber: node.activationWeekNumber,
                clubActivatedAt: node.clubActivatedAt,
                userCreated: node.userCreated,
                children: []
            });
        });

        // Build parent-child relationships
        nodes.forEach(node => {
            if (node.parentId && node.parentId !== node.userId) {
                const parent = nodeMap.get(node.parentId);
                const child = nodeMap.get(node.userId);
                if (parent && child) {
                    parent.children.push(child);
                }
            }
        });

        // Return root as D3 hierarchy
        const rootNode = nodeMap.get(root.userId);
        return d3.hierarchy(rootNode);
    },

    destroy: function(elementId) {
        const container = document.getElementById(elementId);
        if (container) {
            container.innerHTML = '';
        }
    }
};
