/**
 * d3-org-chart integration for BackOffice Admin
 * Network Binary Tree visualization with admin features
 */

window.AdminOrgChart = {
    chart: null,
    dotNetHelper: null,
    containerId: null,

    /**
     * Initialize the organization chart
     * @param {string} containerId - The ID of the container element
     * @param {object} data - The tree data in flat array format
     * @param {object} dotNetHelper - Blazor .NET helper for callbacks
     * @param {object} options - Chart options (filterWeek, etc.)
     */
    init: function (containerId, data, dotNetHelper, options = {}) {
        this.dotNetHelper = dotNetHelper;
        this.containerId = containerId;
        
        const container = document.getElementById(containerId);
        if (!container) {
            console.error('AdminOrgChart: Container not found:', containerId);
            return;
        }

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

        if (!data || data.length === 0) {
            container.innerHTML = '<div class="no-data-message" style="padding: 40px; text-align: center; color: #666;">داده‌ای برای نمایش وجود ندارد</div>';
            return;
        }

        try {
            const filterWeek = options.filterWeek || null;
            
            this.chart = new d3.OrgChart()
                .container('#' + containerId)
                .data(data)
                .nodeWidth((d) => 178)
                .nodeHeight((d) => 92)
                .childrenMargin((d) => 60)
                .compactMarginBetween((d) => 20)
                .compactMarginPair((d) => 20)
                .neighbourMargin((a, b) => 20)
                .siblingsMargin((d) => 20)
                .buttonContent(({ node, state }) => {
                    const hasChildren = node.data._directSubordinates > 0;
                    const isExpanded = node.children;
                    return hasChildren ? `<div class="admin-expand-btn">
                        <span>${isExpanded ? '−' : '+'}</span>
                    </div>` : '';
                })
                .linkUpdate(function (d, i, arr) {
                    d3.select(this)
                        .attr('stroke', (d) => d.data._highlighted || d.data._upToTheRootHighlighted ? '#1976d2' : '#bdbdbd')
                        .attr('stroke-width', (d) => d.data._highlighted || d.data._upToTheRootHighlighted ? 3 : 2);
                })
                .nodeContent(function (d, i, arr, state) {
                    const data = d.data;
                    const isRoot = !data.parentId || data.parentId === '';
                    
                    // Position styling
                    const positionClass = data.networkLeg === 0 ? 'leg-left' : 
                                          data.networkLeg === 1 ? 'leg-right' : 'leg-root';
                    
                    // Club status
                    const clubClass = data.isClubActive ? 'club-active' : 'club-inactive';
                    
                    // Week filter: check if this node is activated in target week
                    const isTargetWeek = data.isActivatedInTargetWeek;
                    const weekFilterActive = filterWeek && filterWeek > 0;
                    const isDisabledByWeekFilter = weekFilterActive && !isTargetWeek;
                    const disabledClass = isDisabledByWeekFilter ? 'week-disabled' : '';
                    
                    // Week activation status badge
                    let weekIndicator = '';
                    if (weekFilterActive && data.activationWeekDefinitionId) {
                        weekIndicator = `<div class="week-badge ${isTargetWeek ? 'week-match' : 'week-other'}">
                            W${data.activationWeekDefinitionId}
                        </div>`;
                    }
                    
                    // نوع فعالسازی - inline pill در meta row
                    let activationTypePill = '';
                    if (data.isNewActivation === true) {
                        activationTypePill = '<span class="activation-pill new-member-pill">عضو جدید</span>';
                    } else if (data.isNewActivation === false) {
                        activationTypePill = '<span class="activation-pill renewal-pill">تمدید</span>';
                    }

                    // نام پکیج badge
                    const packageBadge = data.packageName
                        ? `<div class="package-name-badge">${data.packageName}</div>`
                        : '';

                    // Avatar - first letter of name
                    const firstChar = data.userName ? data.userName.charAt(0).toUpperCase() : '?';
                    
                    // Level badge
                    const levelBadge = `<span class="level-badge">L${data.networkLevel || 0}</span>`;
                    
                    // Leg indicator
                    const legText = isRoot ? '' : (data.networkLeg === 0 ? 'چپ' : 'راست');
                    const legClass = data.networkLeg === 0 ? 'leg-text-left' : 'leg-text-right';

                    // Build tooltip text
                    const tooltipLines = [
                        `👤 ${data.userName || 'کاربر ' + data.userId}`,
                        `🆔 شناسه: ${data.userId}`,
                        `📊 سطح: ${data.networkLevel || 0}`,
                        `${data.networkLeg === 0 ? '⬅️' : '➡️'} موقعیت: ${data.networkLeg === 0 ? 'چپ' : 'راست'}`,
                        `${data.isClubActive ? '✅' : '❌'} باشگاه: ${data.isClubActive ? 'فعال' : 'غیرفعال'}`
                    ];
                    
                    if (data.clubActivatedAt) {
                        tooltipLines.push(`📅 فعالسازی: ${data.clubActivatedAt}`);
                    }
                    if (data.activationWeekDefinitionId) {
                        tooltipLines.push(`📆 هفته: ${data.activationWeekDefinitionId}`);
                    }
                    if (data.packageName) {
                        tooltipLines.push(`📦 پکیج: ${data.packageName}`);
                    }
                    if (data.isNewActivation === true) {
                        tooltipLines.push('🆕 نوع: اولین فعال‌سازی');
                    } else if (data.isNewActivation === false) {
                        tooltipLines.push('🔄 نوع: خرید مجدد');
                    }
                    if (weekFilterActive) {
                        tooltipLines.push(isTargetWeek ? '🎯 فعال در هفته انتخابی' : '⚪ خارج از هفته انتخابی');
                    }
                    
                    const tooltipText = tooltipLines.join('&#10;');

                    return `
                        <div class="admin-node-card ${positionClass} ${clubClass} ${disabledClass}" 
                             data-user-id="${data.userId}"
                             title="${tooltipText}">
                            ${weekIndicator}
                            <div class="node-header">
                                <div class="node-avatar">${firstChar}</div>
                                <div class="node-main-info">
                                    <div class="node-name">${data.userName || 'کاربر ' + data.userId}</div>
                                    ${packageBadge}
                                    <div class="node-meta">
                                        ${levelBadge}
                                        ${legText ? `<span class="${legClass}">${legText}</span>` : ''}
                                        ${activationTypePill}
                                    </div>
                                </div>
                            </div>
                            <div class="node-footer">
                                <span class="club-status ${clubClass}">
                                    ${data.isClubActive ? '✓ فعال' : '✗ غیرفعال'}
                                </span>
                                ${data.clubActivatedAt ? `<span class="activation-date">${data.clubActivatedAt}</span>` : ''}
                            </div>
                        </div>
                    `;
                })
                .onNodeClick((d) => {
                    if (this.dotNetHelper) {
                        const userId = parseInt(d.data.userId, 10);
                        this.dotNetHelper.invokeMethodAsync('OnNodeClicked', userId);
                    }
                })
                .render();

            // Initial fit
            setTimeout(() => {
                if (this.chart) {
                    this.chart.fit();
                }
            }, 100);

        } catch (error) {
            console.error('AdminOrgChart: Error initializing chart:', error);
            container.innerHTML = '<div class="error-message" style="padding: 40px; text-align: center; color: #f44336;">خطا در بارگذاری نمودار</div>';
        }
    },

    /**
     * Update the chart with new data
     */
    update: function (data, options = {}) {
        if (this.chart && this.containerId) {
            // Re-init with new data
            this.init(this.containerId, data, this.dotNetHelper, options);
        }
    },

    /**
     * Expand all nodes
     */
    expandAll: function () {
        if (this.chart) {
            this.chart.expandAll().render();
        }
    },

    /**
     * Collapse all nodes
     */
    collapseAll: function () {
        if (this.chart) {
            this.chart.collapseAll().render();
        }
    },

    /**
     * Center/Fit the chart
     */
    fit: function () {
        if (this.chart) {
            this.chart.fit();
        }
    },

    /**
     * Zoom to specific node
     */
    zoomToNode: function (nodeId) {
        if (this.chart) {
            this.chart.setCentered(nodeId.toString()).render();
        }
    },

    /**
     * Export chart as PNG
     */
    exportPng: function () {
        if (this.chart) {
            this.chart.exportImg({ full: true });
        }
    },

    /**
     * Export chart as SVG
     */
    exportSvg: function () {
        if (this.chart) {
            this.chart.exportSvg();
        }
    },

    /**
     * Dispose the chart
     */
    dispose: function () {
        if (this.chart) {
            this.chart = null;
            this.dotNetHelper = null;
            this.containerId = null;
        }
    }
};
