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

        bindEvents() {
            $(document).on('codeEditor:openFile', (e, data) => {
                this.openFile(data.content, data.path);
            });
        },

        initEditor() {
            this.editor = CodeMirror(document.getElementById('code-editor-app'), {
                lineNumbers: true,
                mode: 'text/x-php',
                theme: 'default',
                indentUnit: 4,
                tabSize: 4,
                lineWrapping: true,
                autoCloseBrackets: true,
                matchBrackets: {maxScanLineLength: 10000},
                highlightSelectionMatches: {showToken: /\w/},
                autoCloseTags: true,
                foldGutter: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                extraKeys: {
                    'Ctrl-S': this.saveFile.bind(this),
                    'Cmd-S': this.saveFile.bind(this),
                    'Ctrl-F': 'findPersistent',
                    'F11': function(cm) {
                        cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                    },
                    'Esc': function(cm) {
                        if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
                    }
                }
            });
        },

        openFile(content, path) {
            this.currentFilePath = path;
            this.editor.setValue(content);
            
            // 根据文件扩展名设置语法高亮模式
            const mode = this.getModeFromExtension(path);
            if (mode) {
                this.editor.setOption('mode', mode);
                CodeMirror.autoLoadMode(this.editor, mode);
            }
        },

        getModeFromExtension(path) {
            const extension = path.split('.').pop().toLowerCase();
            const modes = {
                'js': 'javascript',
                'php': 'text/x-php',
                'css': 'css',
                'html': 'htmlmixed',
                'py': 'python',
                'json': 'application/json',
                'md': 'markdown',
                'xml': 'xml',
                'sql': 'sql',
                'sh': 'shell',
                'scss': 'text/x-scss',
                'less': 'text/x-less',
                'ts': 'text/typescript'
            };
            return modes[extension] || null;
        },

        saveFile() {
            const content = this.editor.getValue();
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_save_file',
                    path: this.currentFilePath,
                    content: content,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showMessage('文件保存成功');
                        this.checkPreviewAvailability();
                    } else {
                        this.showMessage('保存失败: ' + response.data, 'error');
                    }
                }
            });
        },

        checkPreviewAvailability() {
            const path = this.currentFilePath;
            if (path.endsWith('.php') && path.includes('/plugins/')) {
                this.enablePreviewButton('plugin');
            } else if (path.endsWith('style.css') && path.includes('/themes/')) {
                this.enablePreviewButton('theme');
            } else if (path.endsWith('.htm') && path.includes('/template/')) {
                this.enablePreviewButton('discuz_theme');
            } else if (path.endsWith('.php') && path.includes('/source/plugin/')) {
                this.enablePreviewButton('discuz_plugin');
            } else {
                this.disablePreviewButton();
            }
        },

        enablePreviewButton(type) {
            let $previewBtn = $('#preview-button');
            if ($previewBtn.length === 0) {
                $previewBtn = $(`<button id="preview-button" class="button button-primary">预览${type === 'plugin' ? '插件' : '主题'}</button>`);
                $('.CodeMirror').before($previewBtn);
            }
            
            $previewBtn.off('click').on('click', () => {
                this.previewContent(type);
            }).text(`预览${type === 'plugin' ? '插件' : '主题'}`);
        },

        disablePreviewButton() {
            $('#preview-button').remove();
        },

        previewContent(type) {
            const content = this.editor.getValue();
            const slug = this.currentFilePath.split('/').slice(-2, -1)[0];
            
            // 先清理旧的预览
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_clean_preview',
                    type: type,
                    slug: slug,
                    security: codeEditorVars.nonce
                },
                success: () => {
                    // 创建新的预览
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: `code_editor_preview_${type}`,
                            [`${type}_slug`]: slug,
                            [`${type}_content`]: content,
                            security: codeEditorVars.nonce
                        },
                        success: (response) => {
                            if (response.success) {
                                this.showMessage(response.data.message);
                                const previewWindow = window.open(response.data.preview_url, '_blank');
                                
                                // 添加预览关闭监听
                                if (previewWindow) {
                                    const checkInterval = setInterval(() => {
                                        if (previewWindow.closed) {
                                            clearInterval(checkInterval);
                                            this.cleanupPreview(type, slug);
                                        }
                                    }, 1000);
                                }
                            } else {
                                this.showMessage(response.data, 'error');
                            }
                        }
                    });
                }
            });
        },

        enablePreviewButton(type) {
            let $previewBtn = $('#preview-button');
            if ($previewBtn.length === 0) {
                const btnText = {
                    'plugin': '预览插件',
                    'theme': '预览主题',
                    'discuz_theme': '预览Discuz主题',
                    'discuz_plugin': '预览Discuz插件'
                };
                $previewBtn = $(`<button id="preview-button" class="button button-primary">${btnText[type]}</button>`);
                $('.CodeMirror').before($previewBtn);
            }
            
            $previewBtn.off('click').on('click', () => {
                this.previewContent(type);
            }).text(btnText[type]);
        },

        cleanupPreview(type, slug) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_clean_preview',
                    type: type,
                    slug: slug,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showMessage('预览已清理');
                    }
                }
            });
        },

        showMessage(message, type = 'success') {
            const $message = $('#editor-message');
            $message.text(message).removeClass('error success').addClass(type).fadeIn();
            setTimeout(() => $message.fadeOut(), 3000);
        }
    };

    // 加载CodeMirror资源
    const loadCodeMirror = () => {
        const baseUrl = plugin_dir_url + 'assets/codemirror/';
        
        // 加载核心CSS和JS
        $('head').append(
            `<link rel="stylesheet" href="${baseUrl}lib/codemirror.css">` +
            `<script src="${baseUrl}lib/codemirror.js"></script>`
        );
        
        // 加载模式和主题
        const scripts = [
            `${baseUrl}mode/javascript/javascript.js`,
            `${baseUrl}mode/php/php.js`,
            `${baseUrl}mode/htmlmixed/htmlmixed.js`,
            `${baseUrl}mode/css/css.js`,
            `${baseUrl}mode/python/python.js`,
            `${baseUrl}mode/xml/xml.js`,
            `${baseUrl}mode/sql/sql.js`,
            `${baseUrl}mode/shell/shell.js`,
            `${baseUrl}mode/markdown/markdown.js`
        ];
        
        scripts.forEach(script => {
            $('head').append(`<script src="${script}"></script>`);
        });
        
        // 初始化编辑器
        $.when.apply($, scripts.map(script => $.getScript(script)))
            .done(() => codeEditorApp.init());
    };
    
    // 确保DOM加载完成后加载CodeMirror
    if (typeof CodeMirror === 'undefined') {
        loadCodeMirror();
    } else {
        codeEditorApp.init();
    }
});