jQuery(document).ready(function($) {
    const fileManagerApp = {
        init() {
            this.bindEvents();
            this.loadFileTree();
        },

        bindEvents() {
            // 文件操作按钮事件
            $(document).on('click', '.file-action', this.handleFileAction.bind(this));
            $('#file-upload').on('change', this.handleFileUpload.bind(this));
        },

        handleFileUpload(e) {
            const formData = new FormData();
            formData.append('file', e.target.files[0]);
            formData.append('action', 'code_editor_file_action');
            formData.append('action_type', 'upload_file');
            formData.append('path', this.currentPath);
            formData.append('security', codeEditorVars.nonce);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: (response) => {
                    if (response.success) {
                        this.loadFileTree(this.currentPath);
                    } else {
                        console.error(response.data);
                    }
                }
            });
        },

        loadFileTree(path = '', parentPath = '') {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_file_action',
                    action_type: 'list_files',
                    path: path,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.renderFileTree(response.data, parentPath || path);
                    } else {
                        console.error(response.data);
                    }
                }
            });
        },

        renderFileTree(files, parentPath = '') {
            const $fileList = $('#file-list').empty();
            
            files.forEach(file => {
                const icon = file.type === 'directory' ? 'dashicons-portfolio' : 'dashicons-media-default';
                const indent = parentPath.split('/').length - 1;
                const indentPx = indent * 20;
                
                const $item = $(`
                    <div class="file-item" data-path="${file.path}" data-type="${file.type}" 
                         style="margin-left: ${indentPx}px">
                        <span class="dashicons ${icon}"></span>
                        <span class="file-name">${file.name}</span>
                    <div class="file-actions">
                        <button class="button file-action" data-action="edit">编辑</button>
                        <button class="button file-action" data-action="download">下载</button>
                        <button class="button file-action" data-action="zip">压缩</button>
                        <button class="button file-action" data-action="send_email">发送到邮箱</button>
                        ${file.type === 'directory' ? 
                          '<button class="button file-action" data-action="expand">+</button>' : ''}
                    </div>
                    </div>
                `);
                
                $fileList.append($item);
                
                // 鼠标悬停显示操作按钮
                $item.hover(
                    () => $item.find('.file-actions').show(),
                    () => $item.find('.file-actions').hide()
                );
                
                // 默认隐藏操作按钮
                $item.find('.file-actions').hide();
            });
        },

        handleFileAction(e) {
            const $target = $(e.currentTarget);
            const action = $target.data('action');
            const $fileItem = $target.closest('.file-item');
            const filePath = $fileItem.data('path');
            const fileType = $fileItem.data('type');

            switch (action) {
                case 'edit':
                    this.viewFile(filePath, fileType);
                    break;
                case 'download':
                    this.downloadFile(filePath);
                    break;
                case 'zip':
                    this.zipFile(filePath);
                    break;
                case 'send_email':
                    this.sendFileToEmail(filePath);
                    break;
                case 'expand':
                    this.loadFileTree(filePath, filePath);
                    break;
            }
        },

        viewFile(path, type) {
            if (type === 'directory') {
                this.loadFileTree(path, path);
            } else {
                const ext = path.split('.').pop().toLowerCase();
                const previewable = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'pdf', 'mp4', 'webm', 'mov', 'psd', 'cdr'];
                
                if (previewable.includes(ext)) {
                    this.previewFile(path, ext);
                } else {
                    this.loadFileContent(path);
                }
            }
        },

        previewFile(path, ext) {
            const $preview = $(`
                <div class="file-preview-modal">
                    <div class="preview-header">
                        <h3>${path.split('/').pop()}</h3>
                        <button class="close-preview">&times;</button>
                    </div>
                    <div class="preview-content">
                        ${this.getPreviewContent(path, ext)}
                    </div>
                </div>
            `);
            
            $('body').append($preview);
            $preview.find('.close-preview').on('click', () => $preview.remove());
            
            // 如果是Discuz文件，添加特殊样式
            if (path.includes('/template/') || path.includes('/source/plugin/')) {
                $preview.addClass('discuz-preview');
            }
        },

        getPreviewContent(path, ext) {
            const url = ajaxurl + '?action=code_editor_file_action&action_type=get_file&path=' + 
                       encodeURIComponent(path) + '&security=' + codeEditorVars.nonce;
            
            if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) {
                return `<img src="${url}" style="max-width: 100%; max-height: 80vh;">`;
            } else if (['mp4', 'webm', 'mov'].includes(ext)) {
                return `<video controls style="max-width: 100%; max-height: 80vh;">
                    <source src="${url}" type="video/${ext === 'mov' ? 'quicktime' : ext}">
                </video>`;
            } else if (ext === 'pdf') {
                return `<iframe src="${url}" style="width: 100%; height: 80vh;"></iframe>`;
            } else {
                return `<div class="unsupported-preview">
                    <p>不支持预览此文件类型</p>
                    <a href="${url}" class="button">下载文件</a>
                </div>`;
            }
        },

        loadFileContent(path) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_file_action',
                    action_type: 'get_file',
                    path: path,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.openEditor(response.data.content, path);
                    } else {
                        console.error(response.data);
                    }
                }
            });
        },

        openEditor(content, path) {
            $(document).trigger('codeEditor:openFile', {
                content: content,
                path: path
            });
        },
        
        downloadFile(path) {
            const link = document.createElement('a');
            link.href = ajaxurl + '?action=code_editor_file_action&action_type=download_file&path=' + 
                        encodeURIComponent(path) + '&security=' + codeEditorVars.nonce;
            link.download = path.split('/').pop();
            link.click();
        },
        
        zipFile(path) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_zip_file',
                    path: path,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.downloadFile(response.data.zip_path);
                    } else {
                        console.error(response.data);
                    }
                }
            });
        },

        sendFileToEmail(filePath) {
            const $dialog = $(`
                <div class="email-dialog">
                    <h3>发送文件到邮箱</h3>
                    <div class="form-group">
                        <label>选择邮箱服务</label>
                        <select id="email-protocol">
                            <option value="qqmail">QQ邮箱</option>
                            <option value="163mail">网易邮箱</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>收件人邮箱</label>
                        <input type="email" id="email-recipient" placeholder="recipient@example.com">
                    </div>
                    <div class="form-actions">
                        <button id="send-email" class="button button-primary">发送</button>
                        <button id="cancel-email" class="button">取消</button>
                    </div>
                </div>
            `);
            
            $('body').append($dialog);
            
            $('#send-email').on('click', () => {
                const protocol = $('#email-protocol').val();
                const recipient = $('#email-recipient').val();
                
                if (!recipient) {
                    alert('请输入收件人邮箱');
                    return;
                }

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'code_editor_send_to_email',
                        protocol: protocol,
                        file_path: filePath,
                        recipient: recipient,
                        security: codeEditorVars.nonce
                    },
                    success: (response) => {
                        if (response.success) {
                            alert('文件已成功发送到邮箱');
                            $dialog.remove();
                        } else {
                            alert('发送失败: ' + response.data);
                        }
                    }
                });
            });
            
            $('#cancel-email').on('click', () => {
                $dialog.remove();
            });
        }
    };

    fileManagerApp.init();
});