/**
 * 评论弹窗逻辑
 */

(function() {
    'use strict';

    // 评论相关状态
    const commentState = {
        postId: 0,
        page: 1,
        hasMore: true,
        isLoading: false,
        replyToUserId: 0,
        replyToUsername: '',
        replyToCommentId: 0
    };

    /**
     * 打开评论弹窗
     */
    window.openCommentModal = function(postId) {
        commentState.postId = postId;
        commentState.page = 1;
        commentState.hasMore = true;
        commentState.replyToUserId = 0;
        commentState.replyToUsername = '';
        commentState.replyToCommentId = 0;

        // 清空评论列表
        const commentList = document.getElementById('commentListContainer');
        if (commentList) {
            commentList.innerHTML = `
                <div class="comment-loading" id="commentLoading">
                    <div class="loading-dots">
                        <span></span><span></span><span></span>
                    </div>
                </div>
            `;
        }

        // 清空输入框
        const input = document.getElementById('modalCommentInput');
        if (input) input.value = '';

        // 隐藏回复提示
        const replyTip = document.getElementById('commentReplyTip');
        if (replyTip) replyTip.style.display = 'none';

        openModal('commentModal');

        // 加载评论
        loadComments();
    };

    /**
     * 加载评论列表
     */
    async function loadComments() {
        if (commentState.isLoading || !commentState.hasMore) return;

        commentState.isLoading = true;
        
        // 第一页时清空列表，防止重复
        if (commentState.page === 1) {
            const commentList = document.getElementById('commentListContainer');
            if (commentList) {
                commentList.innerHTML = `
                    <div class="comment-loading" id="commentLoading">
                        <div class="loading-dots">
                            <span></span><span></span><span></span>
                        </div>
                    </div>
                `;
            }
        }

        try {
            const baseUrl = window.BASE_URL || window.location.origin;
            const response = await fetch(`${baseUrl}/?r=mobileApi/comments&post_id=${commentState.postId}&page=${commentState.page}`);
            const result = await response.json();

            if (result.code === 0) {
                renderComments(result.data.items || result.data);
                commentState.hasMore = result.data.pagination?.has_more || result.has_more || false;
                commentState.page++;
                
                // 更新评论总数
                const countBadge = document.getElementById('commentCount');
                if (countBadge && result.data.total !== undefined) {
                    countBadge.textContent = result.data.total.toString();
                }
            } else {
                showToast(result.message || '加载评论失败');
            }
        } catch (error) {
            showToast('网络错误，请稍后重试');
            console.error('Load comments error:', error);
        } finally {
            commentState.isLoading = false;
            // 隐藏加载指示器
            const loading = document.getElementById('commentLoading');
            if (loading) loading.style.display = 'none';
        }
    }

    /**
 * 获取头像URL（处理可能包含HTML标签的情况）
 */
function getAvatarUrl(avatar) {
    const defaultAvatar = '/templates/mobile/images/avatar_default.png';
    
    if (!avatar || typeof avatar !== 'string' || avatar.trim() === '') {
        return defaultAvatar;
    }
    
    // 如果是HTML格式（包含img标签），提取src属性
    if (avatar.includes('<img')) {
        const match = avatar.match(/<img[^>]+src=["']([^"']+)["']/i);
        if (match && match[1]) {
            return match[1];
        }
    } else if (!avatar.includes('<')) {
        // 纯URL
        return avatar;
    }
    
    // 格式异常，使用默认头像
    return defaultAvatar;
}

/**
 * 渲染评论列表
 */
function renderComments(comments) {
    const container = document.getElementById('commentListContainer');
    if (!container) return;

    const existingLoading = document.getElementById('commentLoading');
    if (existingLoading) {
        existingLoading.remove();
    }

    if (!comments || comments.length === 0) {
        if (commentState.page === 1) {
            container.innerHTML = '<div class="comment-empty">暂无评论</div>';
        }
        return;
    }

    comments.forEach(comment => {
        const commentItem = document.createElement('div');
        commentItem.className = 'comment-item';
        commentItem.dataset.commentId = comment.id;

        // 构建回复列表HTML
        let repliesHtml = '';
        if (comment.replies && comment.replies.length > 0) {
            repliesHtml = `
                <div class="comment-replies">
                    ${comment.replies.map(reply => `
                        <div class="comment-reply-item" data-reply-id="${reply.id}">
                            <div class="comment-reply-header">
                                <img src="${getAvatarUrl(reply.avatar)}" class="comment-reply-avatar" onerror="this.src='/templates/mobile/images/avatar_default.png'">
                                <span class="comment-reply-user">${reply.username}</span>
                                <div class="comment-reply-meta">
                                    <span class="comment-reply-time">${reply.time_ago || formatTime(reply.created_at)}</span>
                                </div>
                            </div>
                            <div class="comment-reply-content">
                                ${reply.reply_to_username ? `<span class="comment-reply-to">@${reply.reply_to_username}</span>` : ''}
                                ${reply.content}
                            </div>
                            <div class="comment-reply-actions">
                                <button class="comment-reply-action" onclick="replyToComment(${comment.id}, ${reply.user_id}, '${reply.username}', ${reply.id})">回复</button>
                                <button class="comment-reply-action ${reply.is_liked ? 'liked' : ''}" onclick="likeComment(${reply.id})">
                                    <span>${reply.is_liked ? '❤' : '♡'} ${reply.likes || 0}</span>
                                </button>
                            </div>
                        </div>
                    `).join('')}
                </div>
            `;
        }

        // 处理头像URL，支持空字符串、null和HTML标签格式
        const avatarUrl = getAvatarUrl(comment.avatar);
        
        commentItem.innerHTML = `
            <div class="comment-avatar-wrapper">
                <img src="${avatarUrl}" class="comment-avatar" onerror="this.src='/templates/mobile/images/avatar_default.png'">
            </div>
            <div class="comment-body">
                <div class="comment-user-info">
                    <span class="comment-username">${comment.username}</span>
                    <span class="comment-time">${comment.time_ago || formatTime(comment.created_at)}</span>
                </div>
                <div class="comment-content">${comment.content}</div>
                <div class="comment-actions">
                    <button class="comment-action-btn ${comment.is_liked ? 'liked' : ''}" onclick="likeComment(${comment.id})">
                        <span class="action-icon">${comment.is_liked ? '❤' : '♡'}</span>
                        <span class="action-text">${comment.likes || 0}</span>
                    </button>
                    <button class="comment-action-btn" onclick="replyToComment(${comment.id}, ${comment.user_id}, '${comment.username}', 0)">
                        <span class="action-icon">↩</span>
                        <span class="action-text">回复</span>
                    </button>
                    <button class="comment-action-btn" onclick="shareComment(${comment.id})">
                        <span class="action-icon">↗</span>
                        <span class="action-text">分享</span>
                    </button>
                </div>
                ${repliesHtml}
            </div>
        `;

        container.appendChild(commentItem);
    });

        // 如果还有更多，添加加载更多提示
        if (commentState.hasMore) {
            const loadMoreBtn = document.createElement('button');
            loadMoreBtn.className = 'view-more-replies';
            loadMoreBtn.textContent = '查看更多';
            loadMoreBtn.addEventListener('click', loadComments);
            container.appendChild(loadMoreBtn);
        }
    }

    /**
     * 提交评论
     */
    window.submitModalComment = async function() {
        const input = document.getElementById('modalCommentInput');
        const content = input?.value?.trim();

        if (!content) {
            showToast('请输入评论内容');
            return;
        }

        const submitBtn = document.getElementById('modalCommentSubmit');
        if (submitBtn) submitBtn.disabled = true;

        try {
            const data = {
                post_id: commentState.postId,
                content: content,
                parent_id: commentState.replyToCommentId,
                reply_to_user_id: commentState.replyToUserId
            };

            const baseUrl = window.BASE_URL || window.location.origin;
            const response = await fetch(`${baseUrl}/?r=mobileApi/comment`, {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.code === 0) {
                showToast('评论成功');
                // 清空输入
                if (input) input.value = '';
                // 重置回复状态
                cancelReply();
                // 重置分页，清空列表，重新加载第一页
                commentState.page = 1;
                commentState.hasMore = true;
                const commentList = document.getElementById('commentListContainer');
                if (commentList) {
                    commentList.innerHTML = `
                        <div class="comment-loading" id="commentLoading">
                            <div class="loading-dots">
                                <span></span><span></span><span></span>
                            </div>
                        </div>
                    `;
                }
                // 重新加载评论
                loadComments();
            } else {
                showToast(result.message || '评论失败');
            }
        } catch (error) {
            showToast('网络错误，请稍后重试');
            console.error('Submit comment error:', error);
        } finally {
            if (submitBtn) submitBtn.disabled = false;
        }
    };

    /**
     * 回复评论
     */
    window.replyToComment = function(commentId, userId, username, replyToId) {
        commentState.replyToUserId = userId;
        commentState.replyToUsername = username;
        commentState.replyToCommentId = replyToId;

        const replyTip = document.getElementById('commentReplyTip');
        const replyToUsernameEl = document.getElementById('replyToUsername');
        const input = document.getElementById('modalCommentInput');

        if (replyTip) replyTip.style.display = 'flex';
        if (replyToUsernameEl) replyToUsernameEl.textContent = username;
        if (input) {
            input.focus();
            input.value = `@${username} `;
        }
    };

    /**
     * 取消回复
     */
    window.cancelReply = function() {
        commentState.replyToUserId = 0;
        commentState.replyToUsername = '';
        commentState.replyToCommentId = 0;

        const replyTip = document.getElementById('replyTip');
        const input = document.getElementById('modalCommentInput');

        if (replyTip) replyTip.style.display = 'none';
        if (input) input.value = '';
    };

    /**
     * 点赞评论
     */
    window.likeComment = async function(commentId) {
        // 检查登录状态
        if (!checkLogin()) {
            if (typeof openLoginModal === 'function') {
                openLoginModal();
            } else {
                showToast('请先登录');
            }
            return;
        }

        // 查找评论元素（支持主评论和楼中楼回复）
        const commentItem = document.querySelector(`.comment-item[data-comment-id="${commentId}"]`);
        const replyItem = document.querySelector(`.comment-reply-item[data-reply-id="${commentId}"]`);
        const targetItem = commentItem || replyItem;
        
        if (!targetItem) return;

        // 获取当前点赞状态
        const isLiked = targetItem.querySelector('.comment-action-btn')?.classList.contains('liked') ||
                        targetItem.querySelector('.comment-reply-action')?.classList.contains('liked');

        try {
            const baseUrl = window.BASE_URL || window.location.origin;
            const apiUrl = isLiked 
                ? `${baseUrl}/?r=mobileApi/unlikeComment` 
                : `${baseUrl}/?r=mobileApi/likeComment`;

            const response = await fetch(apiUrl, {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ comment_id: commentId })
            });

            const result = await response.json();

            if (result.code === 0) {
                // 更新UI
                if (commentItem) {
                    const actionBtn = commentItem.querySelector('.comment-action-btn');
                    const likeCount = actionBtn?.querySelector('.action-text');
                    const actionIcon = actionBtn?.querySelector('.action-icon');

                    if (!isLiked) {
                        actionBtn.classList.add('liked');
                        actionIcon.textContent = '❤';
                    } else {
                        actionBtn.classList.remove('liked');
                        actionIcon.textContent = '♡';
                    }

                    if (likeCount) {
                        likeCount.textContent = (result.data.likes || result.data.like_count).toString();
                    }
                }
                
                // 更新楼中楼回复的UI
                if (replyItem) {
                    const actionBtn = replyItem.querySelector('.comment-reply-action');
                    if (actionBtn) {
                        const likeSpan = actionBtn.querySelector('span');
                        if (likeSpan) {
                            if (!isLiked) {
                                actionBtn.classList.add('liked');
                                likeSpan.innerHTML = `❤ ${result.data.likes || result.data.like_count || 1}`;
                            } else {
                                actionBtn.classList.remove('liked');
                                likeSpan.innerHTML = `♡ ${result.data.likes || result.data.like_count || 0}`;
                            }
                        }
                    }
                }
            } else {
                showToast(result.message || '操作失败');
            }
        } catch (error) {
            console.error('Like comment error:', error);
            showToast('网络错误，请稍后重试');
        }
    };

    /**
     * 分享评论
     */
    window.shareComment = function(commentId) {
        const url = `${window.location.origin}/post/${commentState.postId}#comment-${commentId}`;
        
        // 检查 clipboard API 是否可用（需要 HTTPS 或 localhost）
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(() => {
                showToast('链接已复制');
            }).catch(() => {
                // clipboard API 失败，尝试降级方案
                copyTextToClipboardFallback(url);
            });
        } else {
            // clipboard API 不可用，使用降级方案
            copyTextToClipboardFallback(url);
        }
    };

    /**
     * 降级复制方案（兼容 HTTP 环境）
     */
    function copyTextToClipboardFallback(text) {
        // 创建临时 textarea 元素
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.cssText = `
            position: fixed;
            left: -9999px;
            top: -9999px;
            width: 1px;
            height: 1px;
            opacity: 0;
        `;
        document.body.appendChild(textarea);
        
        try {
            // 选中内容
            textarea.select();
            textarea.setSelectionRange(0, textarea.value.length);
            
            // 执行复制
            const success = document.execCommand('copy');
            
            if (success) {
                showToast('链接已复制');
            } else {
                // 复制失败，显示链接供用户手动复制
                showToast('复制失败，请手动复制链接');
                // 可选：显示链接
                if (confirm('复制失败，是否打开链接？')) {
                    window.open(text, '_blank');
                }
            }
        } catch (err) {
            showToast('复制失败，请手动复制链接');
            console.error('Copy fallback error:', err);
        } finally {
            // 清理
            document.body.removeChild(textarea);
        }
    };

    /**
     * 切换评论表情选择器
     */
    window.toggleCommentEmoji = function() {
        const emojiPicker = document.getElementById('commentEmojiPicker');
        if (!emojiPicker) return;

        if (emojiPicker.style.display === 'none' || emojiPicker.style.display === '') {
            emojiPicker.style.display = 'block';
            loadCommentEmojis();
        } else {
            emojiPicker.style.display = 'none';
        }
    };

    /**
     * 加载评论表情
     */
    function loadCommentEmojis() {
        const emojiGrid = document.getElementById('commentEmojiGrid');
        if (!emojiGrid || emojiGrid.children.length > 0) return;

        const emojis = ['1f600', '1f601', '1f602', '1f603', '1f604', '1f605', '1f606', '1f607',
                        '1f608', '1f609', '1f60a', '1f60b', '1f60c', '1f60d', '1f60e', '1f60f',
                        '1f610', '1f611', '1f612', '1f613', '1f614', '1f615', '1f616', '1f617',
                        '1f44d', '1f44e', '2764', '1f389', '1f31f', '2728', '1f64f', '1f44b'];

        emojis.forEach(emojiCode => {
            const emojiItem = document.createElement('span');
            emojiItem.className = 'emoji-item';
            emojiItem.textContent = String.fromCodePoint(parseInt(emojiCode, 16));
            emojiItem.addEventListener('click', () => {
                insertCommentEmoji(emojiItem.textContent);
            });
            emojiGrid.appendChild(emojiItem);
        });
    }

    /**
     * 插入评论表情
     */
    function insertCommentEmoji(emoji) {
        const input = document.getElementById('modalCommentInput');
        if (!input) return;

        const start = input.selectionStart;
        const end = input.selectionEnd;
        const value = input.value;

        input.value = value.substring(0, start) + emoji + value.substring(end);
        input.selectionStart = input.selectionEnd = start + emoji.length;
        input.focus();
    }

    /**
     * 初始化评论弹窗
     */
    function initCommentModal() {
        // 提交按钮已通过 onclick 属性绑定，这里不再重复绑定

        // 添加输入框事件
        const input = document.getElementById('modalCommentInput');
        if (input) {
            input.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    submitModalComment();
                }
            });
        }

        // 表情按钮已通过 onclick 属性绑定，这里不再重复绑定

        // 添加取消回复按钮事件
        const cancelReplyBtn = document.getElementById('commentReplyTip')?.querySelector('button');
        if (cancelReplyBtn) {
            cancelReplyBtn.addEventListener('click', cancelReply);
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', initCommentModal);
})();
