/**
 * 类目选择弹窗逻辑
 */
class CategoryModal {
    constructor() {
        this.modal = null;
        this.input = null;
        this.hiddenInput = null;
        this.columnsContainer = null;
        this.breadcrumb = null;
        this.searchInput = null;
        this.confirmBtn = null;
        
        this.categoryData = null; // 完整类目树
        this.selectedPath = []; // 当前选中的路径 [node1, node2, ...]
        this.tempSelectedPath = []; // 弹窗中临时选中的路径
    }

    // 工厂模式调用的初始化方法
    init(modalElement) {
        console.log('初始化类目选择弹窗');
        this.modal = modalElement;
        this.input = document.getElementById('categoryInput');
        this.hiddenInput = document.getElementById('categoryId');
        
        if (!this.modal) return;

        this.columnsContainer = this.modal.querySelector('.category-columns-container');
        this.breadcrumb = this.modal.querySelector('#categoryBreadcrumb');
        this.searchInput = this.modal.querySelector('#categorySearchInput');
        this.confirmBtn = this.modal.querySelector('#confirmCategoryBtn');
        
        this.bindEvents();
        
        // 首次加载数据
        this.loadData();
    }

    bindEvents() {
        // 关闭弹窗 (工厂模式已处理通用关闭，这里处理特定逻辑)
        // ...

        // 确认选择
        if (this.confirmBtn) {
            // 移除旧的监听器（防止多次绑定）
            const newBtn = this.confirmBtn.cloneNode(true);
            this.confirmBtn.parentNode.replaceChild(newBtn, this.confirmBtn);
            this.confirmBtn = newBtn;
            
            this.confirmBtn.addEventListener('click', () => this.confirmSelection());
        }

        // 搜索 (简单的防抖)
        let timeout;
        if (this.searchInput) {
            this.searchInput.addEventListener('input', (e) => {
                clearTimeout(timeout);
                timeout = setTimeout(() => this.handleSearch(e.target.value), 300);
            });
        }
    }

    async loadData() {
        // 显示加载中...
        if (this.columnsContainer) {
            this.columnsContainer.innerHTML = '<div style="padding:20px; text-align:center; color:#999;">加载类目数据中...</div>';
        }
        
        const data = await window.categoryLoader.getData();
        if (data) {
            this.categoryData = data;
            this.renderColumns();
        } else {
            if (this.columnsContainer) {
                this.columnsContainer.innerHTML = '<div style="padding:20px; text-align:center; color:red;">数据加载失败，请重试</div>';
            }
        }
    }

    show() {
        if (!this.modal) return;
        this.modal.style.display = 'flex';
        
        // 重置视图到当前选中状态
        this.tempSelectedPath = [...this.selectedPath];
        if (this.categoryData) {
            this.renderColumns();
        } else {
            this.loadData();
        }
    }

    hide() {
        if (this.modal) {
            this.modal.style.display = 'none';
        }
    }

    /**
     * 渲染列视图
     * 根据 tempSelectedPath 渲染每一级
     */
    renderColumns() {
        this.columnsContainer.innerHTML = '';
        this.updateBreadcrumb();

        // 始终渲染第一级
        const rootNodes = this.categoryData.nodes || [];
        this.renderColumn(rootNodes, 0);

        // 渲染后续级别
        for (let i = 0; i < this.tempSelectedPath.length; i++) {
            const node = this.tempSelectedPath[i];
            if (node.nodes && node.nodes.length > 0) {
                this.renderColumn(node.nodes, i + 1);
            }
        }
    }

    /**
     * 渲染单列
     * @param {Array} nodes 节点列表
     * @param {Number} level 层级 (0-based)
     */
    renderColumn(nodes, level) {
        const column = document.createElement('div');
        column.className = 'category-column';
        
        // 当前层级选中的节点ID (如果有)
        const selectedNode = this.tempSelectedPath[level];
        
        nodes.forEach(node => {
            const item = document.createElement('div');
            item.className = 'category-item';
            
            const isSelected = selectedNode && selectedNode.name === node.name; // 这里假设name唯一，最好用id
            if (isSelected) {
                item.classList.add('active');
            }
            
            const hasChildren = node.nodes && node.nodes.length > 0;
            
            item.innerHTML = `
                <span class="category-name">${node.name}</span>
                ${hasChildren ? '<span class="category-arrow">></span>' : ''}
            `;
            
            item.addEventListener('click', () => {
                this.handleItemClick(node, level);
            });
            
            column.appendChild(item);
        });
        
        this.columnsContainer.appendChild(column);
        
        // 自动滚动到选中项
        if (selectedNode) {
            // 简单处理，实际可能需要计算位置
        }
    }

