<?php
/**
 * HuSNS - 首页模板 - defaultpro主题
 * 今日头条/动态PC端风格
 * 
 * 布局：顶部导航 + 左侧菜单 + 中间动态流 + 右侧widgets
 */
?>

<!-- 顶部导航栏 -->
<header class="top-navbar">
    <div class="navbar-container">
        <div class="navbar-left">
            <a href="<?php echo $this->url(); ?>" class="logo">
                <span class="logo-icon">📱</span>
                <span class="logo-text">HuSNS</span>
            </a>
            <div class="navbar-search">
                <input type="text" placeholder="搜索动态、用户、话题..." class="search-input" id="navbarSearch">
                <button class="search-btn"><span>🔍</span></button>
            </div>
        </div>
        
        <nav class="navbar-center">
            <a href="<?php echo $this->url(); ?>" class="nav-link <?php echo (!isset($tab) || $tab !== 'following') ? 'active' : ''; ?>">
                <span class="nav-icon">🏠</span>
                <span class="nav-text">首页</span>
            </a>
            <a href="<?php echo $this->url('post/hot'); ?>" class="nav-link">
                <span class="nav-icon">🔥</span>
                <span class="nav-text">热门</span>
            </a>
            <a href="<?php echo $this->url('post/featured'); ?>" class="nav-link">
                <span class="nav-icon">✨</span>
                <span class="nav-text">推荐</span>
            </a>
        </nav>
        
        <div class="navbar-right">
            <?php if (isset($_SESSION['user_id'])): ?>
            <!-- 消息入口 -->
            <a href="<?php echo $this->url('notification'); ?>" class="nav-icon-btn" title="消息">
                <span>💬</span>
                <?php if (isset($unreadCount) && $unreadCount > 0): ?>
                <span class="icon-badge"><?php echo $unreadCount > 99 ? '99+' : $unreadCount; ?></span>
                <?php endif; ?>
            </a>
            <!-- 用户菜单 -->
            <div class="user-menu" id="userMenu">
                <button class="user-menu-btn">
                    <img src="/templates/defaultpro/images/avatar_default.png" alt="" class="user-avatar">
                    <span class="user-name"><?php echo $this->escape($userStats['user']['username'] ?? ''); ?></span>
                    <span class="arrow">▼</span>
                </button>
                <div class="user-dropdown">
                    <a href="<?php echo $this->url('user/profile'); ?>" class="dropdown-item">
                        <span>👤</span> 我的主页
                    </a>
                    <a href="<?php echo $this->url('user/favorites'); ?>" class="dropdown-item">
                        <span>⭐</span> 我的收藏
                    </a>
                    <a href="<?php echo $this->url('user/points'); ?>" class="dropdown-item">
                        <span>💰</span> 积分中心
                    </a>
                    <div class="dropdown-divider"></div>
                    <a href="<?php echo $this->url('user/settings'); ?>" class="dropdown-item">
                        <span>⚙️</span> 设置
                    </a>
                    <a href="<?php echo $this->url('user/logout'); ?>" class="dropdown-item">
                        <span>🚪</span> 退出登录
                    </a>
                </div>
            </div>
            <!-- 发布按钮 -->
            <button class="publish-btn" onclick="showPublishPopup()">
                <span>✏️</span>
                <span>发布</span>
            </button>
            <?php else: ?>
            <a href="<?php echo $this->url('user/login'); ?>" class="nav-link">登录</a>
            <a href="<?php echo $this->url('user/register'); ?>" class="register-btn">注册</a>
            <?php endif; ?>
        </div>
    </div>
</header>

