/* UI/UX Pro Max - 增强版 JavaScript */
/* ================================ */

// 等待 DOM 加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 初始化主题
    initTheme();
    
    // 初始化侧边栏
    initSidebar();
    
    // 初始化工具提示
    initTooltips();
    
    // 初始化动画
    initAnimations();
    
    // 初始化搜索高亮
    initSearchHighlight();
});

// 主题管理
function initTheme() {
    const themeToggle = document.querySelector('.theme-toggle');
    const savedTheme = localStorage.getItem('theme') || 'light';
    
    // 应用保存的主题
    document.documentElement.setAttribute('data-theme', savedTheme);
    
    if (themeToggle) {
        themeToggle.addEventListener('click', function() {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            
            // 添加切换动画
            showNotify('已切换到' + (newTheme === 'dark' ? '暗色' : '浅色') + '模式', 'info');
        });
    }
    
    // 监听系统主题变化
    if (window.matchMedia) {
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function(e) {
            if (!localStorage.getItem('theme')) {
                document.documentElement.setAttribute('data-theme', e.matches ? 'dark' : 'light');
            }
        });
    }
}

// 侧边栏管理
function initSidebar() {
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const sidebar = document.querySelector('.sidebar');
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            document.body.classList.toggle('sidebar-collapsed');
            
            // 保存状态
            const isCollapsed = document.body.classList.contains('sidebar-collapsed');
            localStorage.setItem('sidebar-collapsed', isCollapsed);
        });
        
        // 恢复侧边栏状态
        const savedState = localStorage.getItem('sidebar-collapsed');
        if (savedState === 'true') {
            document.body.classList.add('sidebar-collapsed');
        }
    }
    
    // 移动端侧边栏
    const menuToggle = document.querySelector('.menu-toggle');
    if (menuToggle && sidebar) {
        menuToggle.addEventListener('click', function() {
            sidebar.classList.toggle('open');
        });
        
        // 点击遮罩关闭侧边栏
        document.addEventListener('click', function(e) {
            if (window.innerWidth <= 992 && 
                !sidebar.contains(e.target) && 
                !menuToggle.contains(e.target) &&
                sidebar.classList.contains('open')) {
                sidebar.classList.remove('open');
            }
        });
    }
}

// 工具提示
function initTooltips() {
    const tooltipElements = document.querySelectorAll('[data-tooltip]');
    
    tooltipElements.forEach(function(el) {
        el.addEventListener('mouseenter', function() {
            this.style.position = 'relative';
        });
    });
}

// 动画初始化
function initAnimations() {
    // 为卡片添加入场动画
    const cards = document.querySelectorAll('.card, .stat-card');
    cards.forEach(function(card, index) {
        card.style.animationDelay = (index * 0.1) + 's';
    });
    
    // 为列表项添加入场动画
    const listItems = document.querySelectorAll('.file-item, .context-menu-item');
    listItems.forEach(function(item, index) {
        item.style.animationDelay = (index * 0.05) + 's';
    });
}

// 搜索高亮
function initSearchHighlight() {
    const searchInput = document.querySelector('#searchInput');
    const searchResults = document.querySelector('#searchResults');
    
    if (searchInput && searchResults) {
        let debounceTimer;
        
        searchInput.addEventListener('input', function() {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(function() {
                const query = searchInput.value.trim().toLowerCase();
                
                if (query.length > 0) {
                    highlightSearch(query);
                    showNotify('找到 ' + document.querySelectorAll('.search-highlight').length + ' 个匹配项', 'info');
                } else {
                    clearSearchHighlight();
                }
            }, 300);
        });
    }
}

// 高亮搜索结果
function highlightSearch(query) {
    clearSearchHighlight();
    
    const contentElements = document.querySelectorAll('.file-name, .breadcrumb-item');
    contentElements.forEach(function(el) {
        const text = el.textContent;
        const regex = new RegExp('(' + escapeRegExp(query) + ')', 'gi');
        
        if (regex.test(text)) {
            // 先转义HTML，再进行高亮替换
            const escapedText = escapeHtml(text);
            const escapedQuery = escapeHtml(query);
            const highlightRegex = new RegExp('(' + escapeRegExp(escapedQuery) + ')', 'gi');
            el.innerHTML = escapedText.replace(highlightRegex, '<span class="search-highlight">$1</span>');
        }
    });
}

