// Tree Context Menu Helper
window.treeContextMenu = {
    lastRightClickedNodeId: null,
    dotNetHelper: null,

    initialize: function (dotNetHelper) {
        this.dotNetHelper = dotNetHelper;
        console.log('Tree context menu initialized');
    },

    setupContextMenuTracking: function (treeViewSelector) {
        const treeElement = document.querySelector(treeViewSelector);
        if (!treeElement) {
            console.warn('Tree view element not found:', treeViewSelector);
            return;
        }

        // Add contextmenu event listener to track right-clicked nodes
        treeElement.addEventListener('contextmenu', (e) => {
            // Find the closest tree node element
            const nodeElement = e.target.closest('.e-list-item');
            if (nodeElement) {
                // Try multiple ways to get the node ID
                // 1. Try data-uid attribute (standard Syncfusion attribute)
                let nodeId = nodeElement.getAttribute('data-uid');
                
                // 2. Try aria-labelledby or id
                if (!nodeId) {
                    nodeId = nodeElement.getAttribute('id');
                }
                
                // 3. Try getting from nested elements
                if (!nodeId) {
                    const textContent = nodeElement.querySelector('.e-list-text');
                    if (textContent) {
                        // Try to find the node by visible text as fallback
                        console.log('Node text content:', textContent.innerText);
                    }
                    // Get the data-uid from parent or child elements
                    const parentWithUid = nodeElement.closest('[data-uid]');
                    if (parentWithUid) {
                        nodeId = parentWithUid.getAttribute('data-uid');
                    }
                }
                
                if (nodeId) {
                    this.lastRightClickedNodeId = nodeId;
                    console.log('Right-clicked node ID:', nodeId);
                    
                    // Notify Blazor component
                    if (this.dotNetHelper) {
                        this.dotNetHelper.invokeMethodAsync('OnNodeRightClick', nodeId);
                    }
                } else {
                    console.warn('Could not find node ID for right-clicked element');
                    console.log('Node element:', nodeElement);
                }
            }
        });

        console.log('Context menu tracking setup complete');
    },

    getLastRightClickedNodeId: function () {
        return this.lastRightClickedNodeId;
    },

    clearLastRightClickedNode: function () {
        this.lastRightClickedNodeId = null;
    }
};
