<?php
/**
 * HuSNS - 发现页面
 *
 * @author  HYR
 * @QQ     281900864
 * @website https://huyourui.com
 * @license MIT
 */
$currentPage = 'discover';
$pageType = 'discover';
$bodyClass = 'discover-page';
$headerTitle = '发现';
$showTabbar = true;

// 页面特定CSS和JS文件
$pageCssFiles = [$this->themeUrl() . '/app/css/discover.css'];
$pageJsFiles = [$this->themeUrl() . '/app/js/discover.js'];

// 将页面特定资源添加到视图数据中
$this->assign('pageCssFiles', $pageCssFiles);
$this->assign('pageJsFiles', $pageJsFiles);

$this->setLayout('app');
?>

<!-- 包含头部 -->
<?php include $this->themePath() . '/layouts/header.php'; ?>

<div class="discover-content">
    <!-- 搜索栏 -->
    <div class="discover-search-wrapper">
        <div class="discover-search">
            <a href="<?php echo $this->url('mobile/topics'); ?>" class="search-input-wrapper">
                <span class="iconify search-icon" data-icon="mdi:magnify"></span>
                <span class="search-input">搜索话题、用户</span>
            </a>
        </div>
    </div>

    <!-- 快捷入口 -->
    <div class="quick-entry">
        <a href="<?php echo $this->url('mobile/hot'); ?>" class="quick-entry-item">
            <div class="quick-entry-icon hot">
                <svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 3.73-2.07 0-3.63-1.67-3.63-3.73l.03-.36C5.21 7.51 4 10.62 4 14c0 4.42 3.58 8 8 8s8-3.58 8-8C20 8.61 17.41 3.8 13.5.67zM11.71 19c-1.78 0-3.22-1.4-3.22-3.14 0-1.62 1.05-2.76 2.81-3.12 1.77-.36 3.6-1.21 4.62-2.58.39 1.29.59 2.65.59 4.04 0 2.65-2.15 4.8-4.8 4.8z"/></svg>
            </div>
            <span class="quick-entry-text">热门</span>
        </a>
        <a href="<?php echo $this->url('mobile/circles'); ?>" class="quick-entry-item">
            <div class="quick-entry-icon circle">
                <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"/></svg>
            </div>
            <span class="quick-entry-text">圈子</span>
        </a>
        <a href="<?php echo $this->url('mobile/topics'); ?>" class="quick-entry-item">
            <div class="quick-entry-icon trend">
                <svg viewBox="0 0 24 24" fill="currentColor"><path d="M16 6l2.29 2.29-4.88 4.88-4-4L2 16.59 3.41 18l6-6 4 4 6.3-6.29L22 12V6z"/></svg>
            </div>
            <span class="quick-entry-text">话题</span>
        </a>
        <a href="<?php echo $this->url('mobile/recommend'); ?>" class="quick-entry-item">
            <div class="quick-entry-icon rank">
                <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>
            </div>
            <span class="quick-entry-text">推荐</span>
        </a>
    </div>

    <!-- 热门话题 -->
    <div class="discover-section">
        <div class="section-header">
            <div class="section-title-wrapper">
                <span class="section-icon trending">
                    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M16 6l2.29 2.29-4.88 4.88-4-4L2 16.59 3.41 18l6-6 4 4 6.3-6.29L22 12V6z"/></svg>
                </span>
                <span class="section-title">热门话题</span>
            </div>
            <a href="<?php echo $this->url('mobile/topics'); ?>" class="section-more">
                查看更多
                <svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>
            </a>
        </div>
        <div class="topic-grid" id="topicGrid">
            <div class="loading-state">
                <div class="loading-spinner"></div>
                <div class="loading-text">加载中...</div>
            </div>
        </div>
    </div>

    <!-- 推荐用户 -->
    <div class="discover-section">
        <div class="section-header">
            <div class="section-title-wrapper">
                <span class="section-icon recommend">
                    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>
                </span>
                <span class="section-title">推荐关注</span>
            </div>
            <a href="<?php echo $this->url('mobile/recommend'); ?>" class="section-more" onclick="handleRecommendMoreClick(event)">
                查看更多
                <svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>
            </a>
        </div>
        <div class="user-scroll-wrapper">
            <div class="user-scroll" id="userScroll">
                <div class="loading-state">
                    <div class="loading-spinner"></div>
                    <div class="loading-text">加载中...</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 热门帖子 -->
    <div class="discover-section">
        <div class="section-header">
            <div class="section-title-wrapper">
                <span class="section-icon hot">
                    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 3.73-2.07 0-3.63-1.67-3.63-3.73l.03-.36C5.21 7.51 4 10.62 4 14c0 4.42 3.58 8 8 8s8-3.58 8-8C20 8.61 17.41 3.8 13.5.67zM11.71 19c-1.78 0-3.22-1.4-3.22-3.14 0-1.62 1.05-2.76 2.81-3.12 1.77-.36 3.6-1.21 4.62-2.58.39 1.29.59 2.65.59 4.04 0 2.65-2.15 4.8-4.8 4.8z"/></svg>
                </span>
                <span class="section-title">热门动态</span>
            </div>
            <a href="<?php echo $this->url('mobile/hot'); ?>" class="section-more">
                查看更多
                <svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>
            </a>
        </div>
        <div class="hot-posts-list" id="hotPostsList">
            <div class="loading-state">
                <div class="loading-spinner"></div>
                <div class="loading-text">加载中...</div>
            </div>
        </div>
    </div>

    <!-- 底部留白 -->
    <div class="discover-bottom-spacer"></div>