// 清除搜索高亮
function clearSearchHighlight() {
    const highlights = document.querySelectorAll('.search-highlight');
    highlights.forEach(function(highlight) {
        const parent = highlight.parentNode;
        parent.replaceChild(document.createTextNode(highlight.textContent), highlight);
        parent.normalize();
    });
}

// 转义正则特殊字符
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

// 转义HTML特殊字符
function escapeHtml(text) {
    if (text === null || text === undefined) return '';
    return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

// 显示通知
function showNotify(message, type) {
    type = type || 'info';
    
    // 转义消息内容，防止XSS
    const escapedMessage = escapeHtml(message);
    
    let notify = document.querySelector('.notify');
    if (!notify) {
        notify = document.createElement('div');
        notify.className = 'notify ' + type;
        notify.innerHTML = '<i class="fas fa-info-circle"></i><span>' + escapedMessage + '</span>';
        document.body.appendChild(notify);
    } else {
        notify.className = 'notify ' + type;
        notify.innerHTML = '<i class="fas fa-' + getNotifyIcon(type) + '"></i><span>' + escapedMessage + '</span>';
    }
    
    notify.style.display = 'flex';
    
    // 3秒后自动隐藏
    setTimeout(function() {
        notify.style.display = 'none';
    }, 3000);
}

// 获取通知图标
function getNotifyIcon(type) {
    const icons = {
        'success': 'check-circle',
        'error': 'exclamation-circle',
        'warning': 'exclamation-triangle',
        'info': 'info-circle'
    };
    return icons[type] || 'info-circle';
}

// 显示加载状态
function showLoading(message) {
    message = message || '加载中...';
    
    // 转义消息内容，防止XSS
    const escapedMessage = escapeHtml(message);
    
    let overlay = document.querySelector('.progress-overlay');
    if (!overlay) {
        overlay = document.createElement('div');
        overlay.className = 'progress-overlay';
        overlay.innerHTML = '<div class="progress-box"><div class="progress-spinner"></div><p class="progress-text">' + escapedMessage + '</p></div>';
        document.body.appendChild(overlay);
    } else {
        overlay.querySelector('.progress-text').textContent = message;
    }
    
    overlay.style.display = 'flex';
    return overlay;
}

// 隐藏加载状态
function hideLoading() {
    const overlay = document.querySelector('.progress-overlay');
    if (overlay) {
        overlay.style.display = 'none';
    }
}

// 显示确认对话框
function showConfirm(message, onConfirm, onCancel) {
    const modal = document.createElement('div');
    modal.className = 'modal fade';
    // 转义消息内容，防止XSS
    const escapedMessage = escapeHtml(message);
    modal.innerHTML = '<div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">确认操作</h5></div><div class="modal-body"><p>' + escapedMessage + '</p></div><div class="modal-footer"><button class="btn btn-secondary" id="confirmCancel">取消</button><button class="btn btn-danger" id="confirmOk">确定</button></div></div></div>';
    
    document.body.appendChild(modal);
    jQuery(modal).modal('show');
    
    modal.querySelector('#confirmOk').addEventListener('click', function() {
        if (onConfirm) onConfirm();
        jQuery(modal).modal('hide');
        setTimeout(function() { modal.remove(); }, 300);
    });
    
    modal.querySelector('#confirmCancel').addEventListener('click', function() {
        if (onCancel) onCancel();
        jQuery(modal).modal('hide');
        setTimeout(function() { modal.remove(); }, 300);
    });
}

// 文件操作确认
function confirmFileOperation(message, operation) {
    showConfirm(message, function() {
        showLoading('正在执行操作...');
        operation();
    });
}

// 平滑滚动到元素
function scrollToElement(selector) {
    const element = document.querySelector(selector);
    if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
}

// 复制到剪贴板
function copyToClipboard(text, callback) {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(function() {
            showNotify('已复制到剪贴板', 'success');
            if (callback) callback();
        }).catch(function() {
            showNotify('复制失败，请手动复制', 'error');
        });
    } else {
        // 降级处理
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        
        try {
            document.execCommand('copy');
            showNotify('已复制到剪贴板', 'success');
            if (callback) callback();
        } catch (err) {
            showNotify('复制失败，请手动复制', 'error');
        }
        
        document.body.removeChild(textarea);
    }
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 格式化日期时间
function formatDateTime(timestamp) {
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;
}

// 获取文件图标
function getFileIcon(filename) {
    const ext = filename.split('.').pop().toLowerCase();
    const iconMap = {
        // 文件夹
        'folder': 'fa-folder',
        
        // 图片
        'jpg': 'fa-file-image', 'jpeg': 'fa-file-image', 'png': 'fa-file-image',
        'gif': 'fa-file-image', 'bmp': 'fa-file-image', 'svg': 'fa-file-image', 'webp': 'fa-file-image',
        
        // 视频
        'mp4': 'fa-file-video', 'avi': 'fa-file-video', 'mov': 'fa-file-video',
        'mkv': 'fa-file-video', 'wmv': 'fa-file-video', 'flv': 'fa-file-video',
        
        // 音频
        'mp3': 'fa-file-audio', 'wav': 'fa-file-audio', 'ogg': 'fa-file-audio',
        'flac': 'fa-file-audio', 'aac': 'fa-file-audio',
        
        // 文档
        'pdf': 'fa-file-pdf', 'doc': 'fa-file-word', 'docx': 'fa-file-word',
        'xls': 'fa-file-excel', 'xlsx': 'fa-file-excel', 'ppt': 'fa-file-powerpoint',
        'pptx': 'fa-file-powerpoint', 'txt': 'fa-file-alt', 'md': 'fa-file-alt',
        
        // 压缩包
        'zip': 'fa-file-archive', 'rar': 'fa-file-archive', '7z': 'fa-file-archive',
        'tar': 'fa-file-archive', 'gz': 'fa-file-archive',
        
        // 代码
        'php': 'fa-file-code', 'js': 'fa-file-code', 'ts': 'fa-file-code',
        'html': 'fa-file-code', 'css': 'fa-file-code', 'json': 'fa-file-code',
        'py': 'fa-file-code', 'java': 'fa-file-code', 'c': 'fa-file-code',
        'cpp': 'fa-file-code', 'cs': 'fa-file-code', 'rb': 'fa-file-code',
        
        // 其他
        'exe': 'fa-file', 'dll': 'fa-file', 'iso': 'fa-file'
    };
    
    return iconMap[ext] || 'fa-file';
}

// 获取文件类型分类
function getFileTypeClass(filename) {
    const ext = filename.split('.').pop().toLowerCase();
    const typeMap = {
        'folder': 'folder',
        'jpg': 'image', 'jpeg': 'image', 'png': 'image', 'gif': 'image',
        'mp4': 'video', 'avi': 'video', 'mov': 'video', 'mkv': 'video',
        'mp3': 'audio', 'wav': 'audio', 'ogg': 'audio',
        'pdf': 'document', 'doc': 'document', 'docx': 'document',
        'xls': 'document', 'xlsx': 'document', 'txt': 'text', 'md': 'text',
        'zip': 'archive', 'rar': 'archive', '7z': 'archive',
        'php': 'code', 'js': 'code', 'ts': 'code', 'html': 'code', 'css': 'code',
        'py': 'code', 'java': 'code', 'rb': 'code'
    };
    
    return typeMap[ext] || 'text';
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(function() {
                inThrottle = false;
            }, limit);
        }
    };
}