<!-- 主内容区 -->
<div class="main-wrapper">
    <!-- 左侧边栏 -->
    <aside class="sidebar-left">
        <nav class="side-nav">
            <a href="<?php echo $this->url(); ?>" class="side-nav-item <?php echo (!isset($tab) || $tab !== 'following') ? 'active' : ''; ?>">
                <span class="side-nav-icon">🏠</span>
                <span>首页</span>
            </a>
            <a href="<?php echo $this->url('?tab=following'); ?>" class="side-nav-item <?php echo (isset($tab) && $tab === 'following') ? 'active' : ''; ?>">
                <span class="side-nav-icon">❤️</span>
                <span>关注</span>
            </a>
            <a href="<?php echo $this->url('user/profile'); ?>" class="side-nav-item">
                <span class="side-nav-icon">👤</span>
                <span>我的主页</span>
            </a>
            <a href="<?php echo $this->url('user/favorites'); ?>" class="side-nav-item">
                <span class="side-nav-icon">⭐</span>
                <span>收藏</span>
            </a>
            <a href="<?php echo $this->url('user/points'); ?>" class="side-nav-item">
                <span class="side-nav-icon">💰</span>
                <span>积分</span>
            </a>
        </nav>
        
        <!-- 签到入口 -->
        <?php if (isset($_SESSION['user_id'])): ?>
        <div class="sign-in-widget" id="signInCard">
            <div class="sign-in-info">
                <span class="sign-in-label">📅 签到领积分</span>
                <span class="sign-in-streak">连续 <?php echo $signInDays ?? 0; ?> 天</span>
            </div>
            <button class="sign-in-action <?php echo isset($hasSignedIn) && $hasSignedIn ? 'signed' : ''; ?>" id="signInBtn" <?php echo isset($hasSignedIn) && $hasSignedIn ? 'disabled' : ''; ?>>
                <?php echo isset($hasSignedIn) && $hasSignedIn ? '✓ 已签到' : '+ 签到'; ?>
            </button>
        </div>
        <?php endif; ?>
        
        <!-- 快捷入口 -->
        <div class="quick-access">
            <a href="<?php echo $this->url('post/topics'); ?>" class="quick-access-item">
                <span>🏷️</span>
                <span>话题</span>
            </a>
            <a href="<?php echo $this->url('user/search'); ?>" class="quick-access-item">
                <span>🔍</span>
                <span>找人</span>
            </a>
            <a href="<?php echo $this->url('user/recommend'); ?>" class="quick-access-item">
                <span>👥</span>
                <span>推荐</span>
            </a>
        </div>
    </aside>

    <!-- 中间动态区 -->
    <main class="main-content">
        <!-- 发布框 -->
        <?php if (isset($_SESSION['user_id'])): ?>
        <div class="publish-card">
            <div class="publish-user">
                <img src="/templates/defaultpro/images/avatar_default.png" alt="" class="publish-avatar">
            </div>
            <div class="publish-area">
                <textarea class="publish-input" placeholder="有什么新鲜事分享给大家？" rows="2"></textarea>
                <div class="publish-tools">
                    <div class="publish-actions">
                        <button class="tool-btn" title="图片"><span>🖼️</span></button>
                        <button class="tool-btn" title="视频"><span>🎬</span></button>
                        <button class="tool-btn" title="话题"><span>#</span></button>
                        <button class="tool-btn" title="位置"><span>📍</span></button>
                    </div>
                    <button class="publish-submit">发布</button>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- 公告 -->
        <?php if (!empty($announcements)): ?>
        <div class="announcement-bar">
            <span class="announcement-icon">📢</span>
            <div class="announcement-scroll">
                <?php foreach ($announcements as $announcement): ?>
                <span class="announcement-text"><?php echo $announcement['content']; ?></span>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- 置顶动态 -->
        <?php if (!empty($pinnedPost)): ?>
        <article class="post-card post-pinned" data-id="<?php echo $pinnedPost['id']; ?>">
            <div class="post-card-header">
                <a href="<?php echo $this->url('user/profile?id=' . $pinnedPost['user_id']); ?>" class="post-author-avatar">
                    <?php echo $this->avatar($pinnedPost['avatar'] ?? null, $pinnedPost['username'], 44); ?>
                </a>
                <div class="post-author-info">
                    <a href="<?php echo $this->url('user/profile?id=' . $pinnedPost['user_id']); ?>" class="post-author-name"><?php echo $this->escape($pinnedPost['username']); ?></a>
                    <span class="post-time"><?php echo Helper::formatTime($pinnedPost['created_at']); ?></span>
                </div>
                <div class="post-tags">
                    <span class="tag tag-pinned">置顶</span>
                    <?php if (!empty($pinnedPost['is_featured'])): ?>
                    <span class="tag tag-featured">精华</span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="post-card-content">
                <?php echo $pinnedPost['content']; ?>
            </div>
            <?php if (!empty($pinnedPost['images'])): ?>
            <div class="post-images-grid">
                <?php foreach ($pinnedPost['images'] as $index => $image): ?>
                <?php $imagePath = is_array($image) && isset($image['path']) ? $image['path'] : $image; ?>
                <div class="post-image-item <?php echo count($pinnedPost['images']) == 1 ? 'single' : ''; ?>" onclick="previewImage(this.src)">
                    <img src="<?php echo $this->uploadUrl($imagePath); ?>" alt="图片" loading="lazy">
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            <div class="post-card-actions">
                <button class="action-item like-btn <?php echo !empty($pinnedPost['is_liked']) ? 'liked' : ''; ?>" data-id="<?php echo $pinnedPost['id']; ?>">
                    <span class="action-icon">👍</span>
                    <span class="action-count"><?php echo $pinnedPost['likes'] ?? 0; ?></span>
                </button>
                <button class="action-item comment-btn" data-id="<?php echo $pinnedPost['id']; ?>">
                    <span class="action-icon">💬</span>
                    <span class="action-count"><?php echo $pinnedPost['comments'] ?? 0; ?></span>
                </button>
                <button class="action-item repost-btn <?php echo !empty($pinnedPost['is_repost']) ? 'reposted' : ''; ?>" data-id="<?php echo $pinnedPost['id']; ?>">
                    <span class="action-icon">🔄</span>
                    <span class="action-count"><?php echo $pinnedPost['reposts'] ?? 0; ?></span>
                </button>
                <button class="action-item favorite-btn <?php echo !empty($pinnedPost['is_favorited']) ? 'favorited' : ''; ?>" data-id="<?php echo $pinnedPost['id']; ?>">
                    <span class="action-icon">⭐</span>
                </button>
            </div>
        </article>
        <?php endif; ?>

        <!-- 动态列表 -->
        <?php if (empty($posts)): ?>
        <div class="empty-state">
            <div class="empty-icon">📭</div>
            <div class="empty-text">
                <?php if ($tab === 'following'): ?>
                <p>您还没有关注任何人</p>
                <p><a href="<?php echo $this->url('?tab=all'); ?>">查看全站动态</a> 发现更多精彩内容</p>
                <?php else: ?>
                <p>暂无动态，快来发布第一条吧！</p>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
        <?php foreach ($posts as $post): ?>
        <article class="post-card" data-id="<?php echo $post['id']; ?>">
            <div class="post-card-header">
                <a href="<?php echo $this->url('user/profile?id=' . $post['user_id']); ?>" class="post-author-avatar">
                    <?php echo $this->avatar($post['avatar'] ?? null, $post['username'], 44); ?>
                </a>
                <div class="post-author-info">
                    <a href="<?php echo $this->url('user/profile?id=' . $post['user_id']); ?>" class="post-author-name"><?php echo $this->escape($post['username']); ?></a>
                    <span class="post-time"><?php echo $post['time_ago'] ?? Helper::formatTime($post['created_at']); ?></span>
                </div>
                <?php if (!empty($post['is_featured'])): ?>
                <span class="tag tag-featured">精华</span>
                <?php endif; ?>
            </div>
            
            <div class="post-card-content">
                <?php if (!empty($post['content'])): ?>
                <p class="post-text"><?php echo $post['content']; ?></p>
                <?php endif; ?>
                
                <!-- 转发内容 -->
                <?php if (!empty($post['original_post'])): ?>
                <div class="repost-original">
                    <div class="repost-header">
                        <a href="<?php echo $this->url('user/profile?id=' . $post['original_post']['user_id']); ?>" class="repost-author">
                            @<?php echo $this->escape($post['original_post']['username']); ?>
                        </a>
                    </div>
                    <div class="repost-content">
                        <?php if (!empty($post['original_post']['deleted'])): ?>
                        <p style="color:#999;">原文已删除</p>
                        <?php else: ?>
                        <p><?php echo $post['original_post']['content'] ?? ''; ?></p>
                        <?php if (!empty($post['original_post']['images'])): ?>
                        <div class="post-images-grid">
                            <?php foreach ($post['original_post']['images'] as $image): ?>
                            <?php $imagePath = is_array($image) && isset($image['path']) ? $image['path'] : $image; ?>
                            <div class="post-image-item" onclick="previewImage(this.querySelector('img').src)">
                                <img src="<?php echo $this->uploadUrl($imagePath); ?>" alt="图片" loading="lazy">
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
                <?php elseif (empty($post['repost_id'])): ?>
                <!-- 图片 -->
                <?php if (!empty($post['images'])): ?>
                <div class="post-images-grid <?php echo count($post['images']) > 1 ? 'multi' : 'single'; ?>">
                    <?php foreach ($post['images'] as $image): ?>
                    <?php $imagePath = is_array($image) && isset($image['path']) ? $image['path'] : $image; ?>
                    <div class="post-image-item" onclick="previewImage(this.querySelector('img').src)">
                        <img src="<?php echo $this->uploadUrl($imagePath); ?>" alt="图片" loading="lazy">
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                
                <!-- 视频 -->
                <?php if (!empty($post['videos'])): ?>
                <div class="post-videos">
                    <?php foreach ($post['videos'] as $video): ?>
                    <?php
                    if (is_array($video) && isset($video['path'])) {
                        $videoPath = $video['path'];
                        $videoExt = $video['ext'] ?? 'mp4';
                        $videoName = $video['name'] ?? '';
                    } else {
                        $videoPath = $video;
                        $videoExt = 'mp4';
                        $videoName = '';
                    }
                    ?>
                    <div class="post-video-item" onclick="playVideo(this)">
                        <video preload="metadata" playsinline>
                            <source src="<?php echo $this->uploadUrl($videoPath); ?>#t=3" type="video/<?php echo $videoExt; ?>">
                        </video>
                        <div class="video-overlay"><div class="video-play-btn">▶</div></div>
                        <?php if (!empty($videoName)): ?>
                        <div class="video-name-tag"><?php echo $this->escape($videoName); ?></div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                
                <!-- 附件 -->
                <?php if (!empty($post['attachments'])): ?>
                <div class="post-attachments">
                    <?php foreach ($post['attachments'] as $index => $attachment): ?>
                    <a href="<?php echo $this->url('download/attachment?id=' . $post['id'] . '&index=' . $index); ?>" class="attachment-item">
                        <span class="attachment-icon">📄</span>
                        <div class="attachment-info">
                            <span class="attachment-name"><?php echo $this->escape($attachment['name']); ?></span>
                            <span class="attachment-size"><?php echo $this->formatFileSize($attachment['size']); ?></span>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                <?php endif; ?>
            </div>
            
            <div class="post-card-actions">
                <button class="action-item like-btn <?php echo !empty($post['is_liked']) ? 'liked' : ''; ?>" data-id="<?php echo $post['id']; ?>">
                    <span class="action-icon">👍</span>
                    <span class="action-count"><?php echo $post['likes'] ?? 0; ?></span>
                </button>
                <button class="action-item comment-btn" data-id="<?php echo $post['id']; ?>">
                    <span class="action-icon">💬</span>
                    <span class="action-count"><?php echo $post['comments'] ?? 0; ?></span>
                </button>
                <button class="action-item repost-btn <?php echo !empty($post['is_repost']) ? 'reposted' : ''; ?>" data-id="<?php echo $post['id']; ?>">
                    <span class="action-icon">🔄</span>
                    <span class="action-count"><?php echo $post['reposts'] ?? 0; ?></span>
                </button>
                <button class="action-item favorite-btn <?php echo !empty($post['is_favorited']) ? 'favorited' : ''; ?>" data-id="<?php echo $post['id']; ?>">
                    <span class="action-icon">⭐</span>
                </button>
            </div>
        </article>
        <?php endforeach; ?>
        <?php endif; ?>

        <!-- 加载更多 -->
        <?php if (isset($totalPages) && $page < $totalPages): ?>
        <div class="load-more" id="infiniteScrollLoader">
            <div class="loading-spinner"></div>
            <span>加载中...</span>
        </div>
        <?php endif; ?>
    </main>

    <!-- 右侧边栏 -->
    <aside class="sidebar-right">
        <!-- 用户信息卡 -->
        <?php if (isset($_SESSION['user_id']) && $userStats): ?>
        <div class="user-profile-card">
            <div class="profile-cover"></div>
            <div class="profile-info">
                <a href="<?php echo $this->url('user/profile'); ?>" class="profile-avatar">
                    <img src="/templates/defaultpro/images/avatar_default.png" alt="">
                </a>
                <a href="<?php echo $this->url('user/profile'); ?>" class="profile-name"><?php echo $this->escape($userStats['user']['username'] ?? ''); ?></a>
                <p class="profile-bio"><?php echo $this->escape($userStats['user']['bio'] ?? '这个人很懒，什么都没写'); ?></p>
            </div>
            <div class="profile-stats">
                <a href="<?php echo $this->url('user/follows'); ?>" class="stat-item">
                    <span class="stat-num"><?php echo $userStats['posts'] ?? 0; ?></span>
                    <span class="stat-text">动态</span>
                </a>
                <a href="<?php echo $this->url('user/follows'); ?>" class="stat-item">
                    <span class="stat-num"><?php echo $userStats['following'] ?? 0; ?></span>
                    <span class="stat-text">关注</span>
                </a>
                <a href="<?php echo $this->url('user/fans'); ?>" class="stat-item">
                    <span class="stat-num"><?php echo $userStats['followers'] ?? 0; ?></span>
                    <span class="stat-text">粉丝</span>
                </a>
            </div>
        </div>
        <?php else: ?>
        <div class="login-prompt-card">
            <p>登录后体验更多功能</p>
            <div class="login-actions">
                <a href="<?php echo $this->url('user/login'); ?>" class="login-btn">登录</a>
                <a href="<?php echo $this->url('user/register'); ?>" class="register-link">注册</a>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- 推荐关注 -->
        <div class="widget-card">
            <div class="widget-header">
                <h3 class="widget-title">推荐关注</h3>
                <a href="<?php echo $this->url('user/recommend'); ?>" class="widget-more">查看更多</a>
            </div>
            <div class="widget-content" id="recommend-users">
                <?php if (!empty($recommendedUsers)): ?>
                <?php foreach ($recommendedUsers as $user): ?>
                <div class="user-item">
                    <a href="<?php echo $this->url('user/profile?id=' . $user['id']); ?>" class="user-avatar-link">
                        <?php echo $this->avatar($user['avatar'], $user['username'], 48); ?>
                    </a>
                    <div class="user-info">
                        <a href="<?php echo $this->url('user/profile?id=' . $user['id']); ?>" class="user-name"><?php echo $this->escape($user['username']); ?></a>
                        <span class="user-fans"><?php echo $user['followers_count'] ?? 0; ?> 粉丝</span>
                    </div>
                    <button class="follow-btn-widget" data-user-id="<?php echo $user['id']; ?>">关注</button>
                </div>
                <?php endforeach; ?>
                <?php else: ?>
                <div class="widget-empty">暂无推荐用户</div>
                <?php endif; ?>
            </div>
            <button id="refresh-recommend" class="widget-refresh">换一批</button>
        </div>
        
        <!-- 热门话题 -->
        <div class="widget-card">
            <div class="widget-header">
                <h3 class="widget-title">🔥 热门话题</h3>
                <a href="<?php echo $this->url('post/topics'); ?>" class="widget-more">更多</a>
            </div>
            <div class="widget-content" id="hot-topics">
                <?php if (!empty($hotTopics)): ?>
                <div class="topic-list">
                    <?php foreach ($hotTopics as $index => $topic): ?>
                    <a href="<?php echo $this->url('post/topic?keyword=' . urlencode($topic['name'])); ?>" class="topic-item">
                        <span class="topic-rank <?php echo $index < 3 ? 'top-' . ($index + 1) : ''; ?>"><?php echo $index + 1; ?></span>
                        <div class="topic-info">
                            <span class="topic-name">#<?php echo $this->escape($topic['name']); ?>#</span>
                            <?php if (!empty($topic['count'])): ?>
                            <span class="topic-count"><?php echo $topic['count']; ?> 帖</span>
                            <?php endif; ?>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="widget-empty">暂无热门话题</div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- 活跃用户 -->
        <div class="widget-card">
            <div class="widget-header">
                <h3 class="widget-title">🏆 活跃用户</h3>
            </div>
            <div class="widget-content">
                <?php if (!empty($activeUsers)): ?>
                <div class="rank-list">
                    <?php foreach ($activeUsers as $index => $user): ?>
                    <div class="rank-item">
                        <span class="rank-num <?php echo $index < 3 ? 'top-' . ($index + 1) : ''; ?>"><?php echo $index + 1; ?></span>
                        <a href="<?php echo $this->url('user/profile?id=' . $user['id']); ?>">
                            <?php echo $this->avatar($user['avatar'], $user['username'], 32); ?>
                        </a>
                        <div class="rank-info">
                            <a href="<?php echo $this->url('user/profile?id=' . $user['id']); ?>" class="rank-name"><?php echo $this->escape($user['username']); ?></a>
                            <span class="rank-score"><?php echo $user['points'] ?? 0; ?> 积分</span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="widget-empty">暂无数据</div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- 社区统计 -->
        <div class="widget-card">
            <div class="widget-header">
                <h3 class="widget-title">📊 社区数据</h3>
            </div>
            <div class="widget-content">
                <div class="stats-row">
                    <div class="stat-item">
                        <span class="stat-num"><?php echo $totalUsers ?? 0; ?></span>
                        <span class="stat-label">用户</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-num"><?php echo $totalPosts ?? 0; ?></span>
                        <span class="stat-label">动态</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-num"><?php echo $totalComments ?? 0; ?></span>
                        <span class="stat-label">评论</span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 在线用户 -->
        <?php if (!empty($onlineUsers)): ?>
        <div class="widget-card">
            <div class="widget-header">
                <h3 class="widget-title">👥 在线用户</h3>
                <span class="online-count-text"><?php echo $onlineCount ?? 0; ?> 人在线</span>
            </div>
            <div class="widget-content">
                <div class="online-avatars">
                    <?php foreach ($onlineUsers as $onlineUser): ?>
                    <a href="<?php echo $this->url('user/profile?id=' . $onlineUser['id']); ?>" title="<?php echo $this->escape($onlineUser['username']); ?>">
                        <?php echo $this->avatar($onlineUser['avatar'], $onlineUser['username'], 40); ?>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- 热门评论 -->
        <?php if (!empty($hotComments)): ?>
        <div class="widget-card">
            <div class="widget-header">
                <h3 class="widget-title">💬 热门评论</h3>
            </div>
            <div class="widget-content">
                <div class="hot-comments">
                    <?php foreach ($hotComments as $comment): ?>
                    <div class="comment-item">
                        <a href="<?php echo $this->url('user/profile?id=' . $comment['user_id']); ?>">
                            <?php echo $this->avatar($comment['avatar'], $comment['username'], 28); ?>
                        </a>
                        <div class="comment-content">
                            <a href="<?php echo $this->url('post/detail?id=' . $comment['post_id']); ?>" class="comment-text">
                                <?php echo $this->truncate($comment['content'], 40); ?>
                            </a>
                            <span class="comment-likes">👍 <?php echo $comment['likes'] ?? 0; ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- 最新公告 -->
        <?php if (!empty($announcements)): ?>
        <div class="widget-card">
            <div class="widget-header">
                <h3 class="widget-title">📢 最新公告</h3>
            </div>
            <div class="widget-content">
                <?php foreach ($announcements as $announcement): ?>
                <div class="announcement-item">
                    <p class="announcement-text"><?php echo $announcement['content']; ?></p>
                    <span class="announcement-time"><?php echo Helper::formatTime($announcement['created_at'] ?? ''); ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- 底部信息 -->
        <div class="footer-links">
            <a href="#">关于我们</a>
            <a href="#">联系我们</a>
            <a href="https://github.com/huyourui" target="_blank">GitHub</a>
            <div class="copyright">© 2024 HuSNS</div>
        </div>
    </aside>