</div>

<script>
const BASE_URL = '<?php echo Helper::getBaseUrl(); ?>';

// 推荐关注 - 查看更多点击处理（未登录弹出登录弹窗）
function handleRecommendMoreClick(event) {
    event.preventDefault();
    if (!checkLogin()) {
        openModal('loginModal');
        return;
    }
    window.location.href = '<?php echo $this->url('mobile/recommend'); ?>';
}

document.addEventListener('DOMContentLoaded', function() {
    loadTrendingTopics();
    loadRecommendedUsers();
    loadHotPosts();
});

// 加载热门话题
function loadTrendingTopics() {
    const container = document.getElementById('topicGrid');

    fetch(BASE_URL + '/?r=mobileApi/getHotTopics&limit=6')
        .then(r => r.json())
        .then(data => {
            if (data.code === 0 && data.data && data.data.items && data.data.items.length > 0) {
                container.innerHTML = data.data.items.map(topic => `
                    <div class="topic-card" onclick="window.location.href='${BASE_URL}/?r=mobile/topic&keyword=${encodeURIComponent(topic.name)}'">
                        <div class="topic-card-icon">
                            <span class="iconify" data-icon="mdi:tag"></span>
                        </div>
                        <div class="topic-card-content">
                            <div class="topic-card-name">${topic.name}</div>
                            <div class="topic-card-count">${topic.post_count || 0} 帖子</div>
                        </div>
                    </div>
                `).join('');
            } else {
                container.innerHTML = '<div class="empty-state"><div class="empty-icon">📋</div><div class="empty-text">暂无热门话题</div></div>';
            }
        })
        .catch(err => {
            console.error('加载热门话题失败:', err);
            container.innerHTML = '<div class="empty-state"><div class="empty-icon">⚠️</div><div class="empty-text">加载失败</div></div>';
        });
}

