<?php
/**
 * 帖子详情页
 */
require_once __DIR__ . '/includes/functions.php';

$postId = isset($_GET['id']) ? intval($_GET['id']) : 0;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

// 获取帖子信息
$post = db()->queryOne(
    "SELECT p.*, u.username, u.avatar, u.signature, c.name as category_name 
     FROM posts p 
     LEFT JOIN users u ON p.user_id = u.id 
     LEFT JOIN categories c ON p.category_id = c.id 
     WHERE p.id = ? AND p.status = 1",
    [$postId]
);

if (!$post) {
    setFlashMessage('error', '帖子不存在或已被删除');
    redirect(SITE_URL . '/index.php');
}

// 检查帖子是否被锁定（管理员可以查看）
$currentUser = getCurrentUser();
if ($post['is_locked'] && (!$currentUser || $currentUser['role'] != 1)) {
    setFlashMessage('error', '该帖子已被锁定，无法访问');
    redirect(SITE_URL . '/index.php');
}

// 增加浏览次数
db()->execute("UPDATE posts SET view_count = view_count + 1 WHERE id = ?", [$postId]);
$post['view_count']++;

// 每页回复数
$perPage = intval(getSetting('replies_per_page', 20));
$offset = ($page - 1) * $perPage;

// 获取主回复总数（用于分页，只统计有楼层号的主回复）
$totalResult = db()->queryOne(
    "SELECT COUNT(*) as total FROM replies WHERE post_id = ? AND status = 1 AND floor_number > 0",
    [$postId]
);
$total = $totalResult['total'];

// 获取回复列表（只获取主回复，floor_number > 0）
$replies = db()->query(
    "SELECT r.*, u.username, u.avatar 
     FROM replies r 
     LEFT JOIN users u ON r.user_id = u.id 
     WHERE r.post_id = ? AND r.status = 1 AND r.floor_number > 0
     ORDER BY r.floor_number ASC 
     LIMIT ? OFFSET ?",
    [$postId, $perPage, $offset]
);

// 获取所有子回复（楼中楼，floor_number = 0）
$subReplies = []; // 直接挂在主回复下的楼中楼
$nestedSubReplies = []; // 挂在楼中楼下的回复（嵌套）
$parentNames = []; // 存储父回复的用户名
$isMainReply = []; // 记录哪些ID是主回复（有楼层号）

// 标记所有主回复ID
foreach ($replies as $r) {
    $isMainReply[$r['id']] = true;
}

// 获取所有楼中楼回复
$subRepliesList = db()->query(
    "SELECT sr.*, su.username, su.avatar 
     FROM replies sr 
     LEFT JOIN users su ON sr.user_id = su.id 
     WHERE sr.post_id = ? AND sr.status = 1 AND sr.floor_number = 0
     ORDER BY sr.created_at ASC",
    [$postId]
);

// 先获取所有父回复的信息
$allReplyIds = array_column($subRepliesList, 'parent_id');
if (!empty($allReplyIds)) {
    $placeholders = implode(',', array_fill(0, count($allReplyIds), '?'));
    $parentInfoList = db()->query(
        "SELECT r.id, r.parent_id, r.floor_number, u.username 
         FROM replies r 
         LEFT JOIN users u ON r.user_id = u.id 
         WHERE r.id IN ($placeholders)",
        $allReplyIds
    );
    foreach ($parentInfoList as $info) {
        $parentNames[$info['id']] = $info['username'];
        // 标记是否为主回复（floor_number > 0）
        if ($info['floor_number'] > 0) {
            $isMainReply[$info['id']] = true;
        }
    }
}

// 分组：主回复的直接回复挂在 subReplies，楼中楼的回复挂在 nestedSubReplies
foreach ($subRepliesList as $sub) {
    $parentId = $sub['parent_id'];
    if (isset($isMainReply[$parentId])) {
        // 父回复是主回复，直接挂在这层
        $subReplies[$parentId][] = $sub;
    } else {
        // 父回复也是楼中楼，需要嵌套显示
        $nestedSubReplies[$parentId][] = $sub;
    }
}

// 处理删除回复
$currentUser = getCurrentUser();
if (isset($_GET['delete_reply']) && isLoggedIn()) {
    $replyId = intval($_GET['delete_reply']);
    
    // 获取回复信息
    $reply = db()->queryOne("SELECT * FROM replies WHERE id = ?", [$replyId]);
    
    if ($reply) {
        // 检查权限：管理员或回复作者可以删除
        if ($currentUser && ($currentUser['role'] == 1 || $currentUser['id'] == $reply['user_id'])) {
            // 软删除回复
            db()->execute("UPDATE replies SET status = 0 WHERE id = ?", [$replyId]);
            
            // 更新帖子回复数
            db()->execute("UPDATE posts SET reply_count = reply_count - 1 WHERE id = ?", [$postId]);
            
            // 更新用户回复数
            db()->execute("UPDATE users SET reply_count = reply_count - 1 WHERE id = ?", [$reply['user_id']]);
            
            setFlashMessage('success', '回复已删除');
        } else {
            setFlashMessage('error', '您没有权限删除此回复');
        }
    } else {
        setFlashMessage('error', '回复不存在');
    }
    
    redirect(SITE_URL . '/post.php?id=' . $postId . '&page=' . $page);
}

