<?php
/**
 * HuSNS - 一款免费开源的社交平台
 * 
 * 圈子列表页面
 */
$currentPage = 'circles';
$pageType = 'circles';
$bodyClass = 'circles-page';
$this->setLayout('app');
?>
<!-- 圈子页面样式 -->
<link rel="stylesheet" href="<?php echo $this->themeUrl(); ?>/app/css/circles.css">
<link rel="stylesheet" href="<?php echo $this->themeUrl(); ?>/css/dialog.css">

<div class="circles-content">
    <!-- 页面头部 -->
    <div class="circles-header">
        <div class="header-title">圈子</div>
        <div class="header-subtitle">发现感兴趣的圈子，与志同道合的人交流</div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="11" cy="11" r="8"/>
            <path d="m21 21-4.35-4.35"/>
        </svg>
        <input type="text" id="circleSearchInput" placeholder="搜索圈子" onkeyup="searchCircles()">
    </div>

    <!-- 圈子分类标签 -->
    <div class="category-tabs">
        <span class="category-tab active" data-category="all" onclick="filterCircles('all')">全部</span>
        <span class="category-tab" data-category="joined" onclick="filterCircles('joined')">已加入</span>
        <span class="category-tab" data-category="recommend" onclick="filterCircles('recommend')">推荐</span>
    </div>

    <!-- 圈子列表 -->
    <div class="circle-list" id="circleList">
        <div class="loading-state">
            <div class="loading-spinner"></div>
            <div class="loading-text">加载中...</div>
        </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" id="emptyState" style="display:none;">
        <div class="empty-icon">🔍</div>
        <div class="empty-title">暂无圈子</div>
        <div class="empty-desc">快来创建或发现第一个圈子吧</div>
    </div>
</div>

<!-- 圈子详情弹窗 -->
<div class="modal-overlay circle-detail-modal" id="circleDetailModal" style="display:none;">
    <div class="modal-container circle-detail-container">
        <div class="circle-detail-header">
            <img class="circle-cover" id="circleDetailCover" src="" alt="">
            <div class="circle-info">
                <img class="circle-avatar-large" id="circleDetailAvatar" src="" alt="">
                <h3 class="circle-name" id="circleDetailName"></h3>
                <p class="circle-desc" id="circleDetailDesc"></p>
                <div class="circle-stats">
                    <span class="stat-item"><strong id="circleMemberCount">0</strong> 成员</span>
                    <span class="stat-divider">·</span>
                    <span class="stat-item"><strong id="circlePostCount">0</strong> 动态</span>
                </div>
            </div>
        </div>
        <div class="circle-detail-actions">
            <button class="btn btn-primary" id="joinCircleBtn" onclick="joinCircle()">加入圈子</button>
            <button class="btn btn-secondary" id="viewCircleBtn" onclick="viewCirclePosts()">查看动态</button>
        </div>
        <button class="modal-close" onclick="closeCircleDetail()">×</button>
    </div>
</div>

<script>
var circlesData = [];
var currentCategory = 'all';

function loadCircles() {
    fetch('<?php echo Helper::getBaseUrl(); ?>?r=mobileApi/getCirclesList')
        .then(response => response.json())
        .then(data => {
            if (data.code === 0 && data.data) {
                circlesData = data.data;
                renderCircles();
            } else {
                document.getElementById('circleList').innerHTML = '';
                document.getElementById('emptyState').style.display = 'flex';
            }
        })
        .catch(error => {
            console.error('加载圈子失败:', error);
            document.getElementById('circleList').innerHTML = '';
            document.getElementById('emptyState').style.display = 'flex';
        });
}