// 防抖函数
function debounce(func, delay) {
    let debounceTimer;
    return function() {
        const context = this;
        const args = arguments;
        
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(function() {
            func.apply(context, args);
        }, delay);
    };
}

// 键盘快捷键
function initKeyboardShortcuts() {
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + F - 搜索
        if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
            e.preventDefault();
            const searchInput = document.querySelector('#searchInput');
            if (searchInput) {
                searchInput.focus();
            }
        }
        
        // Ctrl/Cmd + S - 保存
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            if (typeof confirmSaveFile === 'function') {
                confirmSaveFile();
            }
        }
        
        // Escape - 关闭模态框
        if (e.key === 'Escape') {
            const modals = document.querySelectorAll('.modal.show');
            modals.forEach(function(modal) {
                jQuery(modal).modal('hide');
            });
        }
    });
}

// 初始化键盘快捷键
initKeyboardShortcuts();

// 右键菜单
function initContextMenu() {
    const contextMenu = document.querySelector('.context-menu');
    
    if (contextMenu) {
        // 阻止默认右键菜单
        document.addEventListener('contextmenu', function(e) {
            if (e.target.closest('.file-item') || e.target.closest('.file-name')) {
                e.preventDefault();
                showContextMenu(e.pageX, e.pageY);
            }
        });
        
        // 点击其他区域关闭右键菜单
        document.addEventListener('click', function(e) {
            if (!contextMenu.contains(e.target)) {
                hideContextMenu();
            }
        });
    }
}