    handleItemClick(node, level) {
        // 更新路径：保留 0 到 level-1 的路径，添加当前节点
        this.tempSelectedPath = this.tempSelectedPath.slice(0, level);
        this.tempSelectedPath.push(node);
        
        // 重新渲染
        this.renderColumns();
    }

    updateBreadcrumb() {
        if (this.tempSelectedPath.length === 0) {
            this.breadcrumb.textContent = '请选择类目';
            return;
        }
        
        const pathNames = this.tempSelectedPath.map(n => n.name).join(' > ');
        this.breadcrumb.textContent = pathNames;
    }

    confirmSelection() {
        if (this.tempSelectedPath.length === 0) {
            alert('请先选择类目');
            return;
        }
        
        // 检查是否是叶子节点（可选，如果允许选择父节点则不需要）
        const lastNode = this.tempSelectedPath[this.tempSelectedPath.length - 1];
        if (lastNode.nodes && lastNode.nodes.length > 0) {
            // 如果必须选择叶子节点
            // alert('请选择最后一级类目');
            // return;
        }

        this.selectedPath = [...this.tempSelectedPath];
        
        // 更新输入框
        // 使用特殊分隔符 ➤ 避免与类目名称中的 / 冲突
        const pathNames = this.selectedPath.map(n => n.name).join(' ➤ ');
        this.input.value = pathNames;
        this.input.title = pathNames; // tooltip
        
        // 保存到本地缓存
        localStorage.setItem('lastSelectedCategory', pathNames);
        
        // 可以在这里存 ID 或其他值
        // this.hiddenInput.value = lastNode.id; 
        
        this.hide();
    }

    handleSearch(keyword) {
        if (!keyword || !keyword.trim()) {
            this.renderColumns(); // 恢复正常视图
            return;
        }
        
        const searchTerm = keyword.trim().toLowerCase();
        const results = [];
        
        // 递归搜索函数
        const searchRecursive = (nodes, currentPath) => {
            nodes.forEach(node => {
                const newPath = [...currentPath, node];
                
                // 检查当前节点是否匹配
                if (node.name.toLowerCase().includes(searchTerm)) {
                    results.push({
                        node: node,
                        path: newPath
                    });
                }
                
                // 递归搜索子节点
                if (node.nodes && node.nodes.length > 0) {
                    searchRecursive(node.nodes, newPath);
                }
            });
        };
        
        if (this.categoryData && this.categoryData.nodes) {
            searchRecursive(this.categoryData.nodes, []);
        }
        
        this.renderSearchResults(results, keyword);
    }

    renderSearchResults(results, keyword) {
        this.columnsContainer.innerHTML = '';
        
        if (results.length === 0) {
            this.columnsContainer.innerHTML = '<div style="padding:20px; text-align:center; color:#999;">未找到匹配的类目</div>';
            return;
        }
        
        const list = document.createElement('div');
        list.className = 'search-results-list';
        
        results.forEach(result => {
            const item = document.createElement('div');
            item.className = 'search-result-item';
            
            // 构建显示路径字符串
            const pathString = result.path.map(n => n.name).join(' ➤ ');
            
            // 高亮关键字
            const regex = new RegExp(keyword, 'gi');
            const highlightedPath = pathString.replace(regex, match => `<span class="search-highlight">${match}</span>`);
            
            item.innerHTML = highlightedPath;
            
            // 检查是否当前选中
            // 简单的比较：如果路径长度和ID都一致（这里简化比较最后一个节点的名称）
            const lastSelected = this.tempSelectedPath[this.tempSelectedPath.length - 1];
            if (lastSelected && lastSelected.name === result.node.name) {
                item.classList.add('active');
            }
            
            item.addEventListener('click', () => {
                // 移除其他选中状态
                list.querySelectorAll('.search-result-item').forEach(el => el.classList.remove('active'));
                item.classList.add('active');
                
                // 更新临时选中路径
                this.tempSelectedPath = result.path;
                this.updateBreadcrumb();
            });

            // 双击直接确认
            item.addEventListener('dblclick', () => {
                this.tempSelectedPath = result.path;
                this.confirmSelection();
            });
            
            list.appendChild(item);
        });
        
        this.columnsContainer.appendChild(list);
    }
}

// 导出单例
window.categoryModal = new CategoryModal();

// 适配工厂模式的初始化函数
window.initCategoryModal = function() {
    const modal = document.getElementById('categorySelectionModal');
    if (modal) {
        window.categoryModal.init(modal);
    }
};