// 处理回复提交
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isLoggedIn()) {
    $content = trim($_POST['content'] ?? '');
    $csrfToken = $_POST['csrf_token'] ?? '';
    $parentId = isset($_POST['parent_id']) ? intval($_POST['parent_id']) : null;

    if (!validateCsrfToken($csrfToken)) {
        $error = '安全验证失败，请刷新页面重试';
    } elseif (empty($content)) {
        $error = '回复内容不能为空';
    } else {
        $user = getCurrentUser();

        // 创建回复
        if ($parentId) {
            // 楼中楼回复 - 不占用楼层号
            $replyId = db()->insert(
                "INSERT INTO replies (post_id, user_id, content, parent_id, floor_number) VALUES (?, ?, ?, ?, 0)",
                [$postId, $user['id'], $content, $parentId]
            );
        } else {
            // 主回复 - 计算楼层号
            $floorResult = db()->queryOne(
                "SELECT MAX(floor_number) as max_floor FROM replies WHERE post_id = ? AND status = 1 AND parent_id IS NULL",
                [$postId]
            );
            $floorNumber = ($floorResult['max_floor'] ?? 0) + 1;
            
            $replyId = db()->insert(
                "INSERT INTO replies (post_id, user_id, content, floor_number) VALUES (?, ?, ?, ?)",
                [$postId, $user['id'], $content, $floorNumber]
            );
        }

        if ($replyId) {
            // 更新帖子回复数和最后回复时间
            db()->execute(
                "UPDATE posts SET reply_count = reply_count + 1, last_reply_at = NOW(), last_reply_user_id = ? WHERE id = ?",
                [$user['id'], $postId]
            );

            // 更新用户回复数
            db()->execute(
                "UPDATE users SET reply_count = reply_count + 1 WHERE id = ?",
                [$user['id']]
            );

            // 发送回复通知给帖子作者或父回复作者
            try {
                $targetUserId = null;
                $notificationContent = '';
                $targetType = 'post';
                $targetId = $postId;

                if ($parentId) {
                    // 楼中楼回复，通知父回复作者
                    $parentReply = db()->queryOne("SELECT user_id, content FROM replies WHERE id = ?", [$parentId]);
                    if ($parentReply && $parentReply['user_id'] != $user['id']) {
                        $targetUserId = $parentReply['user_id'];
                        $targetType = 'reply';
                        $targetId = $parentId;
                        $notificationContent = '回复: ' . mb_substr($parentReply['content'], 0, 50) . (mb_strlen($parentReply['content']) > 50 ? '...' : '');
                    }
                } else {
                    // 主回复，通知帖子作者
                    $postInfo = db()->queryOne("SELECT user_id, title FROM posts WHERE id = ?", [$postId]);
                    if ($postInfo && $postInfo['user_id'] != $user['id']) {
                        $targetUserId = $postInfo['user_id'];
                        $notificationContent = mb_substr($postInfo['title'], 0, 50) . (mb_strlen($postInfo['title']) > 50 ? '...' : '');
                    }
                }

                // 发送通知
                if ($targetUserId) {
                    try {
                        $tableExists = db()->queryOne("SHOW TABLES LIKE 'notifications'");
                        if (!$tableExists) {
                            db()->execute("CREATE TABLE IF NOT EXISTS notifications (
                                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                                user_id INT UNSIGNED NOT NULL,
                                sender_id INT UNSIGNED DEFAULT NULL,
                                type ENUM('like', 'favorite', 'reply', 'follow') NOT NULL,
                                target_type ENUM('post', 'reply') DEFAULT NULL,
                                target_id INT UNSIGNED DEFAULT NULL,
                                content VARCHAR(255) DEFAULT NULL,
                                is_read TINYINT UNSIGNED DEFAULT 0,
                                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                INDEX idx_user_id (user_id),
                                INDEX idx_is_read (is_read)
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
                        }

                        db()->execute(
                            "INSERT INTO notifications (user_id, sender_id, type, target_type, target_id, content) VALUES (?, ?, 'reply', ?, ?, ?)",
                            [$targetUserId, $user['id'], $targetType, $targetId, $notificationContent]
                        );
                    } catch (Exception $e) {
                        // 记录错误但不影响回复成功
                        error_log('发送回复通知失败: ' . $e->getMessage());
                    }
                }
            } catch (Exception $e) {
                error_log('获取回复通知目标失败: ' . $e->getMessage());
            }

            // 检查勋章解锁条件并发送通知（评论数相关）
            try {
                checkAndNotifyMedalUnlock($user['id']);
            } catch (Exception $e) {
                error_log('检查勋章失败: ' . $e->getMessage());
            }

            setFlashMessage('success', '回复成功！');
            // 计算新回复所在的页码（主回复才需要计算页码，楼中楼在当前页）
            if ($parentId) {
                // 楼中楼回复，留在当前页，跳转到父回复位置
                $anchor = '#reply-' . $parentId;
                $redirectPage = $page;
            } else {
                // 主回复，跳转到最后一页
                $newTotal = $total + 1;
                $redirectPage = ceil($newTotal / $perPage);
                $anchor = '';
            }
            redirect(SITE_URL . '/post.php?id=' . $postId . '&page=' . $redirectPage . $anchor);
        } else {
            $error = '回复失败，请稍后重试';
        }
    }
}

$pageTitle = $post['title'];
include __DIR__ . '/templates/header.php';
?>

<div class="post-detail">
    <div class="post-header">
        <h1>
            <?php if ($post['is_top']): ?>
                <span class="tag tag-top">置顶</span>
            <?php endif; ?>
            <?php if ($post['is_essence']): ?>
                <span class="tag tag-essence">精华</span>
            <?php endif; ?>
            <?php echo e($post['title']); ?>
        </h1>
        <div class="post-author">
            <div class="avatar">
                <?php if ($post['avatar']): ?>
                    <img src="<?php echo e($post['avatar']); ?>" alt="<?php echo e($post['username']); ?>">
                <?php else: ?>
                    <i class="fas fa-user"></i>
                <?php endif; ?>
            </div>
            <div class="post-author-info">
                <h4><a href="user.php?id=<?php echo $post['user_id']; ?>"><?php echo e($post['username']); ?></a></h4>
                <span>
                    <i class="fas fa-folder"></i> <?php echo e($post['category_name']); ?> •
                    <i class="fas fa-clock"></i> <?php echo formatTime($post['created_at']); ?> •
                    <i class="fas fa-eye"></i> <?php echo $post['view_count']; ?> 浏览 •
                    <i class="fas fa-comment"></i> <?php echo $post['reply_count']; ?> 回复
                </span>
            </div>
        </div>
    </div>
    <div class="post-body">
        <?php echo $post['content']; ?>
    </div>
    
    <!-- 点赞和收藏按钮 -->
    <?php if (isLoggedIn()): ?>
        <?php
        $isLiked = isLiked($currentUser['id'], 'post', $postId);
        $isFavorited = isFavorited($currentUser['id'], 'post', $postId);
        $likeCount = getLikeCount('post', $postId);
        $favoriteCount = getFavoriteCount('post', $postId);
        ?>
        <div class="post-actions" style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee; display: flex; gap: 15px;">
            <button type="button" class="btn-action like-btn <?php echo $isLiked ? 'active' : ''; ?>"
                    data-type="post" data-id="<?php echo $postId; ?>"
                    style="display: flex; align-items: center; gap: 5px; padding: 8px 15px; border: 1px solid #ddd; border-radius: 20px; background: <?php echo $isLiked ? '#ff6b6b' : '#fff'; ?>; color: <?php echo $isLiked ? '#fff' : '#666'; ?>; cursor: pointer; transition: all 0.3s;">
                <i class="fas fa-thumbs-up"></i>
                <span class="like-count"><?php echo $likeCount; ?></span>
                <span class="like-text"><?php echo $isLiked ? '已赞' : '点赞'; ?></span>
            </button>
            <button type="button" class="btn-action favorite-btn <?php echo $isFavorited ? 'active' : ''; ?>"
                    data-type="post" data-id="<?php echo $postId; ?>"
                    style="display: flex; align-items: center; gap: 5px; padding: 8px 15px; border: 1px solid #ddd; border-radius: 20px; background: <?php echo $isFavorited ? '#ffd700' : '#fff'; ?>; color: <?php echo $isFavorited ? '#fff' : '#666'; ?>; cursor: pointer; transition: all 0.3s;">
                <i class="fas fa-star"></i>
                <span class="favorite-count"><?php echo $favoriteCount; ?></span>
                <span class="favorite-text"><?php echo $isFavorited ? '已收藏' : '收藏'; ?></span>
            </button>
        </div>
    <?php else: ?>
        <div class="post-actions" style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee; display: flex; gap: 15px;">
            <button type="button" onclick="location.href='login.php'" class="btn-action" 
                    style="display: flex; align-items: center; gap: 5px; padding: 8px 15px; border: 1px solid #ddd; border-radius: 20px; background: #fff; color: #666; cursor: pointer;">
                <i class="fas fa-thumbs-up"></i>
                <span><?php echo getLikeCount('post', $postId); ?></span>
                <span>点赞</span>
            </button>
            <button type="button" onclick="location.href='login.php'" class="btn-action" 
                    style="display: flex; align-items: center; gap: 5px; padding: 8px 15px; border: 1px solid #ddd; border-radius: 20px; background: #fff; color: #666; cursor: pointer;">
                <i class="fas fa-star"></i>
                <span><?php echo getFavoriteCount('post', $postId); ?></span>
                <span>收藏</span>
            </button>
        </div>
    <?php endif; ?>
    
    <!-- 管理员操作按钮 -->
    <?php if ($currentUser && $currentUser['role'] >= 1): ?>
        <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #eee;">
            <span style="color: #666; font-size: 13px; margin-right: 10px;"><i class="fas fa-shield-alt"></i> 管理操作:</span>
            <a href="admin/post-edit.php?id=<?php echo $postId; ?>" class="btn btn-sm btn-outline" style="margin-right: 8px;">
                <i class="fas fa-edit"></i> 编辑帖子
            </a>
            <?php if ($post['is_top']): ?>
                <a href="admin/posts.php?action=cancel_top&id=<?php echo $postId; ?>" class="btn btn-sm btn-outline" style="margin-right: 8px;">
                    <i class="fas fa-thumbtack"></i> 取消置顶
                </a>
            <?php else: ?>
                <a href="admin/posts.php?action=set_top&id=<?php echo $postId; ?>" class="btn btn-sm btn-outline" style="margin-right: 8px;">
                    <i class="fas fa-thumbtack"></i> 置顶
                </a>
            <?php endif; ?>
            <?php if ($post['is_essence']): ?>
                <a href="admin/posts.php?action=cancel_essence&id=<?php echo $postId; ?>" class="btn btn-sm btn-outline" style="margin-right: 8px;">
                    <i class="fas fa-star"></i> 取消精华
                </a>
            <?php else: ?>
                <a href="admin/posts.php?action=set_essence&id=<?php echo $postId; ?>" class="btn btn-sm btn-outline" style="margin-right: 8px;">
                    <i class="fas fa-star"></i> 精华
                </a>
            <?php endif; ?>
            <a href="admin/posts.php?action=delete&id=<?php echo $postId; ?>" class="btn btn-sm btn-outline" style="color: #e74c3c;" onclick="return confirm('确定要删除此帖子吗？')">
                <i class="fas fa-trash"></i> 删除
            </a>
        </div>
    <?php endif; ?>
</div>

<!-- 快速导航按钮 -->
<div id="quick-nav" style="position: fixed; right: 20px; bottom: 100px; z-index: 100; display: flex; flex-direction: column; gap: 10px; opacity: 0; visibility: hidden; transition: all 0.3s;">
    <a href="#reply-form" onclick="smoothScrollTo('reply-form'); return false;" 
       style="width: 45px; height: 45px; background: #3498db; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 10px rgba(0,0,0,0.2); text-decoration: none; transition: all 0.3s; transform: scale(0.8);" 
       onmouseover="this.style.transform='scale(1.1)'; this.style.boxShadow='0 4px 15px rgba(0,0,0,0.3)';"
       onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 2px 10px rgba(0,0,0,0.2)';"
       title="到最底部">
        <i class="fas fa-arrow-down"></i>
    </a>
    <a href="#" onclick="smoothScrollToTop(); return false;" 
       style="width: 45px; height: 45px; background: #fff; color: #666; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 10px rgba(0,0,0,0.2); text-decoration: none; transition: all 0.3s; transform: scale(0.8);" 
       onmouseover="this.style.transform='scale(1.1)'; this.style.boxShadow='0 4px 15px rgba(0,0,0,0.3)';"
       onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 2px 10px rgba(0,0,0,0.2)';"
       title="回到顶部">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>

<!-- 回复列表 -->
<div class="card" style="margin-top: 20px;">
    <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
        <h2><i class="fas fa-comments"></i> 回复 (<?php echo $total; ?>)</h2>
        <?php if (!empty($replies)): ?>
            <div style="display: flex; gap: 15px; align-items: center;">
                <a href="#reply-form" style="color: #3498db; font-size: 14px;">
                    <i class="fas fa-arrow-down"></i> 去回复
                </a>
                <a href="javascript:void(0)" onclick="toggleAllReplies()" id="toggle-all-btn" style="color: #666; font-size: 14px;">
                    <i class="fas fa-chevron-down" id="toggle-all-icon"></i>
                    <span id="toggle-all-text">收起全部回复</span>
                </a>
            </div>
        <?php endif; ?>
    </div>
    <div class="reply-list" id="all-replies-container">
        <?php if (empty($replies)): ?>
            <div style="padding: 40px; text-align: center; color: #666;">
                <i class="fas fa-comment-slash" style="font-size: 48px; margin-bottom: 15px;"></i>
                <p>还没有回复，快来抢沙发吧！</p>
            </div>
        <?php else: ?>
            <?php foreach ($replies as $reply):
                $highlightReplyId = isset($_GET['highlight']) ? str_replace('reply-', '', $_GET['highlight']) : '';
                $isHighlighted = $highlightReplyId == $reply['id'];
            ?>
                <div class="reply-item <?php echo $isHighlighted ? 'highlight-reply' : ''; ?>" id="reply-<?php echo $reply['id']; ?>" data-reply-id="<?php echo $reply['id']; ?>">
                    <div class="reply-avatar">
                        <div class="avatar">
                            <?php if ($reply['avatar']): ?>
                                <img src="<?php echo e($reply['avatar']); ?>" alt="<?php echo e($reply['username']); ?>">
                            <?php else: ?>
                                <i class="fas fa-user"></i>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="reply-content">
                        <div class="reply-header">
                            <div>
                                <span class="reply-author">
                                    <a href="user.php?id=<?php echo $reply['user_id']; ?>"><?php echo e($reply['username']); ?></a>
                                </span>
                                <span class="reply-time"><?php echo formatTime($reply['created_at']); ?></span>
                            </div>
                            <span class="floor-number"><?php echo $reply['floor_number']; ?>楼</span>
                        </div>
                        <div class="reply-body">
                            <?php echo $reply['content']; ?>
                        </div>
                        
                        <!-- 回复的点赞和收藏按钮 -->
                        <?php if (isLoggedIn()): ?>
                            <?php
                            $replyIsLiked = isLiked($currentUser['id'], 'reply', $reply['id']);
                            $replyIsFavorited = isFavorited($currentUser['id'], 'reply', $reply['id']);
                            $replyLikeCount = getLikeCount('reply', $reply['id']);
                            $replyFavoriteCount = getFavoriteCount('reply', $reply['id']);
                            ?>
                            <div class="reply-actions" style="margin-top: 10px; display: flex; gap: 10px;">
                                <button type="button" class="btn-action like-btn <?php echo $replyIsLiked ? 'active' : ''; ?>" 
                                        data-type="reply" data-id="<?php echo $reply['id']; ?>"
                                        style="display: flex; align-items: center; gap: 3px; padding: 5px 10px; border: 1px solid #ddd; border-radius: 15px; background: <?php echo $replyIsLiked ? '#ff6b6b' : '#fff'; ?>; color: <?php echo $replyIsLiked ? '#fff' : '#666'; ?>; cursor: pointer; font-size: 12px; transition: all 0.3s;">
                                    <i class="fas fa-thumbs-up"></i>
                                    <span class="like-count"><?php echo $replyLikeCount; ?></span>
                                </button>
                                <button type="button" class="btn-action favorite-btn <?php echo $replyIsFavorited ? 'active' : ''; ?>" 
                                        data-type="reply" data-id="<?php echo $reply['id']; ?>"
                                        style="display: flex; align-items: center; gap: 3px; padding: 5px 10px; border: 1px solid #ddd; border-radius: 15px; background: <?php echo $replyIsFavorited ? '#ffd700' : '#fff'; ?>; color: <?php echo $replyIsFavorited ? '#fff' : '#666'; ?>; cursor: pointer; font-size: 12px; transition: all 0.3s;">
                                    <i class="fas fa-star"></i>
                                    <span class="favorite-count"><?php echo $replyFavoriteCount; ?></span>
                                </button>
                            </div>
                        <?php else: ?>
                            <div class="reply-actions" style="margin-top: 10px; display: flex; gap: 10px;">
                                <button type="button" onclick="location.href='login.php'" class="btn-action" 
                                        style="display: flex; align-items: center; gap: 3px; padding: 5px 10px; border: 1px solid #ddd; border-radius: 15px; background: #fff; color: #666; cursor: pointer; font-size: 12px;">
                                    <i class="fas fa-thumbs-up"></i>
                                    <span><?php echo getLikeCount('reply', $reply['id']); ?></span>
                                </button>
                                <button type="button" onclick="location.href='login.php'" class="btn-action" 
                                        style="display: flex; align-items: center; gap: 3px; padding: 5px 10px; border: 1px solid #ddd; border-radius: 15px; background: #fff; color: #666; cursor: pointer; font-size: 12px;">
                                    <i class="fas fa-star"></i>
                                    <span><?php echo getFavoriteCount('reply', $reply['id']); ?></span>
                                </button>
                            </div>
                        <?php endif; ?>
                        
                        <!-- 楼中楼回复（平级显示） -->
                        <?php if (isset($subReplies[$reply['id']]) && !empty($subReplies[$reply['id']])): ?>
                            <div style="margin-top: 10px;">
                                <!-- 折叠按钮 -->
                                <a href="javascript:void(0)" onclick="toggleSubReplies(<?php echo $reply['id']; ?>)" 
                                   id="toggle-btn-<?php echo $reply['id']; ?>"
                                   style="color: #666; font-size: 13px; display: inline-flex; align-items: center; gap: 5px;">
                                    <i class="fas fa-chevron-down" id="toggle-icon-<?php echo $reply['id']; ?>"></i>
                                    <span id="toggle-text-<?php echo $reply['id']; ?>">收起回复 (<?php echo count($subReplies[$reply['id']]); ?>)</span>
                                </a>
                            </div>
                            <div class="sub-replies" id="sub-replies-<?php echo $reply['id']; ?>" style="margin-top: 10px; padding-left: 20px; border-left: 3px solid #e0e0e0;">
                                <?php foreach ($subReplies[$reply['id']] as $subReply): ?>
                                    <div class="sub-reply" id="reply-<?php echo $subReply['id']; ?>" style="padding: 12px 0; border-bottom: 1px solid #f0f0f0;">
                                        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 5px;">
                                            <div class="avatar" style="width: 24px; height: 24px;">
                                                <?php if ($subReply['avatar']): ?>
                                                    <img src="<?php echo e($subReply['avatar']); ?>" style="width: 100%; height: 100%; border-radius: 50%;">
                                                <?php else: ?>
                                                    <i class="fas fa-user" style="font-size: 12px;"></i>
                                                <?php endif; ?>
                                            </div>
                                            <strong style="font-size: 13px;"><a href="user.php?id=<?php echo $subReply['user_id']; ?>"><?php echo e($subReply['username']); ?></a></strong>
                                            <span style="color: #666; font-size: 12px;">
                                                回复 <a href="user.php?id=<?php echo $reply['user_id']; ?>" style="color: #3498db;">@<?php echo e($parentNames[$subReply['parent_id']] ?? $reply['username']); ?></a>
                                            </span>
                                            <span style="color: #999; font-size: 12px;">• <?php echo formatTime($subReply['created_at']); ?></span>
                                            <!-- 单条折叠按钮 -->
                                            <a href="javascript:void(0)" onclick="toggleSingleReply(<?php echo $subReply['id']; ?>)" 
                                               style="color: #999; font-size: 11px; margin-left: auto;">
                                                <i class="fas fa-minus-square" id="single-icon-<?php echo $subReply['id']; ?>"></i>
                                            </a>
                                        </div>
                                        <div id="reply-content-<?php echo $subReply['id']; ?>">
                                            <div style="font-size: 14px; padding-left: 32px;">
                                                <?php echo $subReply['content']; ?>
                                            </div>
                                            <?php if (isLoggedIn()): ?>
                                                <div style="padding-left: 32px; margin-top: 5px;">
                                                    <a href="javascript:void(0)" onclick="showReplyForm(<?php echo $subReply['id']; ?>, '<?php echo e($subReply['username']); ?>')" 
                                                       style="color: #3498db; font-size: 12px; margin-right: 10px;">
                                                        <i class="fas fa-reply"></i> 回复
                                                    </a>
                                                    <?php if ($currentUser && ($currentUser['role'] >= 1 || $currentUser['id'] == $subReply['user_id'])): ?>
                                                        <a href="admin/reply-edit.php?id=<?php echo $subReply['id']; ?>" 
                                                           style="color: #666; font-size: 12px; margin-right: 10px;">
                                                            <i class="fas fa-edit"></i> 编辑
                                                        </a>
                                                        <a href="?id=<?php echo $postId; ?>&delete_reply=<?php echo $subReply['id']; ?>&page=<?php echo $page; ?>" 
                                                           style="color: #e74c3c; font-size: 12px;"
                                                           onclick="return confirm('确定要删除这条回复吗？')">
                                                            <i class="fas fa-trash"></i> 删除
                                                        </a>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <!-- 楼中楼的回复表单 -->
                                            <div id="reply-form-<?php echo $subReply['id']; ?>" style="display: none; margin-top: 10px; margin-left: 32px; padding: 10px; background: #e8f4fd; border-radius: 4px;">
                                                <form method="POST" action="">
                                                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                                    <input type="hidden" name="parent_id" value="<?php echo $subReply['id']; ?>">
                                                    <div class="form-group">
                                                        <textarea name="content" class="form-control" rows="2" placeholder="回复 <?php echo e($subReply['username']); ?>..." required></textarea>
                                                    </div>
                                                    <div style="display: flex; gap: 10px;">
                                                        <button type="submit" class="btn btn-sm btn-primary">发表</button>
                                                        <button type="button" class="btn btn-sm btn-outline" onclick="hideReplyForm(<?php echo $subReply['id']; ?>)">取消</button>
                                                    </div>
                                                </form>
                                            </div>
                                            
                                            <!-- 嵌套的楼中楼回复（主回复回复楼中楼时嵌套显示） -->
                                            <?php if (isset($nestedSubReplies[$subReply['id']]) && !empty($nestedSubReplies[$subReply['id']])): ?>
                                                <div style="margin-top: 10px; margin-left: 32px; padding: 10px; background: #f5f5f5; border-radius: 4px; border-left: 3px solid #3498db;">
                                                    <?php foreach ($nestedSubReplies[$subReply['id']] as $nestedReply): ?>
                                                        <div style="padding: 8px 0; border-bottom: 1px solid #eee;">
                                                            <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 3px;">
                                                                <div class="avatar" style="width: 20px; height: 20px;">
                                                                    <?php if ($nestedReply['avatar']): ?>
                                                                        <img src="<?php echo e($nestedReply['avatar']); ?>" style="width: 100%; height: 100%; border-radius: 50%;">
                                                                    <?php else: ?>
                                                                        <i class="fas fa-user" style="font-size: 10px;"></i>
                                                                    <?php endif; ?>
                                                                </div>
                                                                <strong style="font-size: 12px;"><a href="user.php?id=<?php echo $nestedReply['user_id']; ?>"><?php echo e($nestedReply['username']); ?></a></strong>
                                                                <span style="color: #666; font-size: 11px;">回复 @<?php echo e($parentNames[$nestedReply['parent_id']] ?? '未知'); ?></span>
                                                                <span style="color: #999; font-size: 11px;">• <?php echo formatTime($nestedReply['created_at']); ?></span>
                                                            </div>
                                                            <div style="font-size: 13px; padding-left: 26px;">
                                                                <?php echo nl2br(e($nestedReply['content'])); ?>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <!-- 折叠后的简洁显示 -->
                                        <div id="reply-collapsed-<?php echo $subReply['id']; ?>" style="display: none; padding-left: 32px; font-size: 13px; color: #666;">
                                            <a href="javascript:void(0)" onclick="toggleSingleReply(<?php echo $subReply['id']; ?>)" style="color: #3498db;">
                                                [已折叠] <?php echo e(truncate(strip_tags($subReply['content']), 30)); ?>
                                            </a>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <div style="margin-top: 10px;">
                            <?php if (isLoggedIn()): ?>
                                <a href="javascript:void(0)" onclick="showReplyForm(<?php echo $reply['id']; ?>, '<?php echo e($reply['username']); ?>')" 
                                   style="color: #3498db; font-size: 13px; margin-right: 15px;">
                                    <i class="fas fa-reply"></i> 回复
                                </a>
                            <?php endif; ?>
                            <?php if ($currentUser && ($currentUser['role'] >= 1 || $currentUser['id'] == $reply['user_id'])): ?>
                                <a href="admin/reply-edit.php?id=<?php echo $reply['id']; ?>" 
                                   style="color: #666; font-size: 13px; margin-right: 15px;">
                                    <i class="fas fa-edit"></i> 编辑
                                </a>
                                <a href="?id=<?php echo $postId; ?>&delete_reply=<?php echo $reply['id']; ?>&page=<?php echo $page; ?>" 
                                   style="color: #e74c3c; font-size: 13px;"
                                   onclick="return confirm('确定要删除这条回复吗？')">
                                    <i class="fas fa-trash"></i> 删除
                                </a>
                            <?php endif; ?>
                        </div>
                        
                        <!-- 楼中楼回复表单 -->
                        <div id="reply-form-<?php echo $reply['id']; ?>" style="display: none; margin-top: 15px; padding: 15px; background: #f0f8ff; border-radius: 4px;">
                            <form method="POST" action="" class="reply-form-sub" data-reply-id="<?php echo $reply['id']; ?>">
                                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                <input type="hidden" name="parent_id" value="<?php echo $reply['id']; ?>">
                                <input type="hidden" name="content" class="reply-content-input-<?php echo $reply['id']; ?>">
                                <div class="form-group">
                                    <div id="reply-editor-<?php echo $reply['id']; ?>" class="reply-editor-sub" style="min-height: 120px; border: 1px solid #ddd; border-radius: 8px; background: white;"></div>
                                    <div class="reply-error-<?php echo $reply['id']; ?>" style="color: #e74c3c; font-size: 13px; margin-top: 5px; display: none;">回复内容至少5个字符</div>
                                </div>
                                <div style="display: flex; gap: 10px;">
                                    <button type="submit" class="btn btn-sm btn-primary">发表回复</button>
                                    <button type="button" class="btn btn-sm btn-outline" onclick="hideReplyForm(<?php echo $reply['id']; ?>)">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<?php if ($total > $perPage): ?>
    <?php echo pagination($total, $page, $perPage, 'post.php?id=' . $postId); ?>
<?php endif; ?>

<!-- 回复表单 -->
<?php if (isLoggedIn()): ?>
    <div class="card" style="margin-top: 20px;">
        <div class="card-header">
            <h2><i class="fas fa-reply"></i> 发表回复</h2>
        </div>
        <div class="card-body">
            <?php if ($error): ?>
                <div class="alert alert-error"><?php echo e($error); ?></div>
            <?php endif; ?>

            <form method="POST" action="" class="reply-form-main" id="reply-form">
                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                <input type="hidden" name="content" class="reply-content-input">

                <div class="form-group">
                    <div class="reply-editor-container" style="height: 200px; border: 1px solid #ddd; border-radius: 8px;"></div>
                    <div class="reply-content-error" style="color: #e74c3c; font-size: 14px; margin-top: 5px; display: none;">回复内容至少5个字符</div>
                </div>

                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-paper-plane"></i> 发表回复
                </button>
            </form>
        </div>
    </div>
<?php else: ?>
    <div class="card" style="margin-top: 20px; text-align: center; padding: 30px;">
        <p style="margin-bottom: 15px;">登录后才能回复</p>
        <a href="login.php" class="btn btn-primary">立即登录</a>
        <a href="register.php" class="btn btn-outline" style="margin-left: 10px;">注册账号</a>
    </div>
<?php endif; ?>

<?php if (isLoggedIn()): ?>
<!-- 回复富文本编辑器脚本 -->
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<style>
    .reply-editor-container .ql-toolbar,
    [class*="reply-editor-"] .ql-toolbar {
        border-radius: 8px 8px 0 0;
        border-color: #ddd !important;
        background: #f8f9fa;
    }
    .reply-editor-container .ql-container,
    [class*="reply-editor-"] .ql-container {
        border-radius: 0 0 8px 8px;
        border-color: #ddd !important;
    }
    .reply-editor-container .ql-editor {
        min-height: 150px;
    }
    .reply-editor-sub .ql-editor {
        min-height: 80px;
    }
    .reply-editor-sub {
        height: auto !important;
    }
    .reply-editor-sub .ql-container {
        height: auto;
    }
    .ql-snow .ql-picker.ql-font .ql-picker-label::before,
    .ql-snow .ql-picker.ql-font .ql-picker-item::before {
        content: '字体';
    }
    .ql-snow .ql-picker.ql-size .ql-picker-label::before,
    .ql-snow .ql-picker.ql-size .ql-picker-item::before {
        content: '字号';
    }
</style>
<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script>
    // 表情列表
    var replyEmojis = ['😀','😃','😄','😁','😅','😂','🤣','😊','😇','🙂','🙃','😉','😌','😍','🥰','😘','😗','😙','😚','😋','😛','😝','😜','🤪','🤨','🧐','🤓','😎','🥸','🤩','🥳','😏','😒','😞','😔','😟','😕','🙁','☹️','😣','😖','😫','😩','🥺','😢','😭','😤','😠','😡','🤬','🤯','😳','🥵','🥶','😱','😨','😰','😥','😓','🤗','🤔','🤭','🤫','🤥','😶','😐','😑','😬','🙄','😯','😦','😧','😮','😲','🥱','😴','🤤','😪','😵','🤐','🥴','🤢','🤮','🤧','😷','🤒','🤕','🤑','🤠','😈','👿','👹','👺','🤡','💩','👻','💀','☠️','👽','👾','🤖','🎃','😺','😸','😹','😻','😼','😽','🙀','😿','😾','👍','👎','👏','🙌','👐','🤲','🤝','✊','👊','🤞','✌️','🤟','🤘','👌','🤏','👈','👉','👆','👇','☝️','✋','🤚','🖐️','🖖','👋','🤙','💪','🦾','✍️','🙏','👂','👃','🧠','👀','👁️','👅','👄','❤️','🧡','💛','💚','💙','💜','🖤','🤍','🤎','💔','❣️','💕','💞','💓','💗','💖','💘','💝','💟'];

    // 创建表情选择器
    function createEmojiPickerForEditor(editor, toolbarContainer) {
        var picker = document.createElement('div');
        picker.className = 'emoji-picker-dropdown';
        picker.style.cssText = 'position: absolute; background: white; border: 1px solid #ddd; border-radius: 8px; padding: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 1000; max-width: 280px; max-height: 200px; overflow-y: auto; display: none;';

        replyEmojis.forEach(function(emoji) {
            var span = document.createElement('span');
            span.style.cssText = 'display: inline-block; padding: 4px; cursor: pointer; font-size: 18px; transition: transform 0.2s;';
            span.textContent = emoji;
            span.onmouseover = function() { this.style.transform = 'scale(1.2)'; };
            span.onmouseout = function() { this.style.transform = 'scale(1)'; };
            span.onclick = function() {
                var range = editor.getSelection(true);
                editor.insertText(range.index, emoji);
                editor.setSelection(range.index + emoji.length);
                picker.style.display = 'none';
            };
            picker.appendChild(span);
        });

        // 将选择器添加到 toolbar 而不是编辑器容器
        toolbarContainer.appendChild(picker);
        return picker;
    }

    // 初始化主回复编辑器
    var mainReplyEditor = null;
    if (document.querySelector('.reply-editor-container')) {
        mainReplyEditor = new Quill('.reply-editor-container', {
            theme: 'snow',
            placeholder: '发表你的回复...',
            modules: {
                toolbar: [
                    [{ 'font': [] }, { 'size': ['small', false, 'large', 'huge'] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'align': [] }],
                    ['link', 'image'],
                    ['emoji'],
                    ['clean']
                ]
            }
        });

        var mainToolbar = mainReplyEditor.getModule('toolbar');
        var mainToolbarElem = document.querySelector('.reply-editor-container').previousElementSibling;
        if (!mainToolbarElem || !mainToolbarElem.classList.contains('ql-toolbar')) {
            mainToolbarElem = document.querySelector('.reply-editor-container').parentElement.querySelector('.ql-toolbar');
        }
        var mainPicker = createEmojiPickerForEditor(mainReplyEditor, mainToolbarElem || document.body);
        mainToolbar.addHandler('emoji', function() {
            mainPicker.style.display = mainPicker.style.display === 'none' ? 'block' : 'none';
        });

        // 自定义图片上传处理
        mainToolbar.addHandler('image', function() {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/jpeg,image/png,image/gif,image/webp');
            input.onchange = function() {
                var file = input.files[0];
                if (!file) return;

                if (file.size > 5 * 1024 * 1024) {
                    alert('图片大小不能超过 5MB');
                    return;
                }

                var range = mainReplyEditor.getSelection(true);
                mainReplyEditor.insertText(range.index, '正在上传...', { 'color': '#999', 'italic': true });

                var formData = new FormData();
                formData.append('image', file);

                fetch('<?php echo SITE_URL; ?>/api/upload-image.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    mainReplyEditor.deleteText(range.index, 7);
                    if (data.error) {
                        alert(data.error);
                    } else if (data.url) {
                        mainReplyEditor.insertEmbed(range.index, 'image', data.url);
                        mainReplyEditor.setSelection(range.index + 1);
                    }
                })
                .catch(error => {
                    mainReplyEditor.deleteText(range.index, 7);
                    alert('上传失败，请重试');
                });
            };
            input.click();
        });

        // 主回复表单提交
        document.querySelector('.reply-form-main').addEventListener('submit', function(e) {
            var content = mainReplyEditor.getText().trim();
            var htmlContent = mainReplyEditor.root.innerHTML;
            var errorDiv = this.querySelector('.reply-content-error');

            if (content.length < 5) {
                e.preventDefault();
                errorDiv.style.display = 'block';
                return false;
            }
            errorDiv.style.display = 'none';
            this.querySelector('.reply-content-input').value = htmlContent;
        });
    }

    // 存储子回复编辑器实例
    var subReplyEditors = {};

    // 初始化子回复编辑器
    function initSubReplyEditor(replyId) {
        var editorContainer = document.getElementById('reply-editor-' + replyId);
        if (!editorContainer || subReplyEditors[replyId]) {
            console.log('编辑器已初始化或容器不存在:', replyId);
            return;
        }

        console.log('初始化编辑器:', replyId, '容器:', editorContainer);

        try {
            var editor = new Quill('#reply-editor-' + replyId, {
                theme: 'snow',
                placeholder: '回复...',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline'],
                        ['link'],
                        ['clean']
                    ]
                }
            });

            console.log('编辑器创建成功:', replyId);
            subReplyEditors[replyId] = editor;

            // 聚焦编辑器
            setTimeout(function() {
                editor.focus();
                console.log('编辑器已聚焦:', replyId);
            }, 100);

            // 表单提交处理
            var form = document.querySelector('.reply-form-sub[data-reply-id="' + replyId + '"]');
            if (form) {
                form.addEventListener('submit', function(e) {
                    var content = editor.getText().trim();
                    var htmlContent = editor.root.innerHTML;
                    var errorDiv = form.querySelector('.reply-error-' + replyId);

                    if (content.length < 5) {
                        e.preventDefault();
                        errorDiv.style.display = 'block';
                        return false;
                    }
                    errorDiv.style.display = 'none';
                    form.querySelector('.reply-content-input-' + replyId).value = htmlContent;
                });
            }
        } catch (e) {
            console.error('编辑器初始化失败:', replyId, e);
        }
    }

    // 修改显示回复表单函数，初始化编辑器
    window.showReplyForm = function(replyId, username) {
        // 隐藏所有其他回复表单
        document.querySelectorAll('[id^="reply-form-"]').forEach(function(el) {
            el.style.display = 'none';
        });
        // 显示当前回复表单
        var form = document.getElementById('reply-form-' + replyId);
        if (form) {
            form.style.display = 'block';
            // 延迟初始化编辑器，确保容器可见且渲染完成
            setTimeout(function() {
                initSubReplyEditor(replyId);
            }, 200);
        }
    };