// 显示右键菜单
function showContextMenu(x, y) {
    const contextMenu = document.querySelector('.context-menu');
    if (contextMenu) {
        contextMenu.style.left = x + 'px';
        contextMenu.style.top = y + 'px';
        contextMenu.style.display = 'block';
        
        // 确保菜单不超出屏幕
        const rect = contextMenu.getBoundingClientRect();
        if (rect.right > window.innerWidth) {
            contextMenu.style.left = (window.innerWidth - rect.width - 10) + 'px';
        }
        if (rect.bottom > window.innerHeight) {
            contextMenu.style.top = (window.innerHeight - rect.height - 10) + 'px';
        }
    }
}

// 隐藏右键菜单
function hideContextMenu() {
    const contextMenu = document.querySelector('.context-menu');
    if (contextMenu) {
        contextMenu.style.display = 'none';
    }
}

// 文件拖拽上传
function initDragUpload() {
    const uploadArea = document.querySelector('.upload-area');
    
    if (uploadArea) {
        uploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = 'var(--primary-color)';
            this.style.background = 'var(--primary-light)';
        });
        
        uploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.style.borderColor = '';
            this.style.background = '';
        });
        
        uploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '';
            this.style.background = '';
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileUpload(files);
            }
        });
    }
    
    // 为上传按钮绑定点击事件
    const uploadBtn = document.getElementById('btUpload');
    if (uploadBtn) {
        uploadBtn.addEventListener('click', function() {
            // 创建文件选择输入框
            const input = document.createElement('input');
            input.type = 'file';
            input.multiple = true;
            input.style.display = 'none';
            input.addEventListener('change', function() {
                if (this.files.length > 0) {
                    handleFileUpload(this.files);
                }
            });
            document.body.appendChild(input);
            input.click();
            document.body.removeChild(input);
        });
    }
    
    // 为工具栏的上传按钮绑定点击事件
    const toolbarUploadItem = document.querySelector('.toolbar-dropdown-item[data-action="open-upload"]');
    if (toolbarUploadItem) {
        toolbarUploadItem.addEventListener('click', function() {
            const input = document.createElement('input');
            input.type = 'file';
            input.multiple = true;
            input.style.display = 'none';
            input.addEventListener('change', function() {
                if (this.files.length > 0) {
                    handleFileUpload(this.files);
                }
            });
            document.body.appendChild(input);
            input.click();
            document.body.removeChild(input);
        });
    }
}

