/*
// 功能：文章详情脚本文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。
*/

// 确保PHP在页面加载时定义了全局变量 DEFAULT_AVATAR_PATH 和 DEFAULT_THUMBNAIL_PATH
// 如果全局变量未定义，提供一个默认值作为后备方案
if (typeof window.DEFAULT_AVATAR_PATH === 'undefined') {
    window.DEFAULT_AVATAR_PATH = '/assets/images/avatar.png';
}

if (typeof window.DEFAULT_THUMBNAIL_PATH === 'undefined') {
    window.DEFAULT_THUMBNAIL_PATH = '/assets/images/moren.jpg';
}

// 用户状态变量 - 由PHP动态注入
window.addEventListener('DOMContentLoaded', function () {
    // 初始化变量
    const isUserBanned = window.isUserBanned || false;
    const isLoggedIn = window.isLoggedIn || false;
    const postId = window.postId || 0;
    const postApiEndpoint = (function () {
        let url = window.location.href || '';
        if (!url) return '/post.php';
        url = url.split('#')[0];
        return url;
    })();

    // 全局变量
    let currentReplyInfo = {
        parentId: 0,
        replyTo: ''
    };

    // 辅助函数：安全地获取元素
    function safeGetElement(id) {
        const element = document.getElementById(id);
        return element;
    }

    // 辅助函数：记录操作结果
    function logOperationResult(operation, success, data = {}) { }

    // 辅助函数：更新元素中的点赞数
    function updateLikesInElement(element, count) {
        if (!element) return;

        const countBadge = element.querySelector('.count-badge');
        const likeCountElement = element.querySelector('.like-count');
        const spanElement = element.querySelector('span:not(.icon)');

        if (countBadge) countBadge.textContent = count;
        if (likeCountElement) likeCountElement.textContent = count;
        if (spanElement && !spanElement.classList.contains('icon')) spanElement.textContent = count;

        if (element.classList.contains('like-count')) element.textContent = count;
    }

    // DOM元素
    const commentModal = document.getElementById('comment-modal');
    const modalCommentInput = document.getElementById('modal-comment-input');
    const closeCommentModalBtn = document.getElementById('close-comment-modal');
    const submitModalCommentBtn = document.getElementById('submit-modal-comment');
    const reportModal = document.getElementById('report-modal');
    const closeReportModalBtn = document.getElementById('close-report-modal');
    const reportForm = document.getElementById('report-form');
    const reportType = document.getElementById('report-type');
    const reportId = document.getElementById('report-id');
    const submitReportBtn = document.getElementById('submitReport');
    const commentSubmit = document.getElementById('comment-submit');
    const commentInput = document.getElementById('comment-input');
    (function () {
        function mark(selector, action) {
            document.querySelectorAll(selector).forEach(function (el) {
                if (el.getAttribute('data-require-login') !== '1') el.setAttribute('data-require-login', '1');
                if (action && !el.getAttribute('data-login-action')) el.setAttribute('data-login-action', action);
            });
        }
        mark('.vertical-action-btn.like-button, .like-button', 'like');
        mark('.vertical-action-btn.report-button, .report-button', 'report');
        mark('.vertical-action-btn.share-button, .share-button', 'share');
        mark('.buy-post-btn', 'buy');
        mark('#comment-submit, #submitReport, #submit-modal-comment', 'comment');
        mark('.comment-reply', 'reply');
        mark('.comment-delete, .reply-delete', 'comment');
    })();

    // 用户状态检查
    function checkUserBanStatus() {
        if (isUserBanned) {
            showToast('您的账户已被封禁', { type: 'error' });
            return true;
        }
        return false;
    }

    function checkUserStatus(actionName = '进行此操作') {
        function getIsLoggedIn() {
            try {
                if (window.LoginSync) {
                    if (typeof window.LoginSync.checkLogout === 'function') window.LoginSync.checkLogout();
                    if (typeof window.LoginSync.checkLogin === 'function') window.LoginSync.checkLogin();
                    return !!window.LoginSync.isLoggedIn;
                }
            } catch (e) { }
            try {
                if (localStorage.getItem('qkcms_user_logged_out') === 'true') return false;
                return localStorage.getItem('qkcms_logged_in') === 'true';
            } catch (e) { }
            return false;
        }
        
        if (!getIsLoggedIn()) {
            showToast('请先登录后再' + actionName, { type: 'error' });
            return false;
        }
        if (checkUserBanStatus()) return false;
        return true;
    }

    // 事件绑定
    function bindCommentEvents() {
        document.addEventListener('click', function (e) {
            // 回复事件
            const replyBtn = e.target.closest('.comment-reply');
            if (replyBtn) {
                e.stopPropagation();
                const commentId = replyBtn.getAttribute('data-id');
                const replyTo = replyBtn.getAttribute('data-username');
                if (commentId && replyTo) showReplyModal(commentId, replyTo);
                return;
            }

            // 删除事件
            const deleteBtn = e.target.closest('.comment-delete, .reply-delete');
            if (deleteBtn) {
                e.stopPropagation();
                if (!checkUserStatus('删除评论')) return;

                const id = deleteBtn.getAttribute('data-id');
                const isReplyDelete = deleteBtn.classList.contains('reply-delete');

                try {
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', postApiEndpoint, true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                if (response.success) {
                                    showToast('删除成功', { type: 'success' });
                                    let itemToRemove = isReplyDelete ?
                                        deleteBtn.closest('.comment-reply-item') :
                                        deleteBtn.closest('.topic-item');

                                    if (itemToRemove) {
                                        itemToRemove.style.height = itemToRemove.offsetHeight + 'px';
                                        setTimeout(() => {
                                            itemToRemove.style.height = '0';
                                            itemToRemove.style.opacity = '0';
                                            itemToRemove.style.overflow = 'hidden';
                                            itemToRemove.style.transition = 'all 0.3s ease';

                                            setTimeout(() => {
                                                itemToRemove.remove();
                                                updateCommentCount(response.deleted_count || 1);
                                            }, 300);
                                        }, 10);
                                    }
                                } else {
                                    const errorMsg = response.message || '删除失败，未知错误';
                                    if (!errorMsg.includes('评论不存在')) showToast(errorMsg, { type: 'error' });
                                }
                            } catch (parseError) {
                                showToast('操作失败，请稍后重试', { type: 'error' });
                            }
                        }
                    };
                    xhr.send('action=delete_comment&comment_id=' + encodeURIComponent(id));
                } catch (reqError) {
                    showToast('网络错误，请稍后重试', { type: 'error' });
                }
            }

            // 举报事件
            const reportBtn = e.target.closest('.comment-report');
            if (reportBtn) {
                e.stopPropagation();
                if (!checkUserStatus('举报内容')) return;

                const type = reportBtn.getAttribute('data-type');
                const id = reportBtn.getAttribute('data-id');

                if (reportType && reportId) {
                    reportType.value = type;
                    reportId.value = id;
                    const reasonInput = safeGetElement('report-reason');
                    if (reasonInput) reasonInput.value = '';
                    reportModal.classList.add('modal-visible');
                    document.body.classList.add('modal-open');
                }
            }
        });
    }

    function setupGlobalEventListeners() {
        document.addEventListener('click', function (e) {
            // 点赞功能
            const likeButton = e.target.closest('.like-button, .comment-like, .reply-like');
            if (likeButton) {
                e.preventDefault();
                e.stopPropagation();
                if (!checkUserStatus('点赞')) return;

                const type = likeButton.getAttribute('data-type');
                const id = likeButton.getAttribute('data-id');
                if (!type || !id) return;

                try {
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', postApiEndpoint, true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                if (response.success) {
                                    showToast(response.action === 'like' ? '点赞成功' : '已取消点赞', { type: 'success' });

                                    const likeIcon = likeButton.querySelector('svg, .icon');
                                    likeButton.dataset.liked = response.action === 'like';

                                    if (response.action === 'like') {
                                        likeButton.classList.add('liked');
                                        if (likeIcon) likeIcon.classList.add('liked');
                                    } else {
                                        likeButton.classList.remove('liked');
                                        if (likeIcon) likeIcon.classList.remove('liked');
                                    }

                                    if (response.likes_count !== undefined) {
                                        logOperationResult('点赞', true, {
                                            action: response.action,
                                            count: response.likes_count,
                                            type: type,
                                            id: id
                                        });

                                        updateLikesInElement(likeButton, response.likes_count);

                                        const contentType = type;
                                        const contentId = id;
                                        const allLikeElements = document.querySelectorAll(`
                                            .like-button[data-type="${contentType}"][data-id="${contentId}"],
                                            .comment-like[data-type="${contentType}"][data-id="${contentId}"],
                                            .reply-like[data-type="${contentType}"][data-id="${contentId}"],
                                            [data-id="${contentId}"].like-count,
                                            [data-id="${contentId}"] .like-count,
                                            .comment-stat[data-id="${contentId}"] .like-count
                                        `);

                                        allLikeElements.forEach(element => {
                                            if (element === likeButton) return;

                                            if (element.classList.contains('like-count')) {
                                                element.textContent = response.likes_count;
                                            } else {
                                                const badge = element.querySelector('.count-badge');
                                                const count = element.querySelector('.like-count');
                                                const span = element.querySelector('span:not(.icon)');

                                                if (badge) badge.textContent = response.likes_count;
                                                if (count) count.textContent = response.likes_count;
                                                if (span) span.textContent = response.likes_count;
                                            }
                                        });
                                    }
                                } else showToast(response.message || '操作失败', { type: 'error' });
                            } catch (parseError) {
                                showToast('操作失败，请稍后重试', { type: 'error' });
                            }
                        }
                    };
                    xhr.send('action=toggle_like&content_type=' + encodeURIComponent(type) + '&content_id=' + encodeURIComponent(id));
                } catch (reqError) {
                    showToast('网络错误，请稍后重试', { type: 'error' });
                }
            }

            // 左侧举报按钮
            const reportButton = e.target.closest('.report-button');
            if (reportButton) {
                e.preventDefault();
                e.stopPropagation();
                if (!checkUserStatus('举报')) return;

                const type = reportButton.getAttribute('data-type');
                const id = reportButton.getAttribute('data-id');
                if (!type || !id || !reportModal || !reportType || !reportId) return;

                reportType.value = type;
                reportId.value = id;
                const reasonInput = safeGetElement('report-reason');
                if (reasonInput) reasonInput.value = '';
                reportModal.classList.add('modal-visible');
                document.body.classList.add('modal-open');
            }
        });

        // 分享功能
        const shareButtons = document.querySelectorAll('.share-button');
        if (shareButtons.length > 0) {
            shareButtons.forEach(button => {
                button.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (!checkUserStatus('分享')) return;

                    const url = window.location.href;
                    const postId = window.postId;

                    const copyText = () => {
                        if (navigator.clipboard && window.isSecureContext) {
                            return navigator.clipboard.writeText(url);
                        } else {
                            return new Promise((resolve, reject) => {
                                const textArea = document.createElement('textarea');
                                textArea.value = url;
                                textArea.style.position = 'fixed';
                                textArea.style.left = '-999999px';
                                textArea.style.top = '-999999px';
                                document.body.appendChild(textArea);
                                textArea.focus();
                                textArea.select();

                                try {
                                    document.execCommand('copy');
                                    document.body.removeChild(textArea);
                                    resolve();
                                } catch (err) {
                                    document.body.removeChild(textArea);
                                    reject(err);
                                }
                            });
                        }
                    };

                    copyText().then(() => {
                        showToast('链接已复制到剪贴板！', { type: 'info' });
                        sendShareRequest(postId, button);
                    }).catch(err => showToast('复制失败，请手动复制链接', { type: 'error' }));
                });
            });
        }
    }

    function sendShareRequest(postId, button) {
        try {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', postApiEndpoint, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success && response.share_count !== undefined) {
                            const countBadge = button.querySelector('.count-badge');
                            if (countBadge) countBadge.textContent = response.share_count;
                        }
                    } catch (e) { }
                }
            };
            xhr.send('action=share&content_type=post&content_id=' + postId);
        } catch (e) { }
    }

    function updateCommentCount(decrementCount) {
        const commentCountElement = document.querySelector("h2.topics-title");
        const commentButtonBadge = document.querySelector('.comment-button .count-badge');

        if (commentCountElement) {
            let currentCount = commentCountElement.textContent.match(/\d+/);
            if (currentCount && currentCount[0]) {
                currentCount = parseInt(currentCount[0]) - decrementCount;
                currentCount = Math.max(0, currentCount);
                commentCountElement.textContent = commentCountElement.textContent.replace(/\d+/, currentCount);
            }
        }

        if (commentButtonBadge) {
            let badgeCount = parseInt(commentButtonBadge.textContent) || 0;
            badgeCount = Math.max(0, badgeCount - decrementCount);
            commentButtonBadge.textContent = badgeCount;
        }
    }

    // 模态框功能
    window.showCommentModal = function () {
        currentReplyInfo.parentId = 0;
        currentReplyInfo.replyTo = '';
        if (!checkUserStatus('发表评论')) return;

        if (modalCommentInput) {
            modalCommentInput.value = '';
            modalCommentInput.placeholder = '写下你的评论...';
        }

        if (commentModal) {
            const modalTitle = commentModal.querySelector('.modal-title');
            if (modalTitle) modalTitle.textContent = '评论';

            const repliedCommentContainer = commentModal.querySelector('.replied-comment-container');
            if (repliedCommentContainer) {
                repliedCommentContainer.style.display = 'none';
                repliedCommentContainer.style.visibility = 'hidden';
                repliedCommentContainer.style.height = '0';
                repliedCommentContainer.style.padding = '0';
                repliedCommentContainer.style.margin = '0';
                repliedCommentContainer.style.overflow = 'hidden';

                const commentText = repliedCommentContainer.querySelector('.replied-comment-text');
                if (commentText) commentText.textContent = '';
            }

            window.modalScrollPosition = window.scrollY;
            commentModal.style.display = 'flex';
            commentModal.classList.add('modal-visible');
            document.body.classList.add('modal-open');
            if (modalCommentInput) modalCommentInput.focus();
        }
    };

    window.showReplyModal = function (commentId, replyTo) {
        currentReplyInfo.parentId = commentId;
        currentReplyInfo.replyTo = replyTo;
        if (!checkUserStatus('回复评论')) return;

        let repliedCommentContent = '[评论内容]';
        let commentItem = null;

        const replyButton = document.querySelector(`.comment-reply[data-id="${commentId}"]`);
        if (replyButton) commentItem = replyButton.closest('.topic-item');

        if (!commentItem) commentItem = document.querySelector(`.topic-item[data-id="${commentId}"]`);

        if (!commentItem) {
            const allReplyItems = document.querySelectorAll('.comment-reply-item');
            for (let item of allReplyItems) {
                const likeButton = item.querySelector(`.reply-like[data-id="${commentId}"]`);
                if (likeButton) {
                    commentItem = item;
                    break;
                }
            }
        }

        if (commentItem) {
            if (commentItem.classList.contains('topic-item')) {
                const contentElement = commentItem.querySelector('.post01');
                if (contentElement && contentElement.textContent.trim()) repliedCommentContent = contentElement.textContent.trim();
            } else if (commentItem.classList.contains('comment-reply-item')) {
                const contentElement = commentItem.querySelector('.reply-body');
                if (contentElement) {
                    const pTag = contentElement.querySelector('p');
                    if (pTag && pTag.textContent.trim()) repliedCommentContent = pTag.textContent.trim();
                    else if (contentElement.textContent.trim()) repliedCommentContent = contentElement.textContent.trim();
                }
            }

            if (repliedCommentContent.length > 160) repliedCommentContent = repliedCommentContent.substring(0, 160) + '...';
        }

        if (modalCommentInput) {
            modalCommentInput.value = '';
            modalCommentInput.placeholder = '回复 @' + replyTo + '...';
        }

        if (commentModal) {
            const modalTitle = commentModal.querySelector('.modal-title');
            if (modalTitle) modalTitle.textContent = '回复 @' + replyTo;

            let repliedCommentContainer = commentModal.querySelector('.replied-comment-container');
            if (repliedCommentContainer) {
                const commentText = repliedCommentContainer.querySelector('.replied-comment-text');
                if (commentText) commentText.textContent = repliedCommentContent || '[评论内容]';

                repliedCommentContainer.classList.add('show');
                repliedCommentContainer.classList.remove('hidden');
            }

            window.modalScrollPosition = window.scrollY;
            commentModal.style.display = 'flex';
            commentModal.classList.add('modal-visible');
            document.body.classList.add('modal-open');
            if (modalCommentInput) modalCommentInput.focus();
        }
    };

    window.closeCommentModal = function () {
        if (!commentModal) return;
        commentModal.classList.remove('modal-visible');

        const repliedCommentContainer = commentModal.querySelector('.replied-comment-container');
        if (repliedCommentContainer) {
            repliedCommentContainer.classList.add('hidden');
            repliedCommentContainer.classList.remove('show');
            const commentText = repliedCommentContainer.querySelector('.replied-comment-text');
            if (commentText) commentText.textContent = '';
        }
        setTimeout(() => {
            commentModal.style.display = 'none';
            document.body.classList.remove('modal-open');
            if (window.modalScrollPosition !== undefined) {
                window.scrollTo(0, window.modalScrollPosition);
                delete window.modalScrollPosition;
            }
        }, 300);
    };

    window.submitModalComment = function () {
        const actionName = currentReplyInfo.parentId > 0 ? '回复评论' : '发表评论';
        if (!checkUserStatus(actionName)) return;

        const content = modalCommentInput ? modalCommentInput.value.trim() : '';
        const hasContentOrImages = content && (content.trim() !== '' || /<img[^>]*>/i.test(content));
        if (!hasContentOrImages) {
            window.showToast('请填写评论内容', { type: 'error', duration: 1500 });
            return;
        }

        if (typeof window.validateCommentContent === 'function') {
            const containsImages = /<img[^>]*>/i.test(content);
            let imageName = '图片';
            if (containsImages) {
                const match = content.match(/src=["']([^"']+)["']/i);
                if (match && match[1]) {
                    const path = match[1];
                    imageName = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.')) || '图片';
                }
            }

            let plainContent = content.replace(/<[^>]*>/g, '').trim();
            if (!plainContent && containsImages) plainContent = '[图片评论：' + imageName + ']';

            if (!window.validateCommentContent(plainContent)) {
                const errorMsg = window.validationError || '内容验证失败';
                window.showToast(errorMsg, { type: 'error', duration: 1500 });
                return;
            }
        }

        try {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', postApiEndpoint, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {

                            // 1. 关闭弹窗
                            closeCommentModal();
                            currentReplyInfo.parentId = 0;
                            currentReplyInfo.replyTo = '';

                            // 2. 显示成功提示
                            window.showToast(response.message, {
                                type: 'success',
                                autoHide: true,
                                duration: 1000
                            });

                            // 3. 延迟刷新页面，确保提示能被用户看到
                            setTimeout(function () {
                                location.reload();
                            }, 1200);
                        } else {
                            window.showToast(response.message || '操作失败', { type: 'error' });
                        }
                    } catch (parseError) {
                        console.error('Parse error:', parseError);
                        window.showToast('操作失败，请稍后重试', { type: 'error' });
                    }
                }
            };

            let params = 'action=submit_comment&post_id=' + postId + '&content=' + encodeURIComponent(content);
            if (currentReplyInfo.parentId > 0) {
                params += '&parent_id=' + currentReplyInfo.parentId;
                if (currentReplyInfo.replyTo) params += '&reply_to=' + encodeURIComponent(currentReplyInfo.replyTo);
            }

            xhr.send(params);
        } catch (reqError) {
            console.error('Request error:', reqError);
            showToast('网络错误，请稍后重试', { type: 'error' });
        }
    };

    window.closeReportModal = function () {
        if (!reportModal) return;
        reportModal.classList.remove('modal-visible');
        setTimeout(() => {
            document.body.classList.remove('modal-open');
            if (reportForm) reportForm.reset();
            if (reportType) reportType.value = '';
            if (reportId) reportId.value = '';
            const reasonInput = document.getElementById('report-reason');
            if (reasonInput) reasonInput.value = '';
        }, 300);
    };

    window.submitReportForm = function () {
        const reasonInput = safeGetElement('report-reason');
        if (!reasonInput) {
            showToast('页面元素未加载完成，请刷新重试', { type: 'error' });
            return;
        }

        const reason = reasonInput.value.trim();
        if (!reason) {
            showToast('请填写举报原因', { type: 'error' });
            return;
        }

        try {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', postApiEndpoint, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            showToast(response.message, {
                                type: 'success',
                                autoHide: false,
                                callback: function () {
                                    closeReportModal();
                                }
                            });

                            if (response.report_count !== undefined && reportType && reportId) {
                                const contentType = reportType.value;
                                const contentId = reportId.value;

                                logOperationResult('举报', true, {
                                    type: contentType,
                                    id: contentId,
                                    count: response.report_count
                                });

                                updateAllReportCounters(contentType, contentId, response.report_count);
                            }
                        } else showToast(response.message || '举报提交失败', { type: 'error' });
                    } catch (e) {
                        showToast('举报提交失败', { type: 'error' });
                    }
                }
            };

            const params = 'action=report&content_type=' + encodeURIComponent(reportType.value) +
                '&content_id=' + encodeURIComponent(reportId.value) +
                '&reason=' + encodeURIComponent(reason);
            xhr.send(params);
        } catch (e) {
            showToast('举报提交失败，请稍后重试', { type: 'error' });
        }
    };

    // 辅助函数：更新所有举报计数器
    function updateAllReportCounters(type, id, count) {
        const allReportElements = document.querySelectorAll(`
            [data-id="${id}"],
            .comment-report[data-id="${id}"],
            .report-button[data-id="${id}"],
            .comment-stat[data-id="${id}"],
            [data-id="${id}"].report-count,
            [data-id="${id}"] .report-count,
            .report-count[data-id="${id}"]
        `);

        allReportElements.forEach(element => {
            if (element.classList.contains('report-count')) {
                element.textContent = `${count}`;
                return;
            }

            const counters = element.querySelectorAll('.report-count, .count-badge, span:not(.icon)');
            counters.forEach(counter => {
                if (!counter.classList.contains('icon')) {
                    if (counter.classList.contains('count-badge')) counter.textContent = count;
                    else if (counter.classList.contains('report-count')) counter.textContent = `${count}`;
                    else if (counter.tagName === 'SPAN' && !counter.classList.contains('icon')) {
                        const currentText = counter.textContent.trim();
                        if (/^\d+$/.test(currentText) || currentText.includes('举报')) counter.textContent = `${count}`;
                    }
                }
            });
        });

        const globalCounters = document.querySelectorAll('.report-count');
        globalCounters.forEach(counter => {
            const parent = counter.closest(`[data-id="${id}"]`);
            const grandparent = parent ? parent.closest(`[data-id="${id}"]`) : null;
            if (parent || grandparent) counter.textContent = `${count}`;
        });

        const statElements = document.querySelectorAll('.comment-stat, .comment-stats');
        statElements.forEach(stat => {
            if (stat.getAttribute('data-id') === id) {
                const reportCounter = stat.querySelector('.report-count');
                if (reportCounter) reportCounter.textContent = `${count}`;
            }
        });
    }

    function rebindCommentEvents() {
        bindCommentEvents();
    }

    // 初始化
    bindCommentEvents();
    setupGlobalEventListeners();

    // 评论提交事件
    if (commentSubmit && commentInput) {
        commentSubmit.addEventListener('click', function () {
            if (!checkUserStatus('发表评论')) return;

            const content = commentInput.value.trim();
            const hasContentOrImages = content && (content.trim() !== '' || /<img[^>]*>/i.test(content));
            if (!hasContentOrImages) {
                showToast('请填写评论内容', { type: 'error' });
                return;
            }

            currentReplyInfo.parentId = 0;
            currentReplyInfo.replyTo = '';

            if (modalCommentInput) modalCommentInput.value = content;
            window.submitModalComment();
            commentInput.value = '';
        });
    }

    // 模态框关闭事件
    /* 调试日志已移除
    console.log('Checking modal elements:', {
        closeCommentModalBtn: closeCommentModalBtn,
        submitModalCommentBtn: submitModalCommentBtn
    });
    */
    if (closeCommentModalBtn) {
        closeCommentModalBtn.addEventListener('click', closeCommentModal);
    }
    if (submitModalCommentBtn) {
        submitModalCommentBtn.addEventListener('click', function () {
            if (typeof window.submitModalComment === 'function') {
                window.submitModalComment();
            } else {
                console.error('window.submitModalComment is not a function');
            }
        });
    }



    // ESC键关闭模态框
    window.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            if (commentModal && commentModal.classList.contains('modal-visible')) closeCommentModal();
            if (reportModal && reportModal.classList.contains('modal-visible')) closeReportModal();
        }
    });
});