</script>

<!-- 图片查看器 -->
<div id="image-viewer" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 10000; justify-content: center; align-items: center;">
    <img id="viewer-image" src="" style="max-width: 70%; max-height: 70%; object-fit: contain; cursor: zoom-in; transition: transform 0.3s;">
    <button id="viewer-close" style="position: absolute; top: 20px; right: 20px; width: 50px; height: 50px; background: rgba(255,255,255,0.2); border: none; border-radius: 50%; color: white; font-size: 24px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.3s;">
        <i class="fas fa-times"></i>
    </button>
    <div id="viewer-info" style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); color: white; font-size: 14px; background: rgba(0,0,0,0.5); padding: 8px 16px; border-radius: 20px;">
        点击任意处关闭 | 滚轮缩放 | 点击图片放大
    </div>
</div>

<script>
// 图片查看器功能
(function() {
    var viewer = document.getElementById('image-viewer');
    var viewerImg = document.getElementById('viewer-image');
    var closeBtn = document.getElementById('viewer-close');
    var currentScale = 1;

    // 为页面中的所有图片添加点击事件
    document.addEventListener('click', function(e) {
        if (e.target.tagName === 'IMG' && !e.target.closest('#image-viewer')) {
            // 排除头像和小图标
            if (e.target.width > 100 || e.target.closest('.post-body') || e.target.closest('.reply-body')) {
                viewerImg.src = e.target.src;
                viewer.style.display = 'flex';
                currentScale = 1;
                viewerImg.style.transform = 'scale(1)';
                viewerImg.style.cursor = 'zoom-in';
            }
        }
    });

    // 关闭查看器
    function closeViewer() {
        viewer.style.display = 'none';
        viewerImg.src = '';
        currentScale = 1;
    }

    closeBtn.addEventListener('click', closeViewer);
    viewer.addEventListener('click', function(e) {
        if (e.target === viewer) closeViewer();
    });

    // 点击图片缩放
    viewerImg.addEventListener('click', function(e) {
        e.stopPropagation();
        if (currentScale === 1) {
            currentScale = 2;
            viewerImg.style.transform = 'scale(2)';
            viewerImg.style.cursor = 'zoom-out';
        } else {
            currentScale = 1;
            viewerImg.style.transform = 'scale(1)';
            viewerImg.style.cursor = 'zoom-in';
        }
    });

    // 滚轮缩放
    viewer.addEventListener('wheel', function(e) {
        if (viewer.style.display === 'flex') {
            e.preventDefault();
            var delta = e.deltaY > 0 ? -0.1 : 0.1;
            currentScale = Math.max(0.5, Math.min(5, currentScale + delta));
            viewerImg.style.transform = 'scale(' + currentScale + ')';
            viewerImg.style.cursor = currentScale > 1 ? 'zoom-out' : 'zoom-in';
        }
    });

    // ESC键关闭
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && viewer.style.display === 'flex') {
            closeViewer();
        }
    });

    // 鼠标悬停关闭按钮效果
    closeBtn.addEventListener('mouseenter', function() {
        this.style.background = 'rgba(255,255,255,0.4)';
        this.style.transform = 'scale(1.1)';
    });
    closeBtn.addEventListener('mouseleave', function() {
        this.style.background = 'rgba(255,255,255,0.2)';
        this.style.transform = 'scale(1)';
    });
})();