// 处理文件上传
function handleFileUpload(files) {
    if (!files || files.length === 0) {
        return;
    }
    
    const currentPath = window.currentPath || '/';
    const CHUNK_THRESHOLD = 5 * 1024 * 1024; // 5MB以上使用分片上传
    
    // 检查是否有大文件需要分片上传
    let hasLargeFile = false;
    for (let i = 0; i < files.length; i++) {
        if (files[i].size > CHUNK_THRESHOLD) {
            hasLargeFile = true;
            break;
        }
    }
    
    // 如果有大文件，使用分片上传
    if (hasLargeFile) {
        handleChunkUpload(files);
        return;
    }
    
    // 普通上传模式
    const uploadUrl = window.apiBaseUrl + '/api.php?action=uploadfile';
    
    showLoading('正在上传文件...');
    
    // 逐个上传文件
    let uploadedCount = 0;
    let failedCount = 0;
    const totalFiles = files.length;
    
    function uploadNext(index) {
        if (index >= files.length) {
            hideLoading();
            if (failedCount > 0) {
                showNotify('上传完成：成功 ' + uploadedCount + ' 个，失败 ' + failedCount + ' 个', failedCount > 0 ? 'error' : 'success');
            } else {
                showNotify('成功上传 ' + uploadedCount + ' 个文件', 'success');
            }
            // 刷新文件列表
            if (typeof loadFileList === 'function') {
                loadFileList(currentPath);
            }
            return;
        }
        
        const file = files[index];
        const formData = new FormData();
        formData.append('dir', currentPath);
        formData.append('files[]', file);
        
        // 添加CSRF Token
        const csrfToken = document.getElementById('csrf_token') ? document.getElementById('csrf_token').value : '';
        if (csrfToken) {
            formData.append('csrf_token', csrfToken);
        }
        
        fetch(uploadUrl, {
            method: 'POST',
            body: formData,
            credentials: 'include'
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === true || data.code === 1) {
                uploadedCount++;
                console.log('文件上传成功:', file.name);
            } else {
                failedCount++;
                console.error('文件上传失败:', file.name, data.msg);
            }
            uploadNext(index + 1);
        })
        .catch(error => {
            failedCount++;
            console.error('文件上传错误:', file.name, error);
            uploadNext(index + 1);
        });
    }
    
    uploadNext(0);
}

// 处理分片上传（用于大文件）
function handleChunkUpload(files) {
    if (!files || files.length === 0) {
        return;
    }
    
    const currentPath = window.currentPath || '/';
    const CHUNK_SIZE = 1024 * 1024; // 1MB 分片大小
    
    showLoading('正在上传文件（分片模式）...');
    
    function uploadFileWithChunks(file, onComplete) {
        const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
        let currentChunk = 0;
        
        function uploadNextChunk() {
            if (currentChunk >= totalChunks) {
                onComplete();
                return;
            }
            
            const start = currentChunk * CHUNK_SIZE;
            const end = Math.min(start + CHUNK_SIZE, file.size);
            const chunk = file.slice(start, end);
            
            const formData = new FormData();
            formData.append('dir', currentPath);
            formData.append('fileName', file.name);
            formData.append('fileSize', file.size);
            formData.append('chunkIndex', currentChunk);
            formData.append('chunkSize', CHUNK_SIZE);
            formData.append('fileType', file.type || 'application/octet-stream');
            formData.append('chunk', chunk);
            
            // 添加CSRF Token
            const csrfToken = document.getElementById('csrf_token') ? document.getElementById('csrf_token').value : '';
            if (csrfToken) {
                formData.append('csrf_token', csrfToken);
            }
            
            fetch(window.apiBaseUrl + '/api.php?action=uploadchunk', {
                method: 'POST',
                body: formData,
                credentials: 'include'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === true || data.code === 1) {
                    currentChunk++;
                    showLoading('上传中: ' + Math.round((currentChunk / totalChunks) * 100) + '%');
                    uploadNextChunk();
                } else {
                    showNotify('分片上传失败: ' + (data.msg || '未知错误'), 'error');
                    onComplete();
                }
            })
            .catch(error => {
                console.error('分片上传错误:', error);
                showNotify('分片上传出错', 'error');
                onComplete();
            });
        }
        
        uploadNextChunk();
    }
    
    let uploadedCount = 0;
    let failedCount = 0;
    const totalFiles = files.length;
    
    function uploadNextFile(index) {
        if (index >= files.length) {
            hideLoading();
            if (failedCount > 0) {
                showNotify('上传完成：成功 ' + uploadedCount + ' 个，失败 ' + failedCount + ' 个', 'warning');
            } else {
                showNotify('成功上传 ' + uploadedCount + ' 个文件', 'success');
            }
            // 刷新文件列表
            if (typeof loadFileList === 'function') {
                loadFileList(currentPath);
            }
            return;
        }
        
        const file = files[index];
        // 如果文件大于5MB，使用分片上传
        if (file.size > 5 * 1024 * 1024) {
            uploadFileWithChunks(file, function() {
                uploadedCount++;
                uploadNextFile(index + 1);
            });
        } else {
            // 小文件直接上传
            const formData = new FormData();
            formData.append('dir', currentPath);
            formData.append('files[]', file);
            
            // 添加CSRF Token
            const csrfToken = document.getElementById('csrf_token') ? document.getElementById('csrf_token').value : '';
            if (csrfToken) {
                formData.append('csrf_token', csrfToken);
            }
            
            fetch(window.apiBaseUrl + '/api.php?action=uploadfile', {
                method: 'POST',
                body: formData,
                credentials: 'include'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === true || data.code === 1) {
                    uploadedCount++;
                } else {
                    failedCount++;
                }
                uploadNextFile(index + 1);
            })
            .catch(error => {
                failedCount++;
                uploadNextFile(index + 1);
            });
        }
    }
    
    uploadNextFile(0);
}

