(function() {
    'use strict';

    /**
     * 自定义编辑器按钮插件
     * 为TinyMCE编辑器添加目录、下载地址、免费下载地址等功能按钮
     * 
     * 样式文件: assets/css/editor-dialogs.css
     * 依赖: TinyMCE编辑器
     */

    tinymce.PluginManager.add('custom_editor_buttons', function(editor, url) {
        


        // 插入下载地址按钮
        editor.addButton('insert_download', {
            title: '插入下载地址',
            icon: 'insert-download',
            onclick: function() {
                showDownloadDialog(editor);
            }
        });

        // 插入样式链接按钮
        editor.addButton('insert_styled_link', {
            title: '插入样式链接',
            icon: 'insert-styled-link',
            onclick: function() {
                showStyledLinkDialog(editor);
            }
        });





        // 显示下载地址对话框
        function showDownloadDialog(editor) {
            var dialog = createDialog('插入下载地址', getDownloadDialogContent(), function() {
                var title = document.getElementById('download-title').value;
                var url = document.getElementById('download-url').value;
                var size = document.getElementById('download-size').value;
                var format = document.getElementById('download-format').value;
                var password = document.getElementById('download-password').value;
                var description = document.getElementById('download-description').value;
                
                if (!title || !url) {
                    alert('请填写标题和下载地址');
                    return;
                }
                
                var downloadShortcode = generateDownloadHtml(title, url, size, format, password, description);
                
                // 在当前光标位置插入短代码
                editor.execCommand('mceInsertContent', false, downloadShortcode + '\n\n');
                closeDialog();
            });
            
            document.body.appendChild(dialog);
            
            // 聚焦第一个输入框
            setTimeout(function() {
                var firstInput = dialog.querySelector('input');
                if (firstInput) {
                    firstInput.focus();
                }
            }, 100);
        }

        // 显示样式链接对话框
        function showStyledLinkDialog(editor) {
            var dialog = createDialog('插入样式链接', getStyledLinkDialogContent(), function() {
                var linkText = document.getElementById('link-text').value;
                var linkUrl = document.getElementById('link-url').value;
                var selectedStyle = document.getElementById('style-select').value;
                var customCss = document.getElementById('custom-css').value;
                var targetBlank = document.getElementById('target-blank').checked;
                
                if (!linkText || !linkUrl) {
                    alert('请填写链接文本和链接地址');
                    return;
                }
                
                var finalCss = selectedStyle === 'custom' ? customCss : selectedStyle;
                if (!finalCss && selectedStyle !== 'none') {
                    alert('请选择样式或输入自定义CSS');
                    return;
                }
                
                var styledLink = generateStyledLinkHtml(linkText, linkUrl, finalCss, targetBlank);
                
                // 在当前光标位置插入链接
                editor.execCommand('mceInsertContent', false, styledLink);
                closeDialog();
            });
            
            document.body.appendChild(dialog);
            
            // 初始化标签页功能
            initLinkDialogTabs();
            
            // 加载样式选项
            loadLinkStyles();
            
            // 初始化文章搜索功能
            initPostSearch();
            
            // 聚焦第一个输入框
            setTimeout(function() {
                var firstInput = dialog.querySelector('input');
                if (firstInput) {
                    firstInput.focus();
                }
            }, 100);
        }



        // 创建对话框
        function createDialog(title, content, onConfirm) {
            var overlay = document.createElement('div');
            overlay.className = 'custom-dialog-overlay';
            
            // 只有点击背景overlay时才关闭对话框
            overlay.onclick = function(e) {
                if (e.target === overlay) {
                    closeDialog();
                }
            };
            
            var dialog = document.createElement('div');
            dialog.className = 'custom-editor-dialog';
            
            // 阻止对话框内部的点击事件冒泡
            dialog.onclick = function(e) {
                e.stopPropagation();
            };
            
            dialog.innerHTML = 
                '<div class="custom-dialog-header">' + 
                    title + 
                    '<button type="button" class="dialog-close-btn" onclick="closeDialog()">&times;</button>' +
                '</div>' +
                '<div class="custom-dialog-content">' + content + '</div>' +
                '<div class="custom-dialog-footer">' +
                    '<button type="button" class="btn btn-secondary" onclick="closeDialog()">取消</button>' +
                    '<button type="button" class="btn btn-primary" id="confirm-btn">确定</button>' +
                '</div>';
            
            overlay.appendChild(dialog);
            
            // 绑定确定按钮事件
            setTimeout(function() {
                var confirmBtn = document.getElementById('confirm-btn');
                if (confirmBtn) {
                    confirmBtn.onclick = function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        onConfirm();
                    };
                }
                
                // 添加键盘支持
                document.addEventListener('keydown', handleKeyDown);
            }, 100);
            
            return overlay;
        }

        // 关闭对话框
        window.closeDialog = function() {
            var overlay = document.querySelector('.custom-dialog-overlay');
            if (overlay) {
                // 移除键盘事件监听器
                document.removeEventListener('keydown', handleKeyDown);
                overlay.remove();
            }
        };
        
        // 键盘事件处理函数
        var handleKeyDown = function(e) {
            if (e.key === 'Escape') {
                closeDialog();
            }
        };



        // 获取下载地址对话框内容
        function getDownloadDialogContent() {
            return '<div class="form-field">' +
                '<label for="download-title">资源标题: <span style="color:red;">*</span></label>' +
                '<input type="text" id="download-title" placeholder="输入资源标题">' +
                '<small>下载资源的标题或名称</small>' +
            '</div>' +
            '<div class="form-field">' +
                '<label for="download-url">下载地址: <span style="color:red;">*</span></label>' +
                '<input type="url" id="download-url" placeholder="https://example.com/file.zip">' +
                '<small>资源的下载链接地址</small>' +
            '</div>' +
            '<div class="form-field">' +
                '<label for="download-size">文件大小:</label>' +
                '<input type="text" id="download-size" placeholder="例如: 128MB">' +
                '<small>文件的大小，可选</small>' +
            '</div>' +
            '<div class="form-field">' +
                '<label for="download-format">文件格式:</label>' +
                '<input type="text" id="download-format" placeholder="例如: ZIP, PDF, MP4">' +
                '<small>文件的格式类型，可选</small>' +
            '</div>' +
            '<div class="form-field">' +
                '<label for="download-password">提取密码:</label>' +
                '<input type="text" id="download-password" placeholder="如果需要密码请填写">' +
                '<small>百度网盘等需要提取密码的填写，可选</small>' +
            '</div>' +
            '<div class="form-field">' +
                '<label for="download-description">资源描述:</label>' +
                '<textarea id="download-description" placeholder="简单描述一下这个资源..."></textarea>' +
                '<small>对资源的简单描述，可选</small>' +
            '</div>';
        }

        // 获取样式链接对话框内容
        function getStyledLinkDialogContent() {
            return '<div class="link-dialog-tabs">' +
                '<div class="tab-buttons" style="margin-bottom: 20px; border-bottom: 1px solid #ddd;">' +
                    '<button type="button" class="tab-btn active" data-tab="manual" style="padding: 8px 16px; margin-right: 10px; border: none; background: #0073aa; color: white; border-radius: 4px;">手动输入</button>' +
                    '<button type="button" class="tab-btn" data-tab="search" style="padding: 8px 16px; border: 1px solid #ddd; background: white; color: #333; border-radius: 4px;">搜索文章</button>' +
                '</div>' +
                
                '<div class="tab-content" id="manual-tab">' +
                    '<div class="form-field">' +
                        '<label for="link-text">链接文本: <span style="color:red;">*</span></label>' +
                        '<input type="text" id="link-text" placeholder="输入链接显示的文本">' +
                        '<small>在页面上显示的链接文字</small>' +
                    '</div>' +
                    '<div class="form-field">' +
                        '<label for="link-url">链接地址: <span style="color:red;">*</span></label>' +
                        '<input type="url" id="link-url" placeholder="https://example.com">' +
                        '<small>链接的目标地址</small>' +
                    '</div>' +
                '</div>' +
                
                '<div class="tab-content" id="search-tab" style="display:none;">' +
                    '<div class="form-field">' +
                        '<label for="post-search">搜索文章:</label>' +
                        '<input type="text" id="post-search" placeholder="输入文章标题关键词...">' +
                        '<small>搜索您的历史文章</small>' +
                    '</div>' +
                    '<div class="form-field">' +
                        '<div id="search-results" style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; margin-top: 10px; display: none;">' +
                            '<p>请输入关键词开始搜索...</p>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
                
                '<div class="form-field">' +
                    '<label>' +
                        '<input type="checkbox" id="target-blank" checked> 在新标签页中打开' +
                    '</label>' +
                    '<small>勾选后链接将在新窗口/标签页中打开</small>' +
                '</div>' +
                
                '<div class="form-field">' +
                    '<label for="style-select">选择样式:</label>' +
                    '<select id="style-select">' +
                        '<option value="none">无样式</option>' +
                        '<option value="custom">自定义样式</option>' +
                    '</select>' +
                    '<small>选择预设样式或自定义</small>' +
                '</div>' +
                
                '<div class="form-field" id="custom-css-field" style="display:none;">' +
                    '<label for="custom-css">自定义CSS:</label>' +
                    '<textarea id="custom-css" placeholder="color: #ff6600; background: #f0f0f0; padding: 5px 10px; border-radius: 4px; text-decoration: none;"></textarea>' +
                    '<small>输入CSS样式，如: color: red; background: yellow;</small>' +
                    '<div class="css-actions" style="margin-top: 10px;">' +
                        '<button type="button" id="save-style-btn" class="btn btn-secondary" style="margin-right: 10px;">保存为新样式</button>' +
                        '<button type="button" id="preview-style-btn" class="btn btn-secondary">预览效果</button>' +
                    '</div>' +
                '</div>' +
                
                '<div class="form-field" id="style-management" style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #ddd;">' +
                    '<h4>样式管理</h4>' +
                    '<div id="style-list"></div>' +
                '</div>' +
            '</div>';
        }





        // 生成下载地址HTML
        function generateDownloadHtml(title, url, size, format, password, description) {
            // 使用短代码格式，确保特殊字符正确转义
            var shortcode = '[download';
            shortcode += ' title="' + title.replace(/"/g, '&quot;') + '"';
            shortcode += ' url="' + url.replace(/"/g, '&quot;') + '"';
            
            if (size) {
                shortcode += ' size="' + size.replace(/"/g, '&quot;') + '"';
            }
            if (format) {
                shortcode += ' format="' + format.replace(/"/g, '&quot;') + '"';
            }
            if (password) {
                shortcode += ' password="' + password.replace(/"/g, '&quot;') + '"';
            }
            if (description) {
                shortcode += ' description="' + description.replace(/"/g, '&quot;') + '"';
            }
            
            shortcode += ']';
            return shortcode;
        }

        // 生成样式链接HTML
        function generateStyledLinkHtml(linkText, linkUrl, cssStyle, targetBlank) {
            var escapedText = linkText.replace(/"/g, '&quot;');
            var escapedUrl = linkUrl.replace(/"/g, '&quot;');
            
            var targetAttr = targetBlank ? ' target="_blank" rel="noopener noreferrer"' : '';
            
            if (cssStyle && cssStyle.trim() !== '') {
                var escapedCss = cssStyle.replace(/"/g, '&quot;');
                return '<a href="' + escapedUrl + '"' + targetAttr + ' style="' + escapedCss + '">' + escapedText + '</a>';
            } else {
                return '<a href="' + escapedUrl + '"' + targetAttr + '>' + escapedText + '</a>';
            }
        }

        // 加载链接样式列表
        function loadLinkStyles() {
            if (typeof linkStyleAjax === 'undefined') {
                console.log('AJAX配置未加载');
                return;
            }

            jQuery.post(linkStyleAjax.ajax_url, {
                action: 'get_link_styles'
            }, function(response) {
                if (response.success) {
                    var styles = response.data;
                    var select = document.getElementById('style-select');
                    var styleList = document.getElementById('style-list');
                    
                    // 清空现有选项（保留无样式和自定义选项）
                    while (select.children.length > 2) {
                        select.removeChild(select.lastChild);
                    }
                    
                    // 添加保存的样式到下拉选择
                    for (var styleName in styles) {
                        var option = document.createElement('option');
                        option.value = styles[styleName];
                        option.textContent = styleName;
                        select.appendChild(option);
                    }
                    
                    // 显示样式管理列表
                    styleList.innerHTML = '';
                    for (var styleName in styles) {
                        var styleItem = document.createElement('div');
                        styleItem.className = 'style-item';
                        styleItem.style.cssText = 'margin: 8px 0; padding: 8px; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;';
                        styleItem.innerHTML = '<strong>' + styleName + '</strong><br>' +
                            '<code style="font-size: 12px; color: #666;">' + styles[styleName] + '</code><br>' +
                            '<button type="button" class="delete-style-btn" data-style-name="' + styleName + '" style="margin-top: 5px; color: red; border: none; background: none; cursor: pointer;">删除</button>';
                        styleList.appendChild(styleItem);
                    }
                    
                    // 绑定删除按钮事件
                    jQuery('.delete-style-btn').on('click', function() {
                        var styleName = jQuery(this).data('style-name');
                        deleteStyle(styleName);
                    });
                }
            });
            
            // 绑定下拉选择变化事件
            jQuery('#style-select').on('change', function() {
                var selectedValue = this.value;
                var customField = document.getElementById('custom-css-field');
                var customCss = document.getElementById('custom-css');
                
                if (selectedValue === 'custom') {
                    customField.style.display = 'block';
                    customCss.value = '';
                } else if (selectedValue === 'none') {
                    customField.style.display = 'none';
                } else {
                    customField.style.display = 'block';
                    customCss.value = selectedValue;
                }
            });
            
            // 绑定保存样式按钮
            jQuery('#save-style-btn').on('click', function() {
                var styleName = prompt('请输入样式名称:');
                if (styleName) {
                    var css = document.getElementById('custom-css').value;
                    if (css.trim() === '') {
                        alert('请输入CSS样式');
                        return;
                    }
                    saveStyle(styleName, css);
                }
            });
            
            // 绑定预览按钮
            jQuery('#preview-style-btn').on('click', function() {
                var linkText = document.getElementById('link-text').value || '预览链接';
                var css = document.getElementById('custom-css').value;
                
                if (css.trim() === '') {
                    alert('请输入CSS样式');
                    return;
                }
                
                var previewHtml = '<div style="margin: 10px 0; padding: 10px; border: 1px solid #ccc; background: #f5f5f5;">' +
                    '<strong>预览效果:</strong><br>' +
                    '<a href="#" style="' + css + '" onclick="return false;">' + linkText + '</a>' +
                    '</div>';
                
                var existingPreview = document.getElementById('style-preview');
                if (existingPreview) {
                    existingPreview.remove();
                }
                
                var previewDiv = document.createElement('div');
                previewDiv.id = 'style-preview';
                previewDiv.innerHTML = previewHtml;
                document.getElementById('custom-css-field').appendChild(previewDiv);
            });
        }

        // 保存样式
        function saveStyle(styleName, css) {
            if (typeof linkStyleAjax === 'undefined') {
                alert('AJAX配置未加载');
                return;
            }

            jQuery.post(linkStyleAjax.ajax_url, {
                action: 'save_link_style',
                nonce: linkStyleAjax.nonce,
                style_name: styleName,
                style_css: css
            }, function(response) {
                if (response.success) {
                    alert('样式保存成功！');
                    loadLinkStyles(); // 重新加载样式列表
                } else {
                    alert('保存失败: ' + response.data);
                }
            });
        }

        // 删除样式
        function deleteStyle(styleName) {
            if (!confirm('确定要删除样式 "' + styleName + '" 吗？')) {
                return;
            }

            if (typeof linkStyleAjax === 'undefined') {
                alert('AJAX配置未加载');
                return;
            }

            jQuery.post(linkStyleAjax.ajax_url, {
                action: 'delete_link_style',
                nonce: linkStyleAjax.nonce,
                style_name: styleName
            }, function(response) {
                if (response.success) {
                    alert('样式删除成功！');
                    loadLinkStyles(); // 重新加载样式列表
                } else {
                    alert('删除失败: ' + response.data);
                }
            });
        }

        // 初始化标签页功能
        function initLinkDialogTabs() {
            jQuery('.tab-btn').on('click', function() {
                var targetTab = jQuery(this).data('tab');
                
                // 切换按钮状态
                jQuery('.tab-btn').removeClass('active').css({
                    'background': 'white',
                    'color': '#333',
                    'border': '1px solid #ddd'
                });
                jQuery(this).addClass('active').css({
                    'background': '#0073aa',
                    'color': 'white',
                    'border': 'none'
                });
                
                // 切换内容
                jQuery('.tab-content').hide();
                jQuery('#' + targetTab + '-tab').show();
                
                // 聚焦相应输入框
                if (targetTab === 'manual') {
                    setTimeout(function() {
                        jQuery('#link-text').focus();
                    }, 100);
                } else if (targetTab === 'search') {
                    setTimeout(function() {
                        jQuery('#post-search').focus();
                    }, 100);
                }
            });
        }

        // 初始化文章搜索功能
        function initPostSearch() {
            var searchTimeout;
            
            jQuery('#post-search').on('input', function() {
                var keyword = jQuery(this).val().trim();
                
                clearTimeout(searchTimeout);
                
                if (keyword.length < 2) {
                    jQuery('#search-results').hide();
                    return;
                }
                
                searchTimeout = setTimeout(function() {
                    searchPosts(keyword);
                }, 500);
            });
        }

        // 搜索文章
        function searchPosts(keyword) {
            if (typeof linkStyleAjax === 'undefined') {
                console.log('AJAX配置未加载');
                return;
            }

            var $results = jQuery('#search-results');
            $results.show().html('<p>搜索中...</p>');

            jQuery.post(linkStyleAjax.ajax_url, {
                action: 'search_posts_for_link',
                nonce: linkStyleAjax.nonce,
                keyword: keyword
            }, function(response) {
                if (response.success && response.data.length > 0) {
                    var html = '';
                    jQuery.each(response.data, function(index, post) {
                        html += '<div class="search-result-item" style="padding: 8px; border-bottom: 1px solid #eee; cursor: pointer;" data-url="' + post.url + '" data-title="' + post.title + '">' +
                            '<strong>' + post.title + '</strong><br>' +
                            '<small style="color: #666;">' + post.url + '</small>' +
                            '</div>';
                    });
                    $results.html(html);
                    
                    // 绑定点击事件
                    jQuery('.search-result-item').on('click', function() {
                        var title = jQuery(this).data('title');
                        var url = jQuery(this).data('url');
                        
                        jQuery('#link-text').val(title);
                        jQuery('#link-url').val(url);
                        
                        // 切换回手动输入标签页
                        jQuery('[data-tab="manual"]').click();
                    });
                } else {
                    $results.html('<p style="color: #666;">未找到相关文章</p>');
                }
            }).fail(function() {
                $results.html('<p style="color: red;">搜索失败，请重试</p>');
            });
        }


    });

})();
