jQuery(document).ready(function($) {
    // 处理拼音索引点击事件
    $('.pinyin-index a').on('click', function(e) {
        e.preventDefault();
        var pinyin = $(this).data('pinyin');
        var formData = {
            'action': 'search_character',
            'pinyin': pinyin
        };

        $.post(ajax_object.ajax_url, formData, function(response) {
            if (response.success) {
                $('.characters-list').html(response.data);
            }
        });
    });

    // 处理部首索引点击事件
    $('.radical-index a').on('click', function(e) {
        e.preventDefault();
        var radical = $(this).data('radical');
        var formData = {
            'action': 'get_characters_by_radical',
            'radical': radical
        };

        $.post(ajax_object.ajax_url, formData, function(response) {
            if (response.success) {
                $('.characters-list').html(response.data);
            }
        });
    });

    // 处理书法作品筛选
    $(document).on('click', '.filter-button', function(e) {
        e.preventDefault();
        var filterType = $(this).data('filter');
        var filterValue = $(this).data('value');
        var characterId = $(this).data('character');

        var formData = {
            'action': 'filter_calligraphy',
            'filter_type': filterType,
            'filter_value': filterValue,
            'character_id': characterId
        };

        $.post(ajax_object.ajax_url, formData, function(response) {
            if (response.success) {
                $('.calligraphy-gallery').html(response.data);
            }
        });
    });

    // 处理子分类筛选
    $(document).on('click', '.subcategory-item', function(e) {
        e.preventDefault();
        
        // 更新活动状态
        $('.subcategory-item').removeClass('active');
        $(this).addClass('active');
        
        // 获取分类ID
        var subcategoryId = $(this).data('subcat');
        var categoryId = $('.subcategory-list').data('category');
        
        // 获取搜索关键词
        var searchKeyword = $('.category-search-input').val();
        
        // 更新浏览器历史记录
        if (typeof subcategory_filter_ajax !== 'undefined' && window.history && window.history.pushState) {
            var newUrl = $(this).attr('href');
            window.history.pushState({path: newUrl}, '', newUrl);
        }
        
        // 如果有分页导航，更新其链接
        if (typeof subcategory_filter_ajax !== 'undefined') {
            var formData = {
                'action': 'filter_posts_by_subcategory',
                'category': categoryId,
                'subcategory': subcategoryId,
                'search_keyword': searchKeyword,
                'nonce': subcategory_filter_ajax.nonce
            };

            // 显示加载状态
            var $content = $('.site-main .posts-list, .site-main .post-list, .site-main article').first();
            if ($content.length) {
                $content.addClass('loading').html('<p>加载中...</p>');
            }

            $.post(subcategory_filter_ajax.ajax_url, formData, function(response) {
                if (response.success) {
                    // 更新文章列表
                    if ($content.length) {
                        $content.removeClass('loading').html(response.data.content);
                    }
                } else {
                    if ($content.length) {
                        $content.removeClass('loading').html('<p>加载失败: ' + response.data + '</p>');
                    }
                }
            }).fail(function() {
                if ($content.length) {
                    $content.removeClass('loading').html('<p>加载失败</p>');
                }
            });
        } else {
            // 降级方案：直接跳转到链接
            window.location.href = $(this).attr('href');
        }
    });
    
    // 处理分类搜索表单提交
    $(document).on('submit', '.category-search-form', function(e) {
        e.preventDefault();
        
        var searchKeyword = $('.category-search-input').val();
        var categoryId = $('.subcategory-list').data('category');
        
        if (!searchKeyword.trim()) {
            alert('请输入搜索关键词');
            return;
        }
        
        // 如果没有子分类列表，使用当前页面的分类ID
        if (!categoryId) {
            // 从页面URL中提取分类ID
            var urlParams = new URLSearchParams(window.location.search);
            categoryId = urlParams.get('cat') || 0;
        }
        
        if (typeof subcategory_filter_ajax !== 'undefined') {
            var formData = {
                'action': 'search_posts_in_category',
                'category': categoryId,
                'search_keyword': searchKeyword,
                'nonce': subcategory_filter_ajax.nonce
            };

            // 显示加载状态
            var $content = $('.site-main .posts-list, .site-main .post-list, .site-main article').first();
            if ($content.length) {
                $content.addClass('loading').html('<p>搜索中...</p>');
            }

            $.post(subcategory_filter_ajax.ajax_url, formData, function(response) {
                if (response.success) {
                    // 更新文章列表
                    if ($content.length) {
                        $content.removeClass('loading').html(response.data.content);
                    }
                } else {
                    if ($content.length) {
                        $content.removeClass('loading').html('<p>搜索失败: ' + response.data + '</p>');
                    }
                }
            }).fail(function() {
                if ($content.length) {
                    $content.removeClass('loading').html('<p>搜索失败</p>');
                }
            });
        } else {
            // 降级方案：提交表单
            this.submit();
        }
    });
    
    // 处理浏览器前进/后退按钮
    $(window).on('popstate', function(e) {
        if (window.location.href.indexOf('subcategory=') > -1 || 
            window.location.href.indexOf('/category/') > -1 ||
            window.location.href.indexOf('category_search=') > -1) {
            window.location.reload();
        }
    });
    
    // 处理搜索表单提交
    $('#character-search-form').on('submit', function(e) {
        e.preventDefault();
        var keyword = $('#character-search-input').val();

        if (keyword.length > 0) {
            var formData = {
                'action': 'search_character',
                'keyword': keyword
            };

            $.post(ajax_object.ajax_url, formData, function(response) {
                if (response.success) {
                    $('.characters-list').html(response.data);
                }
            });
        }
    });

    // 处理书法作品的艺术家、朝代、书体筛选
    $('.calligraphy-filter-select').on('change', function() {
        var artist = $('#calligraphy-artist-filter').val();
        var dynasty = $('#calligraphy-dynasty-filter').val();
        var style = $('#calligraphy-style-filter').val();
        var character = $('#calligraphy-character-filter').val();

        var formData = {
            'action': 'filter_calligraphy',
            'artist': artist,
            'dynasty': dynasty,
            'style': style,
            'character': character
        };

        $.post(ajax_object.ajax_url, formData, function(response) {
            if (response.success) {
                $('.calligraphy-gallery').html(response.data);
            }
        });
    });
    
    // 专业搜索页面表单处理
    $('#professional-search-form').on('submit', function(e) {
        // 表单会正常提交，这里可以添加额外的验证或处理
        var searchQuery = $('#professional-search-input').val().trim();
        
        if (searchQuery === '') {
            e.preventDefault();
            return;
        }
    });
    
    // 部首查询功能
    if ($('.radical-item').length > 0) {
        const radicalItems = document.querySelectorAll('.radical-item');
        const radicalContainer = document.querySelector('.radical-index-container');
        const nonce = radicalContainer.getAttribute('data-nonce');
        
        // 为每个部首项添加点击事件
        radicalItems.forEach(item => {
            item.addEventListener('click', function() {
                // 移除所有活动状态
                radicalItems.forEach(i => i.classList.remove('active'));
                
                // 添加当前活动状态
                this.classList.add('active');
                
                // 获取部首字符
                const radical = this.getAttribute('data-radical');
                
                // 找到包含此部首项的笔画组
                const strokeGroup = this.closest('.radical-stroke-group');
                const characterResults = strokeGroup.querySelector('.character-results');
                
                // 显示汉字结果显示区域
                characterResults.style.display = 'block';
                
                // 显示加载状态
                characterResults.innerHTML = '<p class="placeholder-text">加载中...</p>';
                
                // AJAX请求获取包含该部首的汉字
                const ajaxUrl = typeof ajaxurl !== 'undefined' ? ajaxurl : '/wp-admin/admin-ajax.php';
                fetch(ajaxUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'get_characters_by_radical',
                        radical: radical,
                        nonce: nonce
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data.length > 0) {
                        // 按笔画数对汉字进行分组
                        const charactersByStroke = {};
                        data.data.forEach(character => {
                            const strokeCount = character.stroke_count || '未知';
                            if (!charactersByStroke[strokeCount]) {
                                charactersByStroke[strokeCount] = [];
                            }
                            charactersByStroke[strokeCount].push(character);
                        });
                        
                        // 生成按笔画数分组的HTML
                        let html = '<div class="character-stroke-groups">';
                        
                        // 按笔画数排序
                        const sortedStrokes = Object.keys(charactersByStroke).sort((a, b) => {
                            // 将"未知"放在最后
                            if (a === '未知') return 1;
                            if (b === '未知') return -1;
                            return parseInt(a) - parseInt(b);
                        });
                        
                        sortedStrokes.forEach(strokeCount => {
                            html += `<div class="character-stroke-group">
                                        <h3>${strokeCount}画</h3>
                                        <div class="character-list">`;
                            
                            charactersByStroke[strokeCount].forEach(character => {
                                html += `
                                    <div class="character-card">
                                        <a href="${character.permalink}" class="character-link">
                                            <span class="character-char">${character.title}</span>
                                            <span class="character-pinyin">${character.pinyin || '无拼音'}</span>
                                        </a>
                                    </div>
                                `;
                            });
                            
                            html += `</div>
                                </div>`;
                        });
                        
                        html += '</div>';
                        characterResults.innerHTML = html;
                    } else {
                        characterResults.innerHTML = '<p class="placeholder-text">该部首下暂无汉字</p>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    characterResults.innerHTML = '<p class="placeholder-text">加载失败，请重试</p>';
                });
            });
        });
    }
    
    // 处理WordPress默认搜索表单
    $('form.search-form, #searchform').on('submit', function(e) {
        var searchInput = $(this).find('input[name="s"]').val().trim();
        
        // 检查是否是单个汉字
        if (searchInput && searchInput.length === 1 && /^[\u4e00-\u9fa5]$/.test(searchInput)) {
            // 发送AJAX请求检查汉字是否存在
            $.ajax({
                url: character_ajax.ajax_url,
                type: 'POST',
                async: false, // 同步请求以确保重定向前完成检查
                data: {
                    action: 'search_character',
                    character: searchInput
                },
                success: function(response) {
                    if (response.success) {
                        // 如果汉字存在，重定向到该汉字页面
                        var redirectUrl = '/character/' + encodeURIComponent(searchInput);
                        window.location.href = redirectUrl;
                        e.preventDefault(); // 阻止表单提交
                    }
                }
            });
        }
    });
    
    // 切换标签页 - 适用于所有页面
    $(document).on('click', '.tab-link a', function(e) {
        e.preventDefault();
        
        var target = $(this).attr('href');
        var targetElement = $(target);
        
        if (targetElement.length) {
            // 平滑滚动到目标元素
            $('html, body').animate({
                scrollTop: targetElement.offset().top - 60 // 考虑sticky header的高度
            }, 500);
            
            // 更新活动标签样式
            $('.tab-link').removeClass('active');
            $(this).closest('.tab-link').addClass('active');
        }
    });

    // 增强评论功能
    if ($('#enhanced-comment-editor').length > 0) {
        // 显示富文本编辑器
        $('#enhanced-comment-editor').show();
        
        // 隐藏原始评论文本域
        $('#comment').hide();
        
        // 初始化TinyMCE编辑器
        if (typeof tinymce !== 'undefined') {
            tinymce.init({
                selector: '#enhanced_comment',
                plugins: 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media',
                toolbar1: 'bold,italic,underline,strikethrough,blockquote,bullist,numlist,alignleft,aligncenter,alignright,link,unlink,undo,redo,table',
                toolbar2: 'formatselect,forecolor,pastetext,removeformat,charmap,outdent,indent,help',
                menubar: false,
                statusbar: false,
                height: 150,
                setup: function(editor) {
                    editor.on('change keyup', function() {
                        // 同步内容到隐藏的textarea
                        $('#comment').val(editor.getContent());
                        
                        // 更新预览
                        $('.comment-preview').html(editor.getContent());
                    });
                }
            });
        }
        
        // 同步编辑器内容到预览区域
        $('#enhanced_comment').on('keyup', function() {
            $('.comment-preview').html($(this).val());
        });
    }
    
    // 显示字符信息
    function displayCharacterInfo(data) {
        // 基本信息
        $('#character-title').text(data.title || '');
        $('#character-pinyin').text(data.pinyin || '无');
        $('#character-radical').text(data.radical || '无');
        $('#character-stroke-count').text(data.stroke_count || '无');
        $('#character-traditional-form').text(data.tradical_form || '无');
        $('#character-variants').text(data.variants || '无');
        
        // 内容区域处理
        if (data.content && data.content.trim() !== '') {
            $('#character-content').html(data.content);
        } else {
            $('#character-content').html('<p class="no-content">暂无内容</p>');
        }
        
        // 各个解释部分
        const explanations = [
            'detailed_explanation',
            'guoyu_dictionary', 
            'kangxi_dictionary',
            'shuowen_jiezi',
            'dialects',
            'etymology',
            'other_meanings'
        ];
        
        explanations.forEach(section => {
            const $element = $(`#character-${section.replace('_', '-')}`);
            if (data[section] && data[section].trim() !== '') {
                $element.html(data[section]);
            } else {
                $element.html('<p class="no-content">暂无内容</p>');
            }
        });
        
        // 默认显示第一个标签页为活动状态
        $('.tab-link').removeClass('active');
        $('.tab-link:first').addClass('active');
    }
    
    // 页面加载完成后初始化标签页（针对直接访问汉字页面的情况）
    if ($('.tab-pane').length > 0) {
        // 默认显示第一个标签页为活动状态
        $('.tab-link:first').addClass('active');
        
        // 检查URL hash，如果有则滚动到对应位置
        if (window.location.hash) {
            var targetElement = $(window.location.hash);
            if (targetElement.length) {
                // 延迟执行以确保页面完全加载
                setTimeout(function() {
                    $('html, body').animate({
                        scrollTop: targetElement.offset().top - 60
                    }, 500);
                    
                    // 更新活动标签样式
                    $('.tab-link').removeClass('active');
                    $('.tab-link a[href="' + window.location.hash + '"]').closest('.tab-link').addClass('active');
                }, 100);
            }
        }
    }
    
    // 添加拼音索引链接到归档页面
    if ($('.chinese-character-archive-header').length > 0) {
        $('.chinese-character-archive-header').append(
            '<p class="pinyin-index-link"><a href="' + character_ajax.site_url + '/pinyin-index">查看拼音索引</a></p>'
        );
    }
    
    // 全屏查看器功能
    const lightbox = document.querySelector('.gallery-lightbox');
    const lightboxImage = lightbox.querySelector('.lightbox-image');
    const lightboxTitle = lightbox.querySelector('.lightbox-title');
    const lightboxClose = lightbox.querySelector('.lightbox-close');
    const lightboxPrev = lightbox.querySelector('.lightbox-prev');
    const lightboxNext = lightbox.querySelector('.lightbox-next');
    const lightboxZoom = lightbox.querySelector('.lightbox-zoom');
    const lightboxReset = lightbox.querySelector('.lightbox-reset');
    
    let currentGallery = null;
    let currentIndex = 0;
    let scale = 1;
    let currentCaption = ''; // 添加说明文字变量
    
    // 打开全屏查看器
    function openLightbox(gallery, index) {
        currentGallery = gallery;
        currentIndex = index;
        scale = 1;
        
        const slides = gallery.querySelectorAll('.gallery-slide');
        const slide = slides[index];
        const img = slide.querySelector('img');
        const caption = slide.querySelector('.gallery-caption');
        
        lightboxImage.src = img.src;
        lightboxImage.style.transform = 'scale(1)';
        
        // 设置说明文字
        currentCaption = caption ? caption.textContent : '';
        lightboxTitle.textContent = currentCaption;
        
        lightbox.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }
    
    // 关闭全屏查看器
    function closeLightbox() {
        lightbox.style.display = 'none';
        document.body.style.overflow = 'auto';
        lightboxImage.style.transform = 'scale(1)';
        scale = 1;
    }
    
    // 切换到指定图片
    function goToSlide(index) {
        currentIndex = index;
        const slides = currentGallery.querySelectorAll('.gallery-slide');
        const slide = slides[index];
        const img = slide.querySelector('img');
        const caption = slide.querySelector('.gallery-caption');
        
        lightboxImage.src = img.src;
        
        // 设置说明文字
        currentCaption = caption ? caption.textContent : '';
        lightboxTitle.textContent = currentCaption;
    }
    
    // 放大图片
    function zoomImage() {
        scale += 0.5;
        lightboxImage.style.transform = `scale(${scale})`;
    }
    
    // 重置图片大小
    function resetImage() {
        scale = 1;
        lightboxImage.style.transform = 'scale(1)';
    }
    
    // 绑定全屏查看器事件
    if (lightboxClose) {
        lightboxClose.addEventListener('click', closeLightbox);
    }
    
    if (lightboxPrev) {
        lightboxPrev.addEventListener('click', () => {
            if (currentGallery) {
                const slides = currentGallery.querySelectorAll('.gallery-slide');
                currentIndex = (currentIndex - 1 + slides.length) % slides.length;
                goToSlide(currentIndex);
            }
        });
    }
    
    if (lightboxNext) {
        lightboxNext.addEventListener('click', () => {
            if (currentGallery) {
                const slides = currentGallery.querySelectorAll('.gallery-slide');
                currentIndex = (currentIndex + 1) % slides.length;
                goToSlide(currentIndex);
            }
        });
    }
    
    if (lightboxZoom) {
        lightboxZoom.addEventListener('click', zoomImage);
    }
    
    if (lightboxReset) {
        lightboxReset.addEventListener('click', resetImage);
    }
    
    // 点击背景关闭查看器
    lightbox.addEventListener('click', (e) => {
        if (e.target === lightbox) {
            closeLightbox();
        }
    });
    
    // 键盘事件
    document.addEventListener('keydown', (e) => {
        if (lightbox.style.display === 'block') {
            switch (e.key) {
                case 'Escape':
                    closeLightbox();
                    break;
                case 'ArrowLeft':
                    if (lightboxPrev) lightboxPrev.click();
                    break;
                case 'ArrowRight':
                    if (lightboxNext) lightboxNext.click();
                    break;
                case '+':
                case '=':
                    if (lightboxZoom) lightboxZoom.click();
                    break;
                case '-':
                    // 缩小功能
                    if (scale > 0.5) {
                        scale -= 0.5;
                        lightboxImage.style.transform = `scale(${scale})`;
                    }
                    break;
                case '0':
                    if (lightboxReset) lightboxReset.click();
                    break;
            }
        }
    });

});