// 文件列表动画
function animateFileList() {
    const fileList = document.querySelector('.file-list');
    if (fileList) {
        const files = fileList.querySelectorAll('.file-item');
        files.forEach(function(file, index) {
            file.style.opacity = '0';
            file.style.transform = 'translateX(-20px)';
            
            setTimeout(function() {
                file.style.transition = 'all 0.3s ease';
                file.style.opacity = '1';
                file.style.transform = 'translateX(0)';
            }, index * 50);
        });
    }
}

// 选中动画
function toggleFileSelection(fileItem) {
    fileItem.classList.toggle('selected');
    
    const checkbox = fileItem.querySelector('input[type="checkbox"]');
    if (checkbox) {
        checkbox.checked = fileItem.classList.contains('selected');
    }
    
    // 更新选中计数
    updateSelectedCount();
}

// 更新选中计数
function updateSelectedCount() {
    const selectedFiles = document.querySelectorAll('.file-item.selected');
    const countBadge = document.querySelector('#selectedCount');
    
    if (countBadge) {
        countBadge.textContent = selectedFiles.length;
        countBadge.style.display = selectedFiles.length > 0 ? 'inline' : 'none';
    }
}

// 全选/取消全选
function toggleSelectAll(source) {
    const checkboxes = document.querySelectorAll('.file-item input[type="checkbox"]');
    checkboxes.forEach(function(checkbox) {
        checkbox.checked = source.checked;
        const fileItem = checkbox.closest('.file-item');
        if (fileItem) {
            if (source.checked) {
                fileItem.classList.add('selected');
            } else {
                fileItem.classList.remove('selected');
            }
        }
    });
    updateSelectedCount();
}

// 页面加载动画
function pageLoadAnimation() {
    const content = document.querySelector('.main-content');
    if (content) {
        content.style.opacity = '0';
        content.style.transform = 'translateY(20px)';
        
        setTimeout(function() {
            content.style.transition = 'all 0.5s ease';
            content.style.opacity = '1';
            content.style.transform = 'translateY(0)';
        }, 100);
    }
}

// 初始化页面加载动画
pageLoadAnimation();

// 导出功能
function exportFunctions() {
    window.UIUXProMax = {
        showNotify: showNotify,
        showLoading: showLoading,
        hideLoading: hideLoading,
        showConfirm: showConfirm,
        copyToClipboard: copyToClipboard,
        formatFileSize: formatFileSize,
        formatDateTime: formatDateTime,
        getFileIcon: getFileIcon,
        getFileTypeClass: getFileTypeClass,
        throttle: throttle,
        debounce: debounce,
        scrollToElement: scrollToElement,
        toggleFileSelection: toggleFileSelection,
        updateSelectedCount: updateSelectedCount,
        toggleSelectAll: toggleSelectAll,
        highlightSearch: highlightSearch,
        clearSearchHighlight: clearSearchHighlight
    };
}

exportFunctions();