// 点赞和收藏功能
(function() {
    // 防止重复点击的锁
    var processingButtons = new Set();

    // 显示加载状态
    function setLoading(btn, isLoading) {
        if (isLoading) {
            btn.style.opacity = '0.6';
            btn.style.pointerEvents = 'none';
        } else {
            btn.style.opacity = '1';
            btn.style.pointerEvents = 'auto';
        }
    }

    // 处理 fetch 响应
    function handleResponse(response) {
        if (!response.ok) {
            throw new Error('网络请求失败: ' + response.status);
        }
        return response.text().then(function(text) {
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('JSON 解析错误:', text);
                throw new Error('服务器返回无效数据');
            }
        });
    }

    // 更新点赞按钮UI
    function updateLikeButton(btn, data) {
        var countSpan = btn.querySelector('.like-count');
        if (countSpan) countSpan.textContent = data.count;

        if (data.liked) {
            btn.classList.add('active');
            btn.style.background = '#ff6b6b';
            btn.style.color = '#fff';
            var textSpan = btn.querySelector('.like-text');
            if (textSpan) textSpan.textContent = '已赞';
        } else {
            btn.classList.remove('active');
            btn.style.background = '#fff';
            btn.style.color = '#666';
            var textSpan = btn.querySelector('.like-text');
            if (textSpan) textSpan.textContent = '点赞';
        }
    }

    // 更新收藏按钮UI
    function updateFavoriteButton(btn, data) {
        var countSpan = btn.querySelector('.favorite-count');
        if (countSpan) countSpan.textContent = data.count;

        if (data.favorited) {
            btn.classList.add('active');
            btn.style.background = '#ffd700';
            btn.style.color = '#fff';
            var textSpan = btn.querySelector('.favorite-text');
            if (textSpan) textSpan.textContent = '已收藏';
        } else {
            btn.classList.remove('active');
            btn.style.background = '#fff';
            btn.style.color = '#666';
            var textSpan = btn.querySelector('.favorite-text');
            if (textSpan) textSpan.textContent = '收藏';
        }
    }

    // 获取最新点赞状态
    function refreshLikeStatus(btn, targetType, targetId) {
        fetch('<?php echo SITE_URL; ?>/api/like.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=check&target_type=' + targetType + '&target_id=' + targetId
        })
        .then(handleResponse)
        .then(function(data) {
            if (data.success) {
                updateLikeButton(btn, data);
            }
        })
        .catch(function(error) {
            console.error('获取点赞状态失败:', error);
        });
    }

    // 获取最新收藏状态
    function refreshFavoriteStatus(btn, targetType, targetId) {
        fetch('<?php echo SITE_URL; ?>/api/favorite.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=check&target_type=' + targetType + '&target_id=' + targetId
        })
        .then(handleResponse)
        .then(function(data) {
            if (data.success) {
                updateFavoriteButton(btn, data);
            }
        })
        .catch(function(error) {
            console.error('获取收藏状态失败:', error);
        });
    }

    // 点赞按钮点击事件
    document.querySelectorAll('.like-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var btnId = this.dataset.type + '-' + this.dataset.id;

            // 防止重复点击
            if (processingButtons.has(btnId)) {
                return;
            }
            processingButtons.add(btnId);

            var targetType = this.dataset.type;
            var targetId = this.dataset.id;
            var isLiked = this.classList.contains('active');
            var action = isLiked ? 'unlike' : 'like';
            var btn = this;

            setLoading(btn, true);

            // 添加超时控制
            var controller = new AbortController();
            var timeoutId = setTimeout(function() {
                controller.abort();
            }, 10000); // 10秒超时

            fetch('<?php echo SITE_URL; ?>/api/like.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=' + action + '&target_type=' + targetType + '&target_id=' + targetId,
                signal: controller.signal
            })
            .then(handleResponse)
            .then(function(data) {
                clearTimeout(timeoutId);
                if (data.success) {
                    // 先使用返回的数据更新UI
                    updateLikeButton(btn, data);
                    // 然后重新获取最新状态确保数据准确
                    setTimeout(function() {
                        refreshLikeStatus(btn, targetType, targetId);
                    }, 100);
                } else {
                    alert(data.message || '操作失败');
                }
            })
            .catch(function(error) {
                clearTimeout(timeoutId);
                if (error.name === 'AbortError') {
                    alert('请求超时，请检查网络连接');
                } else {
                    console.error('Error:', error);
                    alert('操作失败: ' + error.message);
                }
            })
            .finally(function() {
                setLoading(btn, false);
                processingButtons.delete(btnId);
            });
        });
    });

    // 收藏按钮点击事件
    document.querySelectorAll('.favorite-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var btnId = 'fav-' + this.dataset.type + '-' + this.dataset.id;

            // 防止重复点击
            if (processingButtons.has(btnId)) {
                return;
            }
            processingButtons.add(btnId);

            var targetType = this.dataset.type;
            var targetId = this.dataset.id;
            var isFavorited = this.classList.contains('active');
            var action = isFavorited ? 'unfavorite' : 'favorite';
            var btn = this;

            setLoading(btn, true);

            // 添加超时控制
            var controller = new AbortController();
            var timeoutId = setTimeout(function() {
                controller.abort();
            }, 10000); // 10秒超时

            fetch('<?php echo SITE_URL; ?>/api/favorite.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=' + action + '&target_type=' + targetType + '&target_id=' + targetId,
                signal: controller.signal
            })
            .then(handleResponse)
            .then(function(data) {
                clearTimeout(timeoutId);
                if (data.success) {
                    // 先使用返回的数据更新UI
                    updateFavoriteButton(btn, data);
                    // 然后重新获取最新状态确保数据准确
                    setTimeout(function() {
                        refreshFavoriteStatus(btn, targetType, targetId);
                    }, 100);
                } else {
                    alert(data.message || '操作失败');
                }
            })
            .catch(function(error) {
                clearTimeout(timeoutId);
                if (error.name === 'AbortError') {
                    alert('请求超时，请检查网络连接');
                } else {
                    console.error('Error:', error);
                    alert('操作失败: ' + error.message);
                }
            })
            .finally(function() {
                setLoading(btn, false);
                processingButtons.delete(btnId);
            });
        });
    });
})();