</div>

<!-- 图片预览弹窗 -->
<div id="imagePreviewModal" onclick="closeImagePreview()" style="display:none;">
    <span class="preview-close" onclick="closeImagePreview()">×</span>
    <img id="previewImage" src="" alt="图片预览">
</div>

<!-- Toast 提示 -->
<div id="toast" style="display:none;"></div>

<script>
// ========== 头条/动态风格 JavaScript ==========

// 图片预览
if (typeof previewImage === 'undefined') {
    function previewImage(src) {
        document.getElementById('previewImage').src = src;
        document.getElementById('imagePreviewModal').style.display = 'flex';
    }
}

if (typeof closeImagePreview === 'undefined') {
    function closeImagePreview() {
        document.getElementById('imagePreviewModal').style.display = 'none';
    }
}

// Toast 提示
if (typeof showToast === 'undefined') {
    function showToast(message, duration) {
        var toast = document.getElementById('toast');
        if (!toast) return;
        toast.textContent = message;
        toast.style.display = 'block';
        toast.classList.add('show');
        setTimeout(function() {
            toast.classList.remove('show');
            setTimeout(function() {
                toast.style.display = 'none';
            }, 300);
        }, duration || 2000);
    }
}

// 用户菜单下拉
document.addEventListener('DOMContentLoaded', function() {
    var userMenuBtn = document.querySelector('.user-menu-btn');
    var userDropdown = document.querySelector('.user-dropdown');
    
    if (userMenuBtn && userDropdown) {
        userMenuBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdown.classList.toggle('show');
        });
        
        document.addEventListener('click', function() {
            userDropdown.classList.remove('show');
        });
    }
    
    // 签到功能
    var signInBtn = document.getElementById('signInBtn');
    if (signInBtn && !signInBtn.disabled) {
        signInBtn.addEventListener('click', function() {
            var btn = this;
            btn.disabled = true;
            btn.textContent = '签到中...';
            
            fetch('<?php echo $this->url('user/signIn'); ?>', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'csrf_token=<?php echo $_SESSION['csrf_token'] ?? Helper::generateToken(); ?>'
            })
            .then(function(res) { return res.json(); })
            .then(function(result) {
                if (result.code === 0) {
                    showToast('签到成功！获得 ' + (result.data?.points || 10) + ' 积分');
                    btn.textContent = '✓ 已签到';
                    btn.classList.add('signed');
                } else {
                    showToast(result.message || '签到失败');
                    btn.disabled = false;
                    btn.textContent = '+ 签到';
                }
            })
            .catch(function(err) {
                console.error('签到失败:', err);
                showToast('网络错误');
                btn.disabled = false;
                btn.textContent = '+ 签到';
            });
        });
    }
    
    // 刷新推荐用户
    var refreshBtn = document.getElementById('refresh-recommend');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            fetch('<?php echo $this->url('user/recommend'); ?>', {
                method: 'GET',
                credentials: 'include'
            })
            .then(function(res) { return res.json(); })
            .then(function(result) {
                if (result.code === 0 && result.data && result.data.users) {
                    var container = document.getElementById('recommend-users');
                    var html = '';
                    result.data.users.forEach(function(user) {
                        html += '<div class=\"user-item\">' +
                            '<a href=\"<?php echo $this->url('user/profile?id='); ?>' + user.id + '\" class=\"user-avatar-link\">' +
                            '<img src=\"' + (user.avatar || '/templates/defaultpro/images/avatar_default.png') + '\" class=\"avatar\" alt=\"\" width=\"48\" height=\"48\">' +
                            '</a>' +
                            '<div class=\"user-info\">' +
                            '<a href=\"<?php echo $this->url('user/profile?id='); ?>' + user.id + '\" class=\"user-name\">' + user.username + '</a>' +
                            '<span class=\"user-fans\">' + (user.followers_count || 0) + ' 粉丝</span>' +
                            '</div>' +
                            '<button class=\"follow-btn-widget\" data-user-id=\"' + user.id + '\">关注</button>' +
                            '</div>';
                    });
                    container.innerHTML = html;
                    initFollowButtons();
                }
            });
        });
    }
    
    // 初始化关注按钮
    initFollowButtons();
});