function renderCircles() {
    var filtered = circlesData;
    
    if (currentCategory === 'joined') {
        filtered = circlesData.filter(c => c.joined);
    } else if (currentCategory === 'recommend') {
        filtered = circlesData.filter(c => !c.joined);
    }
    
    var keyword = document.getElementById('circleSearchInput').value.toLowerCase();
    if (keyword) {
        filtered = filtered.filter(c => c.name.toLowerCase().includes(keyword));
    }
    
    if (filtered.length === 0) {
        document.getElementById('circleList').innerHTML = '';
        document.getElementById('emptyState').style.display = 'flex';
        return;
    }
    
    document.getElementById('emptyState').style.display = 'none';
    
    var html = '';
    filtered.forEach(circle => {
        var avatar = circle.avatar ? circle.avatar : '<?php echo $this->themeUrl(); ?>/images/default-circle.png';
        html += `
            <div class="circle-card" onclick="showCircleDetail(${circle.id})">
                <img class="circle-card-avatar" src="${avatar}" alt="${circle.name}">
                <div class="circle-card-info">
                    <h4 class="circle-card-name">${circle.name}</h4>
                    <p class="circle-card-desc">${circle.description || '暂无描述'}</p>
                    <div class="circle-card-stats">
                        <span>${circle.member_count || 0} 成员</span>
                        <span class="stat-divider">·</span>
                        <span>${circle.post_count || 0} 动态</span>
                    </div>
                </div>
                <div class="circle-card-action">
                    ${circle.joined ? 
                        '<span class="joined-badge">已加入</span>' : 
                        '<button class="join-btn" onclick="event.stopPropagation(); joinCircleDirect(' + circle.id + ')">加入</button>'
                    }
                </div>
            </div>
        `;
    });
    
    document.getElementById('circleList').innerHTML = html;
}

function filterCircles(category) {
    currentCategory = category;
    document.querySelectorAll('.category-tab').forEach(tab => tab.classList.remove('active'));
    document.querySelector('[data-category="' + category + '"]').classList.add('active');
    renderCircles();
}

function searchCircles() {
    renderCircles();
}

function showCircleDetail(circleId) {
    var circle = circlesData.find(c => c.id === circleId);
    if (!circle) return;
    
    document.getElementById('circleDetailName').textContent = circle.name;
    document.getElementById('circleDetailDesc').textContent = circle.description || '暂无描述';
    document.getElementById('circleMemberCount').textContent = circle.member_count || 0;
    document.getElementById('circlePostCount').textContent = circle.post_count || 0;
    
    var avatar = circle.avatar ? circle.avatar : '<?php echo $this->themeUrl(); ?>/images/default-circle.png';
    document.getElementById('circleDetailAvatar').src = avatar;
    document.getElementById('circleDetailCover').src = circle.cover || '<?php echo $this->themeUrl(); ?>/images/default-circle.png';
    
    var joinBtn = document.getElementById('joinCircleBtn');
    if (circle.joined) {
        joinBtn.textContent = '已加入';
        joinBtn.disabled = true;
    } else {
        joinBtn.textContent = '加入圈子';
        joinBtn.disabled = false;
    }
    
    window.currentCircleId = circleId;
    document.getElementById('circleDetailModal').style.display = 'flex';
}

function closeCircleDetail() {
    document.getElementById('circleDetailModal').style.display = 'none';
    window.currentCircleId = null;
}

function joinCircleDirect(circleId) {
    window.currentCircleId = circleId;
    joinCircle();
}

function joinCircle() {
    if (!window.currentCircleId) return;
    
    fetch('<?php echo Helper::getBaseUrl(); ?>?r=mobileApi/joinCircle', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'circle_id=' + window.currentCircleId
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 0) {
            var circle = circlesData.find(c => c.id === window.currentCircleId);
            if (circle) {
                circle.joined = true;
                circle.member_count = (circle.member_count || 0) + 1;
            }
            renderCircles();
            closeCircleDetail();
            
            // 刷新发布弹窗中的圈子列表
            if (typeof refreshPublishCircles === 'function') {
                refreshPublishCircles();
            }
            
            // 使用美观的对话框
            if (window.HuSNS_Dialog) {
                HuSNS_Dialog.joinSuccess();
            } else {
                alert('加入成功');
            }
        } else {
            if (window.HuSNS_Dialog) {
                HuSNS_Dialog.error(data.message || '加入失败');
            } else {
                alert(data.message || '加入失败');
            }
        }
    })
    .catch(error => {
        console.error('加入圈子失败:', error);
        if (window.HuSNS_Dialog) {
            HuSNS_Dialog.error('加入失败');
        } else {
            alert('加入失败');
        }
    });
}

function viewCirclePosts() {
    if (!window.currentCircleId) return;
    closeCircleDetail();
    window.location.href = '<?php echo Helper::url('mobile/circlePosts'); ?>?circle_id=' + window.currentCircleId;
}

// 页面加载完成后加载圈子列表
document.addEventListener('DOMContentLoaded', loadCircles);
</script>

<script src="<?php echo $this->themeUrl(); ?>/js/dialog.js"></script>