// 加载推荐用户
function loadRecommendedUsers() {
    const container = document.getElementById('userScroll');

    fetch(BASE_URL + '/?r=mobileApi/getRecommendedUsers&limit=10')
        .then(r => r.json())
        .then(data => {
            if (data.code === 0 && data.data && data.data.items && data.data.items.length > 0) {
                container.innerHTML = data.data.items.map(user => `
                    <div class="user-card" onclick="window.location.href='${BASE_URL}/?r=mobile/user&id=${user.id}'">
                        <img class="user-card-avatar" src="${user.avatar || '/templates/mobile/images/avatar_default.png'}" alt="${user.username}">
                        <div class="user-card-name">${user.username}</div>
                        <div class="user-card-followers">${user.followers_count || 0} 粉丝</div>
                    </div>
                `).join('');
            } else if (data.code === 401) {
                container.innerHTML = `
                    <div class="user-card" style="width: 120px;" onclick="window.location.href='${BASE_URL}/?r=mobile/login'">
                        <div style="font-size: 32px; margin-bottom: 8px;">🔐</div>
                        <div class="user-card-name" style="font-size: 12px;">登录后查看推荐</div>
                    </div>
                `;
            } else {
                container.innerHTML = '<div class="empty-state"><div class="empty-icon">👥</div><div class="empty-text">暂无推荐用户</div></div>';
            }
        })
        .catch(err => {
            console.error('加载推荐用户失败:', err);
            container.innerHTML = '<div class="empty-state"><div class="empty-icon">⚠️</div><div class="empty-text">加载失败</div></div>';
        });
}

// 加载热门帖子
function loadHotPosts() {
    const container = document.getElementById('hotPostsList');

    fetch(BASE_URL + '/?r=mobileApi/hotPosts&page=1&limit=5')
        .then(r => r.json())
        .then(data => {
            if (data.code === 0 && data.data && data.data.items && data.data.items.length > 0) {
                container.innerHTML = data.data.items.map(post => {
                    const images = post.images && post.images.length > 0 ? post.images : [];
                    const imagesClass = images.length === 1 ? 'single' : 'multiple';
                    const imagesHtml = images.length > 0 ? `
                        <div class="hot-post-images ${imagesClass}">
                            ${images.slice(0, 3).map(img => `<img class="hot-post-image" src="${img}" alt="" loading="lazy">`).join('')}
                        </div>
                    ` : '';

                    return `
                        <div class="hot-post-item" onclick="window.location.href='${BASE_URL}/?r=mobile/detail&id=${post.id}'">
                            <div class="hot-post-header">
                                <img class="hot-post-avatar" src="${post.user.avatar || '/templates/mobile/images/avatar_default.png'}" alt="">
                                <div class="hot-post-user">
                                    <div class="hot-post-username">${post.user.username}</div>
                                    <div class="hot-post-time">${formatTime(post.created_at)}</div>
                                </div>
                            </div>
                            <div class="hot-post-content">${escapeHtml(post.content)}</div>
                            ${imagesHtml}
                            <div class="hot-post-stats">
                                <span class="hot-post-stat">
                                    <span class="iconify" data-icon="mdi:heart"></span>
                                    ${post.like_count || 0}
                                </span>
                                <span class="hot-post-stat">
                                    <span class="iconify" data-icon="mdi:comment"></span>
                                    ${post.comment_count || 0}
                                </span>
                            </div>
                        </div>
                    `;
                }).join('');
            } else {
                container.innerHTML = '<div class="empty-state"><div class="empty-icon">🔥</div><div class="empty-text">暂无热门帖子</div></div>';
            }
        })
        .catch(err => {
            console.error('加载热门帖子失败:', err);
            container.innerHTML = '<div class="empty-state"><div class="empty-icon">⚠️</div><div class="empty-text">加载失败</div></div>';
        });
}

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

function formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp * 1000);
    const now = new Date();
    const diff = (now - date) / 1000;

    if (diff < 60) return '刚刚';
    if (diff < 3600) return Math.floor(diff / 60) + '分钟前';
    if (diff < 86400) return Math.floor(diff / 3600) + '小时前';
    if (diff < 604800) return Math.floor(diff / 86400) + '天前';

    return date.toLocaleDateString('zh-CN');
}
</script>