// 关注按钮
function initFollowButtons() {
    document.querySelectorAll('.follow-btn-widget').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var userId = this.dataset.userId;
            var btnEl = this;
            btnEl.disabled = true;
            
            fetch('<?php echo $this->url('user/follow'); ?>', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'user_id=' + userId + '&csrf_token=<?php echo $_SESSION['csrf_token'] ?? ''; ?>'
            })
            .then(function(res) { return res.json(); })
            .then(function(result) {
                if (result.code === 0) {
                    btnEl.textContent = '已关注';
                    btnEl.classList.add('following');
                } else {
                    showToast(result.message || '关注失败');
                    btnEl.disabled = false;
                }
            })
            .catch(function(err) {
                console.error('关注失败:', err);
                btnEl.disabled = false;
            });
        });
    });
}

// 动态交互
document.addEventListener('DOMContentLoaded', function() {
    // 点赞
    document.querySelectorAll('.like-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var postId = this.dataset.id;
            var btnEl = this;
            
            fetch('<?php echo $this->url('post/like'); ?>', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'post_id=' + postId + '&csrf_token=<?php echo $_SESSION['csrf_token'] ?? ''; ?>'
            })
            .then(function(res) { return res.json(); })
            .then(function(result) {
                if (result.code === 0) {
                    btnEl.classList.toggle('liked');
                    var countEl = btnEl.querySelector('.action-count');
                    if (countEl) {
                        var count = parseInt(countEl.textContent) || 0;
                        countEl.textContent = btnEl.classList.contains('liked') ? count + 1 : count - 1;
                    }
                } else {
                    showToast(result.message || '操作失败');
                }
            });
        });
    });
    
    // 评论按钮
    document.querySelectorAll('.comment-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var postId = this.dataset.id;
            var commentBox = document.querySelector('.comment-box[data-id=\"' + postId + '\"]');
            if (commentBox) {
                commentBox.style.display = commentBox.style.display === 'none' ? 'block' : 'none';
                var textarea = commentBox.querySelector('textarea');
                if (textarea) textarea.focus();
            }
        });
    });
    
    // 转发按钮
    document.querySelectorAll('.repost-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var postId = this.dataset.id;
            showToast('转发功能开发中...');
        });
    });
    
    // 收藏按钮
    document.querySelectorAll('.favorite-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var postId = this.dataset.id;
            var btnEl = this;
            
            fetch('<?php echo $this->url('post/favorite'); ?>', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'post_id=' + postId + '&csrf_token=<?php echo $_SESSION['csrf_token'] ?? ''; ?>'
            })
            .then(function(res) { return res.json(); })
            .then(function(result) {
                if (result.code === 0) {
                    btnEl.classList.toggle('favorited');
                    showToast(btnEl.classList.contains('favorited') ? '已收藏' : '已取消收藏');
                } else {
                    showToast(result.message || '操作失败');
                }
            });
        });
    });
});

