/**
 * Rubric Tree Interactions
 * Interactive tree view for Kent's Repertory
 */

// ============================================
// Rubric Tree Class
// ============================================

class RubricTree {
    constructor(containerId, options = {}) {
        this.container = document.getElementById(containerId);
        this.options = {
            selectable: true,
            editable: false,
            searchable: true,
            ...options
        };
        this.selectedRubrics = [];
        this.expandedNodes = new Set();
        
        this.init();
    }
    
    init() {
        if (!this.container) return;
        this.bindEvents();
        this.loadExpandedState();
        if (this.options.searchable) {
            this.initSearch();
        }
    }
    
    bindEvents() {
        // Toggle children
        this.container.addEventListener('click', (e) => {
            const toggle = e.target.closest('.toggle-icon');
            if (toggle) {
                e.stopPropagation();
                this.toggleNode(toggle.closest('.rubric-node'));
            }
            
            const rubricItem = e.target.closest('.rubric-item');
            if (rubricItem && !e.target.closest('.rubric-actions')) {
                const rubricId = rubricItem.closest('.rubric-node')?.dataset.id;
                const rubricName = rubricItem.querySelector('.rubric-name')?.textContent;
                if (rubricId && this.options.selectable) {
                    this.selectRubric(rubricId, rubricName);
                }
            }
        });
    }
    
    toggleNode(node) {
        const children = node.querySelector('.rubric-children');
        const icon = node.querySelector('.toggle-icon');
        
        if (children) {
            if (children.style.display === 'none') {
                children.style.display = 'block';
                icon.textContent = '▼';
                this.expandedNodes.add(node.dataset.id);
            } else {
                children.style.display = 'none';
                icon.textContent = '▶';
                this.expandedNodes.delete(node.dataset.id);
            }
            this.saveExpandedState();
        }
    }
    
    expandAll() {
        const allChildren = this.container.querySelectorAll('.rubric-children');
        const allIcons = this.container.querySelectorAll('.toggle-icon');
        
        allChildren.forEach(child => child.style.display = 'block');
        allIcons.forEach(icon => icon.textContent = '▼');
        
        // Record all nodes as expanded
        const allNodes = this.container.querySelectorAll('.rubric-node');
        allNodes.forEach(node => this.expandedNodes.add(node.dataset.id));
        this.saveExpandedState();
    }
    
    collapseAll() {
        const allChildren = this.container.querySelectorAll('.rubric-children');
        const allIcons = this.container.querySelectorAll('.toggle-icon');
        
        allChildren.forEach(child => child.style.display = 'none');
        allIcons.forEach(icon => icon.textContent = '▶');
        this.expandedNodes.clear();
        this.saveExpandedState();
    }
    
    selectRubric(id, name) {
        if (!this.selectedRubrics.includes(id)) {
            this.selectedRubrics.push(id);
            this.updateSelectedDisplay(id, name);
            this.trigger('rubricSelected', { id, name });
        }
    }
    
    removeRubric(id) {
        const index = this.selectedRubrics.indexOf(id);
        if (index !== -1) {
            this.selectedRubrics.splice(index, 1);
            const element = document.querySelector(`.selected-rubric-item[data-id="${id}"]`);
            if (element) element.remove();
            this.trigger('rubricRemoved', { id });
        }
    }
    
    updateSelectedDisplay(id, name) {
        const container = document.getElementById('selectedRubricsList');
        if (container) {
            const item = document.createElement('div');
            item.className = 'selected-rubric-item';
            item.dataset.id = id;
            item.innerHTML = `
                <span>${name}</span>
                <button type="button" class="btn-remove" onclick="rubricTree.removeRubric(${id})">×</button>
            `;
            container.appendChild(item);
        }
    }
    
    initSearch() {
        const searchInput = document.getElementById('rubricSearch');
        if (!searchInput) return;
        
        let searchTimeout;
        searchInput.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                this.search(e.target.value);
            }, 300);
        });
    }
    
    async search(query) {
        if (query.length < 2) {
            this.showAllNodes();
            return;
        }
        
        try {
            const response = await fetch('api/search-rubrics.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `query=${encodeURIComponent(query)}`
            });
            const data = await response.json();
            
            if (data.success && data.results.length) {
                this.displaySearchResults(data.results);
            } else {
                this.showAllNodes();
            }
        } catch (error) {
            console.error('Search error:', error);
        }
    }
    
    displaySearchResults(results) {
        const treeContainer = this.container;
        const searchResults = document.getElementById('searchResults');
        
        if (searchResults) {
            let html = '<div class="search-results-list">';
            results.forEach(rubric => {
                html += `
                    <div class="search-result-item" onclick="rubricTree.selectRubric(${rubric.id}, '${rubric.full_path}')">
                        <strong>${rubric.full_path}</strong>
                        <small class="text-muted">(${rubric.remedy_count} remedies)</small>
                    </div>
                `;
            });
            html += '</div>';
            searchResults.innerHTML = html;
            searchResults.style.display = 'block';
            treeContainer.style.display = 'none';
        }
    }
    
    showAllNodes() {
        const treeContainer = this.container;
        const searchResults = document.getElementById('searchResults');
        if (searchResults) {
            searchResults.style.display = 'none';
            treeContainer.style.display = 'block';
        }
    }
    
    saveExpandedState() {
        localStorage.setItem('rubric_expanded', JSON.stringify([...this.expandedNodes]));
    }
    
    loadExpandedState() {
        const saved = localStorage.getItem('rubric_expanded');
        if (saved) {
            const expanded = JSON.parse(saved);
            expanded.forEach(id => {
                const node = this.container.querySelector(`.rubric-node[data-id="${id}"]`);
                if (node) {
                    const children = node.querySelector('.rubric-children');
                    const icon = node.querySelector('.toggle-icon');
                    if (children) {
                        children.style.display = 'block';
                        if (icon) icon.textContent = '▼';
                    }
                }
            });
        }
    }
    
    trigger(event, data) {
        const customEvent = new CustomEvent(event, { detail: data });
        this.container.dispatchEvent(customEvent);
    }
    
    getSelectedRubrics() {
        return this.selectedRubrics;
    }
}

// Initialize rubric tree
let rubricTree = null;

document.addEventListener('DOMContentLoaded', () => {
    const rubricContainer = document.getElementById('rubricTree');
    if (rubricContainer) {
        rubricTree = new RubricTree('rubricTree', {
            selectable: true,
            editable: document.body.classList.contains('admin-panel')
        });
    }
});