// ===== 举报功能模块 =====
let currentReportData = null;

function openReportModal(type, id) {
    if (!window.isLoggedIn) {
        window.showToast('请先登录后再举报', 'error');
        return;
    }
    if (window.isUserBanned) {
        window.showToast('您的账号已被封禁', 'error');
        return;
    }

    currentReportData = { type, id };
    document.getElementById('report-type').value = type;
    document.getElementById('report-id').value = id;
    document.getElementById('report-modal').classList.add('active');
    document.getElementById('report-reason').focus();
}

function closeReportModal() {
    document.getElementById('report-modal').classList.remove('active');
    document.getElementById('report-form').reset();
    currentReportData = null;
}

function submitReportForm() {
    const reason = document.getElementById('report-reason').value.trim();
    if (!reason) {
        window.showToast('请填写举报原因', 'error');
        return;
    }

    const submitBtn = document.getElementById('submitReport');
    const originalText = submitBtn.textContent;
    submitBtn.textContent = '提交中...';
    submitBtn.disabled = true;

    fetch(window.location.href.split('#')[0], {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=report&content_type=${currentReportData.type}&content_id=${currentReportData.id}&reason=${encodeURIComponent(reason)}`
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.showToast('举报提交成功', 'success');
                closeReportModal();

                const reportBtn = document.querySelector(`[data-type="${currentReportData.type}"][data-id="${currentReportData.id}"]`);
                if (reportBtn) {
                    const countSpan = reportBtn.querySelector('span:last-child');
                    if (countSpan) countSpan.textContent = data.report_count || 0;
                }
            } else window.showToast(data.message || '举报提交失败', 'error');
        })
        .catch(error => {
            window.showToast('网络错误，请稍后重试', 'error');
        })
        .finally(() => {
            submitBtn.textContent = originalText;
            submitBtn.disabled = false;
        });
}

// ===== 评论功能模块 =====
function showCommentModal() {
    document.getElementById('comment-modal').classList.add('active');
    document.getElementById('modal-comment-input').focus();
}

function closeCommentModal() {
    document.getElementById('comment-modal').classList.remove('active');
    document.getElementById('modal-comment-input').value = '';

    const repliedContainer = document.querySelector('.replied-comment-container');
    repliedContainer.classList.add('hidden');
    repliedContainer.querySelector('.replied-comment-text').textContent = '';
}

// ===== 内容验证模块 =====
window.validateCommentContent = function (text) {
    if (!text || text.trim() === '') {
        window.validationError = '内容不能为空';
        return false;
    }

    if (/^\d+$/.test(text.trim())) {
        window.validationError = '不允许纯数字';
        return false;
    }

    if (/^[a-zA-Z\s]+$/.test(text.trim())) {
        window.validationError = '不允许纯英文';
        return false;
    }

    const forbiddenWords = [
        '广告', '推广', '促销', 'spam', '垃圾', '营销',
        'qq.com', 'qq群', '微信群', '联系方式', '电话', '手机号',
        '138', '139', '137', '136', '135', '134', '133', '159', '158', '157',
        '博彩', '赌博', '色情', '暴力', '违法', '诈骗',
        '买', '卖', '交易', '价格', '费用', '元', '钱'
    ];

    const lowercaseText = text.toLowerCase();
    for (const word of forbiddenWords) {
        if (lowercaseText.includes(word.toLowerCase())) {
            window.validationError = '包含违禁内容';
            return false;
        }
    }

    if (!text.trim().startsWith('[图片评论：') && text.trim() !== '[图片内容]' && text.trim().length < 5) {
        window.validationError = '内容过短';
        return false;
    }

    if (/([^\x00-\xff])\1{5,}/.test(text) || /(.{1,2})\1{5,}/.test(text)) {
        window.validationError = '重复内容过多';
        return false;
    }

    window.validationError = null;
    return true;
}

// ===== 富文本框功能模块 =====
document.addEventListener('DOMContentLoaded', function () {
    const editorMount = document.getElementById('comment-quill-editor');
    if (!editorMount || typeof Quill === 'undefined') {
        return;
    }
    let quill = null;
    try {
    quill = new Quill('#comment-quill-editor', {
        theme: 'snow',
        placeholder: '写下你的评论...',
        modules: {
            toolbar: {
                container: [
                    ['bold', 'italic', 'underline'],
                    [{ 'size': ['small', false, 'large', 'huge'] }],
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                    ['link', 'image'],
                    ['clean']
                ],
                handlers: {
                    'image': function () {
                        const input = document.createElement('input');
                        input.setAttribute('type', 'file');
                        input.setAttribute('accept', 'image/*');
                        input.click();

                        input.onchange = function () {
                            if (input.files && input.files[0]) {
                                const existingImages = quill.root.querySelectorAll('img');
                                if (existingImages.length >= 2) {
                                    window.showToast('最多只能上传2张图片', 'error');
                                    return;
                                }

                                const formData = new FormData();
                                formData.append('image', input.files[0]);
                                formData.append('action', 'upload_comment_image');

                                window.showToast('图片上传中...', 'info');

                                fetch(window.location.href.split('#')[0], {
                                    method: 'POST',
                                    body: formData,
                                    credentials: 'include'
                                })
                                    .then(response => {
                                        if (!response.ok) {
                                            throw new Error('HTTP error! status: ' + response.status);
                                        }
                                        return response.json();
                                    })
                                    .then(data => {
                                        if (data.success) {
                                            try {
                                                const range = quill.getSelection(true) || { index: 0, length: 0 };
                                                quill.insertEmbed(range.index, 'image', data.url);
                                                quill.setSelection(range.index + 1);

                                                setTimeout(function () {
                                                    const images = quill.root.querySelectorAll('img');
                                                    const lastImage = images[images.length - 1];
                                                    if (lastImage) {
                                                        setTimeout(function () {
                                                            const imgRect = lastImage.getBoundingClientRect();
                                                            const imgHeight = imgRect.height;
                                                            const editor = document.getElementById('comment-quill-editor');
                                                            const quillEditor = editor.querySelector('.ql-editor');
                                                            const contentHeight = quillEditor.scrollHeight;
                                                            const targetHeight = Math.max(contentHeight, imgHeight + 20);
                                                            editor.style.minHeight = targetHeight + 'px';
                                                            editor.style.height = targetHeight + 'px';
                                                            quillEditor.style.minHeight = targetHeight + 'px';
                                                            quillEditor.style.height = targetHeight + 'px';
                                                        }, 100);
                                                    }
                                                }, 200);

                                                window.showToast('图片上传成功', 'success');
                                            } catch (insertError) {
                                                console.error('插入图片错误:', insertError);
                                                window.showToast('图片上传成功，但插入失败，请手动添加', 'warning');
                                            }
                                        } else {
                                            window.showToast(data.message || '图片上传失败', 'error');
                                        }
                                    })
                                    .catch(error => {
                                        console.error('上传错误:', error);
                                        window.showToast('图片上传失败，请稍后重试', 'error');
                                    });
                            }
                        };
                    }
                }
            },
            // 自定义粘贴处理，确保所有粘贴内容都转为纯文本
            clipboard: {
                matchVisual: false,
                // 禁用所有默认粘贴格式
                formats: [],
                // 重写粘贴处理，确保只插入纯文本
                onPaste: function (e) {
                    e.preventDefault();

                    let text = '';

                    // 1. 优先获取纯文本
                    if (e.clipboardData && e.clipboardData.getData) {
                        text = e.clipboardData.getData('text/plain');
                    } else if (window.clipboardData && window.clipboardData.getData) {
                        text = window.clipboardData.getData('Text');
                    }

                    // 2. 如果没有纯文本，从HTML中提取
                    if (!text && e.clipboardData && e.clipboardData.getData) {
                        const html = e.clipboardData.getData('text/html');
                        if (html) {
                            // 创建临时元素来提取纯文本
                            const tempDiv = document.createElement('div');
                            tempDiv.innerHTML = html;
                            text = tempDiv.textContent || tempDiv.innerText || '';
                        }
                    }

                    // 3. 清除任何可能的HTML标签和多余空白
                    text = text.replace(/<[^>]+>/g, '')
                        .replace(/\s+/g, ' ')
                        .trim();

                    // 4. 只插入纯文本，不保留任何格式
                    const selection = quill.getSelection();
                    if (selection) {
                        quill.insertText(selection.index, text);
                        quill.setSelection(selection.index + text.length);
                    }
                }
            }
        }
    });
    } catch(e) {
        return;
    }

    // 移除多余的粘贴事件监听器，恢复正常的文字选择功能

    const commentTextarea = document.getElementById('comment-input');
    quill.on('text-change', function () {
        // 保持HTML格式提交，确保图片等内容正常保存
        commentTextarea.value = quill.root.innerHTML;
    });

    document.getElementById('comment-submit').addEventListener('click', function () {
        const plainText = quill.getText().trim();
        if (!window.validateCommentContent(plainText)) return;
        // 保持HTML格式提交
        commentTextarea.value = quill.root.innerHTML;
    });

    // 添加拖动调整高度功能
    function addResizeFunctionality() {
        const editor = document.getElementById('comment-quill-editor');
        const resizeHandle = document.createElement('div');
        resizeHandle.className = 'quill-resize-handle';
        resizeHandle.textContent = '';
        editor.appendChild(resizeHandle);

        let isResizing = false;
        let startY = 0;
        let startHeight = 0;

        resizeHandle.addEventListener('mousedown', function (e) {
            e.preventDefault();
            isResizing = true;
            startY = e.clientY;
            startHeight = editor.offsetHeight;

            document.addEventListener('mousemove', handleMouseMove);
            document.addEventListener('mouseup', stopResizing);
            document.body.classList.add('no-user-select');
        });

        function handleMouseMove(e) {
            if (!isResizing) return;
            const heightDelta = e.clientY - startY;
            const newHeight = Math.max(150, Math.min(600, startHeight + heightDelta));
            editor.style.height = newHeight + 'px';
        }

        function stopResizing() {
            isResizing = false;
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', stopResizing);
            document.body.classList.remove('no-user-select');
        }
    }

    addResizeFunctionality();

    // 添加图片拖动调整大小功能
    function addImageResizeFunctionality() {
        const editor = document.getElementById('comment-quill-editor');
        let selectedImage = null;
        let resizeHandle = null;
        let isResizing = false;
        let startX, startY, startWidth, startHeight;

        editor.addEventListener('click', function (e) {
            if (e.target.tagName === 'IMG') {
                if (selectedImage && selectedImage !== e.target) {
                    selectedImage.classList.remove('selected');
                    if (resizeHandle && resizeHandle.parentNode) resizeHandle.parentNode.removeChild(resizeHandle);
                }

                selectedImage = e.target;
                selectedImage.classList.add('selected');

                if (!resizeHandle) {
                    resizeHandle = document.createElement('div');
                    resizeHandle.className = 'image-resize-handle';
                    resizeHandle.addEventListener('mousedown', startResize);
                }

                let editorContainer = selectedImage;
                while (editorContainer && !editorContainer.classList.contains('ql-editor')) editorContainer = editorContainer.parentElement;

                window.targetContainer = editorContainer ? editorContainer.parentElement : document.body;

                if (resizeHandle.parentNode !== targetContainer) {
                    if (resizeHandle.parentNode) resizeHandle.parentNode.removeChild(resizeHandle);
                    targetContainer.appendChild(resizeHandle);
                }

                const imgRect = selectedImage.getBoundingClientRect();
                const containerRect = window.targetContainer.getBoundingClientRect();
                resizeHandle.style.left = (imgRect.right - containerRect.left - 26) + 'px';
                resizeHandle.style.top = (imgRect.bottom - containerRect.top - 26) + 'px';
                resizeHandle.textContent = '↘';
                resizeHandle.dataset.targetImageId = selectedImage.id || 'selected-image';
            } else if (selectedImage) {
                selectedImage.classList.remove('selected');
                if (resizeHandle && resizeHandle.parentNode) resizeHandle.parentNode.removeChild(resizeHandle);
                selectedImage = null;
            }
        });

        function startResize(e) {
            e.preventDefault();
            e.stopPropagation();
            if (!selectedImage) return;

            isResizing = true;
            startX = e.clientX;
            startY = e.clientY;
            startWidth = selectedImage.offsetWidth;
            startHeight = selectedImage.offsetHeight;
            aspectRatio = startWidth / startHeight;

            const editor = document.getElementById('comment-quill-editor') || document.querySelector('.ql-editor');
            maxImageWidth = editor ? (editor.clientWidth - 40) : 500;

            document.addEventListener('mousemove', resizeImage);
            document.addEventListener('mouseup', stopResize);
            document.body.classList.add('no-user-select');
        }

        function resizeImage(e) {
            if (!isResizing || !selectedImage) return;
            const widthDelta = e.clientX - startX;
            let newWidth = startWidth + widthDelta;
            const minSize = 50;
            const maxWidth = maxImageWidth || 500;
            newWidth = Math.max(minSize, Math.min(maxWidth, newWidth));
            let newHeight = newWidth / aspectRatio;
            newHeight = Math.max(minSize, newHeight);

            selectedImage.style.width = newWidth + 'px';
            selectedImage.style.height = newHeight + 'px';

            if (resizeHandle && resizeHandle.parentNode) {
                const imgRect = selectedImage.getBoundingClientRect();
                const containerRect = window.targetContainer.getBoundingClientRect();
                resizeHandle.style.left = (imgRect.right - containerRect.left - 26) + 'px';
                resizeHandle.style.top = (imgRect.bottom - containerRect.top - 26) + 'px';
            }

            selectedImage.setAttribute('width', newWidth);
            selectedImage.setAttribute('height', newHeight);
            adjustEditorHeight();
        }

        function adjustEditorHeight() {
            setTimeout(function () {
                const editor = document.getElementById('comment-quill-editor');
                const quillEditor = editor.querySelector('.ql-editor');
                let maxImageHeight = 0;
                const images = quillEditor.querySelectorAll('img');
                images.forEach(img => {
                    const imgRect = img.getBoundingClientRect();
                    maxImageHeight = Math.max(maxImageHeight, imgRect.height);
                });

                const contentHeight = quillEditor.scrollHeight;
                const targetHeight = Math.max(contentHeight, maxImageHeight + 20);

                editor.style.minHeight = targetHeight + 'px';
                editor.style.height = targetHeight + 'px';
                quillEditor.style.minHeight = targetHeight + 'px';
                quillEditor.style.height = targetHeight + 'px';
            }, 0);
        }

        function stopResize() {
            if (!isResizing) return;
            isResizing = false;
            document.removeEventListener('mousemove', resizeImage);
            document.removeEventListener('mouseup', stopResize);
            document.body.classList.remove('no-user-select');

            if (selectedImage) {
                const width = selectedImage.style.width;
                const height = selectedImage.style.height;
                selectedImage.setAttribute('width', width);
                selectedImage.setAttribute('height', height);

                if (quill) {
                    const selection = quill.getSelection();
                    setTimeout(() => {
                        const allImages = quill.root.querySelectorAll('img');
                        allImages.forEach(img => {
                            if (img.src === selectedImage.src) {
                                img.style.width = width;
                                img.style.height = height;
                                img.setAttribute('width', width);
                                img.setAttribute('height', height);
                            }
                        });
                        if (selection) quill.setSelection(selection.index, selection.length);
                    }, 0);
                }
            }
        }
    }

    addImageResizeFunctionality();

    window.commentQuill = quill;
});

// ===== 事件委托处理 =====
// 移除冲突的事件委托处理函数，避免干扰回复弹窗的正常功能

// // 点击遮罩层关闭弹窗
// document.addEventListener('click', function (e) {
//     if (e.target.classList.contains('modal-backdrop')) {
//         closeReportModal();
//         closeCommentModal();
//     }
// });

// // ESC键关闭弹窗
// document.addEventListener('keydown', function (e) {
//     if (e.key === 'Escape') {
//         closeReportModal();
//         closeCommentModal();
//     }
// });