// ========== 无限滚动加载 ==========
(function() {
    var currentPage = <?php echo isset($page) ? (int)$page : 1; ?>;
    var totalPages = <?php echo isset($totalPages) ? (int)$totalPages : 1; ?>;
    var tab = '<?php echo isset($tab) ? $tab : 'all'; ?>';
    var isLoading = false;
    var hasMore = currentPage < totalPages;
    var loader = document.getElementById('infiniteScrollLoader');
    var baseUrl = '<?php echo Helper::getBaseUrl(); ?>';

    if (!loader || !hasMore) return;

    function createPostHTML(post) {
        var avatarSrc = post.avatar || '/templates/defaultpro/images/avatar_default.png';
        var userLink = '<?php echo $this->url("user/profile?id="); ?>' + post.user_id;
        var detailLink = '<?php echo $this->url("post/detail?id="); ?>' + post.id;
        
        var html = '<article class=\"post-card\" data-id=\"' + post.id + '\">' +
            '<div class=\"post-card-header\">' +
            '<a href=\"' + userLink + '\" class=\"post-author-avatar\">' +
            '<img src=\"' + avatarSrc + '\" class=\"avatar\" alt=\"\" width=\"44\" height=\"44\">' +
            '</a>' +
            '<div class=\"post-author-info\">' +
            '<a href=\"' + userLink + '\" class=\"post-author-name\">' + escapeHTML(post.username) + '</a>' +
            '<span class=\"post-time\">' + (post.time_ago || '') + '</span>' +
            '</div>';
        
        if (post.is_featured) {
            html += '<span class=\"tag tag-featured\">精华</span>';
        }
        
        html += '</div><div class=\"post-card-content\">';
        
        if (post.content) {
            html += '<p class=\"post-text\">' + post.content + '</p>';
        }
        
        if (post.images && post.images.length > 0) {
            html += '<div class=\"post-images-grid' + (post.images.length === 1 ? ' single' : '') + '\">';
            post.images.forEach(function(img) {
                html += '<div class=\"post-image-item\" onclick=\"previewImage(this.querySelector(\'img\').src)\">' +
                    '<img src=\"' + (img.path || img) + '\" alt=\"\" loading=\"lazy\">' +
                    '</div>';
            });
            html += '</div>';
        }
        
        html += '</div><div class=\"post-card-actions\">' +
            '<button class=\"action-item like-btn' + (post.is_liked ? ' liked' : '') + '\" data-id=\"' + post.id + '\">' +
            '<span class=\"action-icon\">👍</span><span class=\"action-count\">' + (post.likes || 0) + '</span></button>' +
            '<button class=\"action-item comment-btn\" data-id=\"' + post.id + '\">' +
            '<span class=\"action-icon\">💬</span><span class=\"action-count\">' + (post.comments || 0) + '</span></button>' +
            '<button class=\"action-item repost-btn\" data-id=\"' + post.id + '\">' +
            '<span class=\"action-icon\">🔄</span><span class=\"action-count\">' + (post.reposts || 0) + '</span></button>' +
            '<button class=\"action-item favorite-btn' + (post.is_favorited ? ' favorited' : '') + '\" data-id=\"' + post.id + '\">' +
            '<span class=\"action-icon\">⭐</span></button>' +
            '</div></article>';
        
        return html;
    }

    function escapeHTML(str) {
        if (!str) return '';
        var div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    function loadMorePosts() {
        if (isLoading || !hasMore) return;
        isLoading = true;
        currentPage++;
        
        if (loader) loader.classList.add('loading');
        
        fetch(baseUrl + '/?r=mobileApi/posts&tab=' + tab + '&page=' + currentPage)
            .then(function(res) { return res.json(); })
            .then(function(result) {
                if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
                    var postsContainer = document.querySelector('.main-content');
                    result.data.items.forEach(function(post) {
                        postsContainer.insertAdjacentHTML('beforeend', createPostHTML(post));
                    });
                    
                    currentPage = result.data.page || currentPage;
                    totalPages = result.data.totalPages || totalPages;
                    hasMore = currentPage < totalPages;
                    
                    if (!hasMore && loader) {
                        loader.outerHTML = '<div class=\"load-more-end\">— 没有更多内容了 —</div>';
                        loader = null;
                    }
                } else {
                    hasMore = false;
                    if (loader) {
                        loader.outerHTML = '<div class=\"load-more-end\">— 没有更多内容了 —</div>';
                        loader = null;
                    }
                }
            })
            .catch(function(err) {
                console.error('加载失败:', err);
                currentPage--;
            })
            .finally(function() {
                isLoading = false;
                if (loader) loader.classList.remove('loading');
            });
    }

    var scrollTimeout;
    window.addEventListener('scroll', function() {
        if (scrollTimeout) clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(function() {
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            var scrollHeight = document.documentElement.scrollHeight;
            var clientHeight = document.documentElement.clientHeight;
            
            if (scrollTop + clientHeight >= scrollHeight - 500) {
                loadMorePosts();
            }
        }, 100);
    });
})();
</script>