// 快速导航按钮显示/隐藏控制
(function() {
    var quickNav = document.getElementById('quick-nav');
    var scrollThreshold = 300; // 滚动超过300px显示
    
    function toggleQuickNav() {
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        if (scrollTop > scrollThreshold) {
            quickNav.style.opacity = '1';
            quickNav.style.visibility = 'visible';
        } else {
            quickNav.style.opacity = '0';
            quickNav.style.visibility = 'hidden';
        }
    }
    
    // 初始检查
    toggleQuickNav();
    
    // 滚动时检查
    window.addEventListener('scroll', toggleQuickNav, { passive: true });
})();

// 平滑滚动到指定元素
function smoothScrollTo(elementId) {
    var element = document.getElementById(elementId);
    if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
}

// 平滑滚动到顶部
function smoothScrollToTop() {
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// 高亮提示功能
(function() {
    // 检查是否有高亮参数
    var urlParams = new URLSearchParams(window.location.search);
    var highlight = urlParams.get('highlight');
    var fromUser = urlParams.get('from_user');
    var action = urlParams.get('action');

    if (highlight) {
        var element = document.getElementById(highlight);
        if (element) {
            // 滚动到元素
            setTimeout(function() {
                element.scrollIntoView({ behavior: 'smooth', block: 'center' });

                // 添加高亮动画
                element.style.animation = 'highlight-pulse 2s ease-in-out 3';
                element.style.borderRadius = '8px';

                // 显示提示信息
                if (fromUser && action) {
                    var actionText = {
                        'like': '点赞',
                        'favorite': '收藏',
                        'reply': '回复'
                    }[action] || '互动';

                    var toast = document.createElement('div');
                    toast.style.cssText = 'position: fixed; top: 80px; left: 50%; transform: translateX(-50%); background: #3498db; color: white; padding: 12px 24px; border-radius: 25px; font-size: 14px; z-index: 10000; box-shadow: 0 4px 12px rgba(0,0,0,0.2); animation: fade-in-down 0.5s ease;';
                    toast.innerHTML = '<i class="fas fa-info-circle"></i> ' + decodeURIComponent(fromUser) + ' ' + actionText + '了你的' + (highlight.startsWith('reply') ? '回复' : '帖子');
                    document.body.appendChild(toast);

                    // 3秒后移除提示
                    setTimeout(function() {
                        toast.style.animation = 'fade-out-up 0.5s ease';
                        setTimeout(function() {
                            toast.remove();
                        }, 500);
                    }, 3000);
                }

                // 3秒后移除高亮动画
                setTimeout(function() {
                    element.style.animation = '';
                }, 6000);
            }, 500);
        }
    }
})();
</script>

<style>
@keyframes highlight-pulse {
    0% { background-color: transparent; box-shadow: 0 0 0 0 rgba(52, 152, 219, 0.4); }
    50% { background-color: rgba(52, 152, 219, 0.1); box-shadow: 0 0 0 10px rgba(52, 152, 219, 0); }
    100% { background-color: transparent; box-shadow: 0 0 0 0 rgba(52, 152, 219, 0); }
}
.highlight-reply {
    position: relative;
}
.highlight-reply::before {
    content: '';
    position: absolute;
    left: -5px;
    top: -5px;
    right: -5px;
    bottom: -5px;
    border: 2px solid #3498db;
    border-radius: 12px;
    animation: border-pulse 2s ease-in-out 3;
    pointer-events: none;
}
@keyframes border-pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.3; }
}
@keyframes fade-in-down {
    from { opacity: 0; transform: translateX(-50%) translateY(-20px); }
    to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
@keyframes fade-out-up {
    from { opacity: 1; transform: translateX(-50%) translateY(0); }
    to { opacity: 0; transform: translateX(-50%) translateY(-20px); }
}
</style>
<?php endif; ?>

<?php include __DIR__ . '/templates/footer.php'; ?>
