jQuery(document).ready(function($) {
    var editor;
    
    // Tab切换功能
    $('.nav-tab').on('click', function(e) {
        e.preventDefault();
        
        var tab = $(this).data('tab');
        
        // 更新激活的tab
        $('.nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');
        
        // 显示对应的面板
        $('.tab-pane').removeClass('active').hide();
        $('#' + tab + '-tab').addClass('active').show();
        
        // 如果切换到编辑器tab，初始化CodeMirror
        if (tab === 'editor') {
            setTimeout(function() {
                initCodeMirror();
            }, 100);
        }
    });
    
    // 文件树展开/折叠
    $(document).on('click', '.folder-toggle', function() {
        var children = $(this).parent().find('.folder-children').first();
        var icon = $(this);
        
        if (children.is(':visible')) {
            children.slideUp();
            icon.text('▶');
        } else {
            children.slideDown();
            icon.text('▼');
        }
    });
    
    // 点击文件加载到编辑器
    $(document).on('click', '.file-item:not(:has(.folder-toggle))', function() {
        var filePath = $(this).data('path');
        loadFileToEditor(filePath);
        
        // 切换到编辑器tab
        $('.nav-tab').removeClass('nav-tab-active');
        $('.nav-tab[data-tab="editor"]').addClass('nav-tab-active');
        $('.tab-pane').removeClass('active').hide();
        $('#editor-tab').addClass('active').show();
    });
    
    // 初始化CodeMirror编辑器
    function initCodeMirror() {
        if (editor) {
            return; // 已经初始化过
        }
        
        editor = CodeMirror.fromTextArea(document.getElementById("codemirror-editor"), {
            lineNumbers: true,
            theme: "clouds",
            mode: "application/x-httpd-php",
            autoCloseBrackets: true,
            matchBrackets: true,
            indentUnit: 4,
            indentWithTabs: true,
            smartIndent: true,
            tabSize: 4,
            extraKeys: {
                "Ctrl-Space": "autocomplete",
                "Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }
            },
            foldGutter: true,
            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
        });
        
        // 设置编辑器高度
        editor.setSize(null, 600);
    }
    
    // 文件模式切换
    $('#file-mode').on('change', function() {
        if (editor) {
            var mode = $(this).val();
            editor.setOption("mode", mode);
        }
    });
    
    // 保存文件
    $('#save-file').on('click', function() {
        if (!editor) {
            alert('编辑器未初始化');
            return;
        }
        
        var filePath = $('#current-file-path').val();
        var content = editor.getValue();
        
        if (!filePath) {
            alert('请先选择一个文件');
            return;
        }
        
        $.post(ace_ajax.ajax_url, {
            action: 'ace_file_operations',
            operation: 'save',
            file: filePath,
            content: content,
            nonce: ace_ajax.nonce
        }, function(response) {
            if (response.success) {
                alert(ace_ajax.i18n.save_success);
            } else {
                alert(ace_ajax.i18n.save_error + ': ' + response.data);
            }
        });
    });
    
    // 删除文件
    $('#delete-file').on('click', function() {
        var filePath = $('#current-file-path').val();
        
        if (!filePath) {
            alert('请先选择一个文件');
            return;
        }
        
        if (!confirm(ace_ajax.i18n.confirm_delete)) {
            return;
        }
        
        $.post(ace_ajax.ajax_url, {
            action: 'ace_file_operations',
            operation: 'delete',
            path: filePath,
            nonce: ace_ajax.nonce
        }, function(response) {
            if (response.success) {
                alert(ace_ajax.i18n.delete_success);
                $('#current-file-path').val('');
                if (editor) {
                    editor.setValue('');
                }
                // 刷新文件树
                refreshFileTree();
            } else {
                alert(ace_ajax.i18n.delete_error + ': ' + response.data);
            }
        });
    });
    
    // 下载文件
    $('#download-file').on('click', function() {
        var filePath = $('#current-file-path').val();
        
        if (!filePath) {
            alert('请先选择一个文件');
            return;
        }
        
        // 创建一个临时的下载链接
        var fileName = filePath.split('/').pop();
        var downloadUrl = ace_ajax.ajax_url + '?action=ace_download_file&file=' + encodeURIComponent(filePath) + '&nonce=' + ace_ajax.nonce;
        
        // 创建隐藏的iframe来触发下载
        var iframe = $('<iframe style="display:none;" />');
        iframe.attr('src', downloadUrl);
        $('body').append(iframe);
        setTimeout(function() {
            iframe.remove();
        }, 5000);
    });
    
    // 加载文件到编辑器
    function loadFileToEditor(filePath) {
        $.post(ace_ajax.ajax_url, {
            action: 'ace_file_operations',
            operation: 'read',
            file: filePath,
            nonce: ace_ajax.nonce
        }, function(response) {
            if (response.success) {
                // 初始化编辑器（如果尚未初始化）
                initCodeMirror();
                
                // 设置编辑器内容
                editor.setValue(response.data.content);
                editor.clearHistory(); // 清除历史记录
                $('#current-file-path').val(filePath);
                
                // 获取文件信息
                $.post(ace_ajax.ajax_url, {
                    action: 'ace_file_operations',
                    operation: 'get_file_info',
                    file: filePath,
                    nonce: ace_ajax.nonce
                }, function(infoResponse) {
                    if (infoResponse.success) {
                        var info = infoResponse.data;
                        var infoHtml = '<div class="file-info-box">' +
                            '<strong>文件信息:</strong> ' +
                            '大小: ' + formatFileSize(info.size) + ', ' +
                            '修改时间: ' + info.modified + ', ' +
                            '权限: ' + info.permissions + ', ' +
                            '可读: ' + (info.readable ? '是' : '否') + ', ' +
                            '可写: ' + (info.writable ? '是' : '否') +
                            '</div>';
                        $('#file-info').html(infoHtml);
                    }
                });
                
                // 根据文件扩展名设置模式
                var ext = filePath.split('.').pop().toLowerCase();
                var modeMap = {
                    'php': 'application/x-httpd-php',
                    'js': 'text/javascript',
                    'css': 'text/css',
                    'html': 'text/html',
                    'json': 'application/json',
                    'xml': 'application/xml',
                    'sql': 'text/x-sql',
                    'py': 'text/x-python'
                };
                
                if (modeMap[ext]) {
                    editor.setOption("mode", modeMap[ext]);
                    $('#file-mode').val(modeMap[ext]);
                }
            } else {
                alert(ace_ajax.i18n.read_error + ': ' + response.data);
            }
        });
    }
    
    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        var k = 1024;
        var sizes = ['Bytes', 'KB', 'MB', 'GB'];
        var i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 搜索代码
    $('#perform-search').on('click', function() {
        var term = $('#search-term').val();
        var scope = $('#search-scope').val();
        
        if (!term) {
            alert('请输入搜索关键词');
            return;
        }
        
        $.post(ace_ajax.ajax_url, {
            action: 'ace_code_search',
            term: term,
            scope: scope,
            nonce: ace_ajax.nonce
        }, function(response) {
            if (response.success) {
                var results = response.data;
                var html = '';
                
                if (results.length === 0) {
                    html = '<p>' + ace_ajax.i18n.no_results + '</p>';
                } else {
                    results.forEach(function(result) {
                        html += '<div class="search-result-item">';
                        html += '<div class="search-result-file">' + result.file + ' (第' + result.line + '行)</div>';
                        html += '<div class="search-result-line">' + result.content + '</div>';
                        html += '</div>';
                    });
                }
                
                $('#search-results').html(html);
            }
        });
    });
    
    // WebDAV测试连接
    $('#test-webdav').on('click', function() {
        var url = $('#webdav-url').val();
        var username = $('#webdav-username').val();
        var password = $('#webdav-password').val();
        
        if (!url || !username || !password) {
            alert('请填写所有字段');
            return;
        }
        
        $.post(ace_ajax.ajax_url, {
            action: 'ace_test_webdav_connection',
            url: url,
            username: username,
            password: password,
            nonce: ace_ajax.nonce
        }, function(response) {
            if (response.success) {
                alert('连接成功: ' + response.data);
            } else {
                alert('连接失败: ' + response.data);
            }
        }).fail(function() {
            alert('连接请求失败，请检查网络或服务器设置');
        });
    });
    
    // WebDAV同步
    $('#sync-webdav').on('click', function() {
        var url = $('#webdav-url').val();
        var username = $('#webdav-username').val();
        var password = $('#webdav-password').val();
        
        if (!url || !username || !password) {
            alert('请填写所有字段');
            return;
        }
        
        if (!confirm('确定要同步到WebDAV服务器吗？这可能会覆盖远程文件。')) {
            return;
        }
        
        $(this).prop('disabled', true).text('同步中...');
        
        $.post(ace_ajax.ajax_url, {
            action: 'ace_sync_webdav',
            url: url,
            username: username,
            password: password,
            nonce: ace_ajax.nonce
        }, function(response) {
            $('#sync-webdav').prop('disabled', false).text('同步到WebDAV');
            if (response.success) {
                alert('同步成功: ' + response.data);
            } else {
                alert('同步失败: ' + response.data);
            }
        }).fail(function() {
            $('#sync-webdav').prop('disabled', false).text('同步到WebDAV');
            alert('同步请求失败，请检查网络或服务器设置');
        });
    });
    
    // Nextcloud测试连接
    $('#test-nextcloud').on('click', function() {
        var url = $('#nextcloud-url').val();
        var username = $('#nextcloud-username').val();
        var password = $('#nextcloud-password').val();
        
        if (!url || !username || !password) {
            alert('请填写所有字段');
            return;
        }
        
        $.post(ace_ajax.ajax_url, {
            action: 'ace_test_nextcloud_connection',
            url: url,
            username: username,
            password: password,
            nonce: ace_ajax.nonce
        }, function(response) {
            if (response.success) {
                alert('连接成功: ' + response.data);
            } else {
                alert('连接失败: ' + response.data);
            }
        }).fail(function() {
            alert('连接请求失败，请检查网络或服务器设置');
        });
    });
    
    // Nextcloud同步
    $('#sync-nextcloud').on('click', function() {
        var url = $('#nextcloud-url').val();
        var username = $('#nextcloud-username').val();
        var password = $('#nextcloud-password').val();
        
        if (!url || !username || !password) {
            alert('请填写所有字段');
            return;
        }
        
        if (!confirm('确定要同步到Nextcloud服务器吗？这可能会覆盖远程文件。')) {
            return;
        }
        
        $(this).prop('disabled', true).text('同步中...');
        
        $.post(ace_ajax.ajax_url, {
            action: 'ace_sync_nextcloud',
            url: url,
            username: username,
            password: password,
            nonce: ace_ajax.nonce
        }, function(response) {
            $('#sync-nextcloud').prop('disabled', false).text('同步到Nextcloud');
            if (response.success) {
                alert('同步成功: ' + response.data);
            } else {
                alert('同步失败: ' + response.data);
            }
        }).fail(function() {
            $('#sync-nextcloud').prop('disabled', false).text('同步到Nextcloud');
            alert('同步请求失败，请检查网络或服务器设置');
        });
    });
    
    // 刷新文件树
    $('#refresh-files').on('click', function() {
        refreshFileTree();
    });
    
    function refreshFileTree() {
        $.post(ace_ajax.ajax_url, {
            action: 'ace_refresh_file_tree',
            root_path: ace_ajax.root_path,
            nonce: ace_ajax.nonce
        }, function(response) {
            if (response.success) {
                $('#file-tree').html(response.data);
            }
        });
    }
    
    // 创建文件夹
    $('#create-folder').on('click', function() {
        $('#folder-parent-path').val(ace_ajax.root_path);
        $('#folder-modal').show();
    });
    
    // 文件夹创建表单提交
    $('#folder-create-form').on('submit', function(e) {
        e.preventDefault();
        
        var folderName = $('#folder-name').val();
        var parentPath = $('#folder-parent-path').val();
        
        if (!folderName) {
            alert('请输入文件夹名称');
            return;
        }
        
        $.post(ace_ajax.ajax_url, {
            action: 'ace_file_operations',
            operation: 'create_folder',
            folder_name: folderName,
            parent_path: parentPath,
            nonce: ace_ajax.nonce
        }, function(response) {
            if (response.success) {
                alert(ace_ajax.i18n.create_folder_success);
                $('#folder-modal').hide();
                $('#folder-name').val('');
                refreshFileTree();
            } else {
                alert(ace_ajax.i18n.create_folder_error + ': ' + response.data);
            }
        });
    });
    
    // 模态框功能
    $('#upload-file, #upload-files').on('click', function() {
        $('#upload-modal').show();
    });
    
    $('.close, #upload-modal, #folder-modal').on('click', function(e) {
        if (e.target !== this) return;
        $('#upload-modal').hide();
        $('#folder-modal').hide();
    });
    
    // 阻止模态框内容区域点击时关闭模态框
    $('.ace-modal-content').on('click', function(e) {
        e.stopPropagation();
    });
    
    // 文件上传表单处理
    $('#file-upload-form').on('submit', function(e) {
        e.preventDefault();
        
        var formData = new FormData(this);
        formData.append('action', 'ace_file_operations');
        formData.append('operation', 'upload');
        formData.append('directory', $('#upload-directory').val());
        formData.append('nonce', ace_ajax.nonce);
        
        $.ajax({
            url: ace_ajax.ajax_url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    alert(ace_ajax.i18n.upload_success + ': ' + response.data);
                    $('#upload-modal').hide();
                    refreshFileTree();
                } else {
                    alert(ace_ajax.i18n.upload_error + ': ' + response.data);
                }
            },
            error: function() {
                alert('上传失败，请重试');
            }
        });
    });
    
    // 初始化编辑器（如果默认显示的是编辑器tab）
    if ($('#editor-tab').hasClass('active')) {
        initCodeMirror();
    }
});