<?php
if (!defined('ABSPATH')) {
    exit;
}
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?> class="">
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="renderer" content="webkit">
    <meta name="force-rendering" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <style>
        [x-cloak] { display: none !important; }
    </style>

    <script>
        (function() {
            const savedTheme = localStorage.getItem('icefox_theme_mode');
            if (savedTheme === 'dark') {
                document.documentElement.classList.add('dark');
            } else if (savedTheme === 'light') {
                document.documentElement.classList.remove('dark');
            }
        })();
    </script>

    <script>
        window.ICEFOX_CONFIG = {
            actionUrl: <?php echo wp_json_encode(rest_url('icefox/v1/action')); ?>,
            defaultAvatar: <?php echo wp_json_encode(get_template_directory_uri() . '/assets/images/default-avatar.svg'); ?>,
            restNonce: <?php echo wp_json_encode(wp_create_nonce('wp_rest')); ?>,
            locationLookupEnabled: <?php echo wp_json_encode(icefox_get_frontend_tencent_map_key() !== ''); ?>
        };

        const EMOJI_DATA = {
            '表情': ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🥸', '🤩', '🥳'],
            '手势': ['👋', '🤚', '🖐', '✋', '🖖', '👌', '🤌', '🤏', '✌', '🤞', '🤟', '🤘', '🤙', '👈', '👉', '👆', '🖕', '👇', '☝', '👍', '👎', '✊', '👊', '🤛', '🤜', '👏', '🙌', '👐', '🤲', '🤝', '🙏'],
            '动物': ['🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', '🐨', '🐯', '🦁', '🐮', '🐷', '🐽', '🐸', '🐵', '🙈', '🙉', '🙊', '🐒', '🐔', '🐧', '🐦', '🐤', '🐣', '🐥', '🦆', '🦅', '🦉', '🦇', '🐺', '🐗'],
            '食物': ['🍎', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🍈', '🍒', '🍑', '🥭', '🍍', '🥥', '🥝', '🍅', '🍆', '🥑', '🥦', '🥬', '🥒', '🌶', '🌽', '🥕', '🧄', '🧅', '🥔', '🍠', '🥐', '🥯', '🍞', '🥖', '🥨'],
            '活动': ['⚽', '🏀', '🏈', '⚾', '🥎', '🎾', '🏐', '🏉', '🥏', '🎱', '🪀', '🏓', '🏸', '🏒', '🏑', '🥍', '🏏', '🪃', '🥅', '⛳', '🪁', '🏹', '🎣', '🤿', '🥊', '🥋', '🎽', '🛹', '🛼', '🛷', '⛸', '🥌'],
            '符号': ['❤', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '🤎', '💔', '❣', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '☮', '✝', '☪', '🕉', '☸', '✡', '🔯', '🕎', '☯', '☦', '🛐', '⛎', '♈']
        };

        function commentReplyManager() {
            return {
                activeCommentId: null,
                replyForm: null,

                init() {
                    document.addEventListener('click', this.handleClickOutside.bind(this));
                },

                togglePostTimeComment(event, postId) {
                    event.preventDefault();
                    event.stopPropagation();

                    const currentModal = document.getElementById(`ptcm-${postId}`);
                    if (!currentModal) return;

                    const currentAlpineComponent = Alpine.$data(currentModal);
                    if (!currentAlpineComponent) return;

                    if (currentAlpineComponent.ptcmShow) {
                        currentAlpineComponent.ptcmShow = false;
                        return;
                    }

                    this.hideAllPostTimeCommentModals();
                    currentAlpineComponent.ptcmShow = true;
                },

                hideAllPostTimeCommentModals() {
                    const allModals = document.querySelectorAll('.post-time-comment');
                    allModals.forEach(modal => {
                        const alpineComponent = Alpine.$data(modal);
                        if (alpineComponent && alpineComponent.ptcmShow !== undefined) {
                            alpineComponent.ptcmShow = false;
                        }
                    });
                },

                showReplyForm(event, postId, coid, authorName) {
                    event.preventDefault();

                    const clickedElement = event.target;
                    const commentItem = clickedElement.closest('.pcc-comment-item');
                    if (!commentItem) return;

                    if (!coid || coid === '0') {
                        const domCoid = commentItem.dataset.commentId;
                        if (domCoid && domCoid !== '0') {
                            coid = domCoid;
                        }
                    }

                    const formId = `reply-form-${postId}-${Date.now()}`;

                    if (this.activeCommentId === commentItem) {
                        this.removeReplyForm();
                        this.activeCommentId = null;
                        return;
                    }

                    this.removeReplyForm();

                    const form = this.createReplyForm(formId, postId, authorName, coid);
                    commentItem.parentNode.insertBefore(form, commentItem.nextSibling);
                    this.activeCommentId = commentItem;
                    this.hidePostTimeCommentModal(postId);
                    form.querySelector('input[name="reply_content"]').focus();
                },

                showPostReplyForm(event, postId) {
                    event.preventDefault();
                    event.stopPropagation();

                    this.removeReplyForm();

                    const formId = `post-reply-form-${postId}-${Date.now()}`;
                    const postItem = event.target.closest('.post-item');
                    if (!postItem) return;

                    const targetContainer = postItem.querySelector('.post-comment-container');
                    if (!targetContainer) return;

                    let commentList = targetContainer.querySelector('.pcc-comment-list');
                    if (!commentList) {
                        commentList = document.createElement('div');
                        commentList.className = 'pcc-comment-list';
                        targetContainer.appendChild(commentList);
                    }

                    targetContainer.style.display = '';

                    const form = this.createPostReplyForm(formId, postId);
                    targetContainer.appendChild(form);
                    this.activeCommentId = `post-${postId}`;
                    this.hidePostTimeCommentModal(postId);

                    setTimeout(() => {
                        const input = form.querySelector('input[type="text"]');
                        if (input) {
                            input.focus();
                        }
                    }, 100);
                },

                createPostReplyForm(formId, postId) {
                    const form = document.createElement('div');
                    form.className = 'reply-form-container post-reply-form';
                    form.id = formId;

                    const savedAuthor = localStorage.getItem('icefox_comment_author') || '';
                    const savedEmail = localStorage.getItem('icefox_comment_email') || '';
                    const savedUrl = localStorage.getItem('icefox_comment_url') || '';

                    form.innerHTML = `
                        <div class="reply-form" x-data="{replyAuthor: '${this.escapeHtml(savedAuthor)}', replyEmail: '${this.escapeHtml(savedEmail)}', replyUrl: '${this.escapeHtml(savedUrl)}', replyContent: '', emojiPickerShow: false, currentEmojiTab: '表情'}">
                            <div class="reply-form-header">
                                <strong>发表评论</strong>
                                <button type="button" class="reply-form-close">×</button>
                            </div>
                            <form>
                                <div class="reply-form-user-info">
                                    <div class="reply-form-input">
                                        <input type="text" name="author_name" placeholder="昵称" required x-model="replyAuthor">
                                    </div>
                                    <div class="reply-form-input">
                                        <input type="email" name="author_email" placeholder="邮箱" required x-model="replyEmail">
                                    </div>
                                    <div class="reply-form-input">
                                        <input type="url" name="author_url" placeholder="网址" x-model="replyUrl">
                                    </div>
                                </div>
                                <div class="reply-form-input">
                                    <input type="text" name="reply_content" placeholder="写下你的评论..." required x-model="replyContent">
                                </div>
                                <div class="reply-form-bottom">
                                    <div class="reply-form-emoji-container">
                                        <button type="button" class="reply-form-emoji-toggle" @click.stop="emojiPickerShow = !emojiPickerShow">
                                            😀 <span>表情</span>
                                        </button>
                                        <div class="reply-form-emoji-picker" :class="{'show': emojiPickerShow}" @click.stop>
                                            <div class="emoji-picker-header">
                                                <span class="emoji-picker-title">选择表情</span>
                                                <button type="button" class="emoji-picker-close" @click="emojiPickerShow = false">×</button>
                                            </div>
                                            <div class="emoji-picker-tabs">
                                                ${Object.keys(EMOJI_DATA).map(tab => `
                                                    <button type="button" class="emoji-tab" :class="{'active': currentEmojiTab === '${tab}'}" @click="currentEmojiTab = '${tab}'">${tab}</button>
                                                `).join('')}
                                            </div>
                                            <div class="emoji-picker-content">
                                                ${Object.entries(EMOJI_DATA).map(([category, emojis]) =>
                                                    emojis.map(emoji => `
                                                        <span class="emoji-item" x-show="currentEmojiTab === '${category}'" @click="replyContent += '${emoji}'; emojiPickerShow = false">${emoji}</span>
                                                    `).join('')
                                                ).join('')}
                                            </div>
                                        </div>
                                    </div>
                                    <div class="reply-form-actions">
                                        <button type="submit" class="reply-submit-btn">发表评论</button>
                                        <button type="button" class="reply-cancel-btn">取消</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    `;

                    const closeBtn = form.querySelector('.reply-form-close');
                    const cancelBtn = form.querySelector('.reply-cancel-btn');
                    const submitForm = form.querySelector('form');

                    closeBtn.addEventListener('click', () => {
                        this.removeReplyForm();
                    });

                    cancelBtn.addEventListener('click', () => {
                        this.removeReplyForm();
                    });

                    submitForm.addEventListener('submit', (e) => {
                        e.preventDefault();
                        this.submitPostReply(e, postId);
                    });

                    return form;
                },

                async submitPostReply(event, postId) {
                    const form = event.target;
                    const authorName = form.querySelector('input[name="author_name"]').value.trim();
                    const authorEmail = form.querySelector('input[name="author_email"]').value.trim();
                    const authorUrl = form.querySelector('input[name="author_url"]').value.trim();
                    const content = form.querySelector('input[name="reply_content"]').value.trim();

                    if (!authorName || !authorEmail || !content) {
                        alert('请填写必要信息');
                        return;
                    }

                    localStorage.setItem('icefox_comment_author', authorName);
                    localStorage.setItem('icefox_comment_email', authorEmail);
                    localStorage.setItem('icefox_comment_url', authorUrl);

                    const submitBtn = form.querySelector('button[type="submit"]');
                    const originalText = submitBtn.textContent;
                    submitBtn.disabled = true;
                    submitBtn.textContent = '提交中...';

                    try {
                        const response = await fetch(`${window.ICEFOX_CONFIG.actionUrl}?do=addComment`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                author: authorName,
                                mail: authorEmail,
                                url: authorUrl || '',
                                text: content,
                                cid: postId,
                                coid: 0
                            })
                        });

                        const result = await response.json();

                        if (result.success) {
                            this.addCommentToList(postId, result.comment);
                            this.removeReplyForm();
                        } else {
                            alert(result.message || '评论发表失败，请稍后重试');
                        }
                    } catch (error) {
                        console.error('评论提交错误:', error);
                        alert('网络错误，请稍后重试');
                    } finally {
                        submitBtn.disabled = false;
                        submitBtn.textContent = originalText;
                    }
                },

                createReplyForm(formId, postId, authorName, coid) {
                    const form = document.createElement('div');
                    form.className = 'reply-form-container';
                    form.id = formId;
                    form.dataset.coid = coid;

                    const savedAuthor = localStorage.getItem('icefox_comment_author') || '';
                    const savedEmail = localStorage.getItem('icefox_comment_email') || '';
                    const savedUrl = localStorage.getItem('icefox_comment_url') || '';

                    form.innerHTML = `
                        <div class="reply-form" x-data="{replyAuthor: '${this.escapeHtml(savedAuthor)}', replyEmail: '${this.escapeHtml(savedEmail)}', replyUrl: '${this.escapeHtml(savedUrl)}', replyContent: '', emojiPickerShow: false, currentEmojiTab: '表情'}">
                            <div class="reply-form-header">
                                <strong>回复 ${authorName}</strong>
                                <button type="button" class="reply-form-close">×</button>
                            </div>
                            <form>
                                <div class="reply-form-user-info">
                                    <div class="reply-form-input">
                                        <input type="text" name="author_name" placeholder="昵称" required x-model="replyAuthor">
                                    </div>
                                    <div class="reply-form-input">
                                        <input type="email" name="author_email" placeholder="邮箱" required x-model="replyEmail">
                                    </div>
                                    <div class="reply-form-input">
                                        <input type="url" name="author_url" placeholder="网址" x-model="replyUrl">
                                    </div>
                                </div>
                                <div class="reply-form-input">
                                    <input type="text" name="reply_content" placeholder="写下你的回复..." required x-model="replyContent">
                                </div>
                                <div class="reply-form-bottom">
                                    <div class="reply-form-emoji-container">
                                        <button type="button" class="reply-form-emoji-toggle" @click.stop="emojiPickerShow = !emojiPickerShow">
                                            😀 <span>表情</span>
                                        </button>
                                        <div class="reply-form-emoji-picker" :class="{'show': emojiPickerShow}" @click.stop>
                                            <div class="emoji-picker-header">
                                                <span class="emoji-picker-title">选择表情</span>
                                                <button type="button" class="emoji-picker-close" @click="emojiPickerShow = false">×</button>
                                            </div>
                                            <div class="emoji-picker-tabs">
                                                ${Object.keys(EMOJI_DATA).map(tab => `
                                                    <button type="button" class="emoji-tab" :class="{'active': currentEmojiTab === '${tab}'}" @click="currentEmojiTab = '${tab}'">${tab}</button>
                                                `).join('')}
                                            </div>
                                            <div class="emoji-picker-content">
                                                ${Object.entries(EMOJI_DATA).map(([category, emojis]) =>
                                                    emojis.map(emoji => `
                                                        <span class="emoji-item" x-show="currentEmojiTab === '${category}'" @click="replyContent += '${emoji}'; emojiPickerShow = false">${emoji}</span>
                                                    `).join('')
                                                ).join('')}
                                            </div>
                                        </div>
                                    </div>
                                    <div class="reply-form-actions">
                                        <button type="submit" class="reply-submit-btn">发表回复</button>
                                        <button type="button" class="reply-cancel-btn">取消</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    `;

                    const closeBtn = form.querySelector('.reply-form-close');
                    const cancelBtn = form.querySelector('.reply-cancel-btn');
                    const submitForm = form.querySelector('form');

                    closeBtn.addEventListener('click', () => {
                        this.removeReplyForm();
                    });

                    cancelBtn.addEventListener('click', () => {
                        this.removeReplyForm();
                    });

                    submitForm.addEventListener('submit', (e) => {
                        e.preventDefault();
                        this.submitReply(e, postId);
                    });

                    return form;
                },

                async submitReply(event, postId) {
                    const form = event.target;
                    const authorName = form.querySelector('input[name="author_name"]').value.trim();
                    const authorEmail = form.querySelector('input[name="author_email"]').value.trim();
                    const authorUrl = form.querySelector('input[name="author_url"]').value.trim();
                    const content = form.querySelector('input[name="reply_content"]').value.trim();

                    if (!authorName || !authorEmail || !content) {
                        alert('请填写必要信息');
                        return;
                    }

                    localStorage.setItem('icefox_comment_author', authorName);
                    localStorage.setItem('icefox_comment_email', authorEmail);
                    localStorage.setItem('icefox_comment_url', authorUrl);

                    const formContainer = form.closest('.reply-form-container');
                    const coid = formContainer ? (formContainer.dataset.coid || 0) : 0;
                    const submitBtn = form.querySelector('button[type="submit"]');
                    const originalText = submitBtn.textContent;
                    submitBtn.disabled = true;
                    submitBtn.textContent = '提交中...';

                    try {
                        const response = await fetch(`${window.ICEFOX_CONFIG.actionUrl}?do=addComment`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                author: authorName,
                                mail: authorEmail,
                                url: authorUrl || '',
                                text: content,
                                cid: postId,
                                coid: coid
                            })
                        });

                        const result = await response.json();

                        if (result.success) {
                            this.addCommentToList(postId, result.comment);
                            this.removeReplyForm();
                        } else {
                            alert(result.message || '回复发表失败，请稍后重试');
                        }
                    } catch (error) {
                        console.error('回复提交错误:', error);
                        alert('网络错误，请稍后重试');
                    } finally {
                        submitBtn.disabled = false;
                        submitBtn.textContent = originalText;
                    }
                },

                removeReplyForm() {
                    const existingForms = document.querySelectorAll('.reply-form-container');
                    existingForms.forEach(form => {
                        const commentContainer = form.closest('.post-comment-container');
                        form.remove();

                        if (commentContainer) {
                            const likeList = commentContainer.querySelector('.pcc-like-list');
                            const commentList = commentContainer.querySelector('.pcc-comment-list');
                            const hasLikes = likeList && likeList.style.display !== 'none';
                            const hasComments = commentList && commentList.querySelectorAll('.pcc-comment-item').length > 0;

                            if (!hasLikes && !hasComments) {
                                commentContainer.style.display = 'none';
                            }
                        }
                    });

                    this.activeCommentId = null;
                },

                addCommentToList(postId, commentData) {
                    const allPostItems = document.querySelectorAll('.post-item');
                    let targetCommentList = null;

                    for (const item of allPostItems) {
                        const likeList = item.querySelector('.pcc-like-list');
                        if (likeList && likeList.dataset.cid == postId) {
                            targetCommentList = item.querySelector('.pcc-comment-list');
                            break;
                        }
                    }

                    if (!targetCommentList) {
                        return;
                    }

                    const commentItem = document.createElement('div');
                    commentItem.className = 'pcc-comment-item';
                    commentItem.dataset.commentId = commentData.coid;

                    const isAdmin = commentData.userGroup === 'administrator';
                    const authorBadge = isAdmin ? '<span class="author-badge">作者</span>' : '';

                    if (!commentData.parent || commentData.parent == 0) {
                        commentItem.innerHTML = `
                            <a href="${commentData.url || '#'}">${this.escapeHtml(commentData.author)}</a>
                            ${authorBadge}
                            <span>:</span>
                            <span class="cursor-help pcc-comment-content" @click="showReplyForm($event, '${postId}', '${commentData.coid}', '${this.escapeHtml(commentData.author)}')">${this.escapeHtml(commentData.text)}</span>
                        `;
                    } else {
                        const parentComment = targetCommentList.querySelector(`[data-comment-id="${commentData.parent}"]`);
                        let parentAuthor = '原评论';
                        let parentUrl = '#';
                        let parentAuthorBadge = '';

                        if (parentComment) {
                            const parentLink = parentComment.querySelector('a');
                            if (parentLink) {
                                parentAuthor = parentLink.textContent;
                                parentUrl = parentLink.href;
                            }

                            const parentBadge = parentComment.querySelector('.author-badge');
                            if (parentBadge) {
                                parentAuthorBadge = '<span class="author-badge">作者</span>';
                            }
                        }

                        commentItem.innerHTML = `
                            <a href="${commentData.url || '#'}">${this.escapeHtml(commentData.author)}</a>
                            ${authorBadge}
                            <span>回复</span>
                            <a href="${parentUrl}">${this.escapeHtml(parentAuthor)}</a>
                            ${parentAuthorBadge}
                            <span>:</span>
                            <span class="cursor-help pcc-comment-content" @click="showReplyForm($event, '${postId}', '${commentData.coid}', '${this.escapeHtml(commentData.author)}')">${this.escapeHtml(commentData.text)}</span>
                        `;
                    }

                    if (!commentData.parent || commentData.parent == 0) {
                        if (targetCommentList.firstChild) {
                            targetCommentList.insertBefore(commentItem, targetCommentList.firstChild);
                        } else {
                            targetCommentList.appendChild(commentItem);
                        }
                    } else {
                        const parentComment = targetCommentList.querySelector(`[data-comment-id="${commentData.parent}"]`);
                        if (parentComment && parentComment.nextSibling) {
                            targetCommentList.insertBefore(commentItem, parentComment.nextSibling);
                        } else {
                            targetCommentList.appendChild(commentItem);
                        }
                    }

                    if (window.Alpine) {
                        Alpine.initTree(commentItem);
                    }
                },

                escapeHtml(text) {
                    const div = document.createElement('div');
                    div.textContent = text;
                    return div.innerHTML;
                },

                hidePostTimeCommentModal(postId) {
                    const modal = document.getElementById(`ptcm-${postId}`);
                    if (modal) {
                        const alpineComponent = Alpine.$data(modal);
                        if (alpineComponent && alpineComponent.ptcmShow !== undefined) {
                            alpineComponent.ptcmShow = false;
                        }
                    }
                },

                handleClickOutside(event) {
                    if (this.activeCommentId && !event.target.closest('.reply-form-container') && !event.target.closest('.pcc-comment-content') && !event.target.closest('.ptcm-comment')) {
                        this.removeReplyForm();
                    }

                    if (!event.target.closest('.ptc-more') && !event.target.closest('.post-time-comment-modal')) {
                        this.hideAllPostTimeCommentModals();
                    }
                }
            }
        }
    </script>

    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php wp_body_open(); ?>
