// 圈子动态页面功能

var THEME_URL = window.HuSNS_CirclePosts.themeUrl;
var circleId = window.HuSNS_CirclePosts.circleId;
var currentPage = window.HuSNS_CirclePosts.currentPage;
var isLoading = false;

function loadCircleInfo() {
    if (!circleId) return;
    
    fetch(window.HuSNS_CirclePosts.apiUrls.getCircleInfo + circleId)
        .then(response => response.json())
        .then(data => {
            if (data.code === 0 && data.data) {
                var circle = data.data;
                document.getElementById('circleName').textContent = circle.name;
                document.getElementById('memberCount').textContent = circle.member_count || 0;
                document.getElementById('postCount').textContent = circle.post_count || 0;
                
                if (circle.description) {
                    document.getElementById('circleDesc').textContent = circle.description;
                }
                
                if (circle.is_verified && circle.verify_type) {
                    var verifyTypes = ['', '官方认证', '企业认证', '个人认证'];
                    document.getElementById('verifyType').textContent = verifyTypes[circle.verify_type] || '已认证';
                    document.getElementById('circleVerify').style.display = 'inline-flex';
                    if (circle.verify_info) {
                        document.getElementById('verifyInfoText').textContent = circle.verify_info;
                    }
                }
                
                if (circle.avatar) {
                    document.getElementById('circleAvatar').src = circle.avatar;
                }
                
                if (circle.cover) {
                    var cover = document.getElementById('circleCover');
                    cover.style.backgroundImage = 'url(' + circle.cover + ')';
                    cover.classList.add('has-image');
                }
                
                if (circle.joined) {
                    document.getElementById('joinBtn').style.display = 'none';
                    document.getElementById('exitBtn').style.display = 'inline-flex';
                } else {
                    document.getElementById('joinBtn').style.display = 'inline-flex';
                    document.getElementById('exitBtn').style.display = 'none';
                    document.getElementById('joinBtnText').textContent = '加入圈子';
                    document.getElementById('joinBtn').classList.remove('joined');
                }
            }
        })
        .catch(error => {
            console.error('加载圈子信息失败:', error);
        });
}

function formatTime(timestamp) {
    if (!timestamp) return '';
    var now = Date.now() / 1000;
    var diff = now - timestamp;
    
    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) + '天前';
    
    var date = new Date(timestamp * 1000);
    return date.getMonth() + 1 + '月' + date.getDate() + '日';
}

function loadPosts() {
    if (!circleId || isLoading) return;
    
    isLoading = true;
    document.getElementById('loadMore').style.display = 'none';
    
    fetch(window.HuSNS_CirclePosts.apiUrls.getCirclePosts + circleId + '&page=' + currentPage)
        .then(response => response.json())
        .then(data => {
            isLoading = false;
            
            if (data.code === 0 && data.data && data.data.length > 0) {
                document.getElementById('emptyState').style.display = 'none';
                
                var html = '';
                data.data.forEach(post => {
                    html += HuSNS.createPostHTML(post);
                });
                
                document.getElementById('postList').innerHTML += html;
                
                if (data.data.length >= 10) {
                    document.getElementById('loadMore').style.display = 'block';
                }
            }
        })
        .catch(error => {
            isLoading = false;
            console.error('加载动态失败:', error);
        });
}

function loadMore() {
    currentPage++;
    loadPosts();
}

function toggleJoin() {
    var btn = document.getElementById('joinBtn');
    
    fetch(window.HuSNS_CirclePosts.apiUrls.joinCircle, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'circle_id=' + circleId
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 0) {
            document.getElementById('joinBtn').style.display = 'none';
            document.getElementById('exitBtn').style.display = 'inline-flex';
            document.getElementById('memberCount').textContent = parseInt(document.getElementById('memberCount').textContent) + 1;
            
            // 刷新发布弹窗中的圈子列表
            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 exitCircle() {
    // 使用美观的确认对话框
    if (window.HuSNS_Dialog) {
        HuSNS_Dialog.exitConfirm(doExitCircle);
    } else {
        if (!confirm('确定要退出该圈子吗？')) {
            return;
        }
        doExitCircle();
    }
}

function doExitCircle() {
    fetch(window.HuSNS_CirclePosts.apiUrls.exitCircle, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'circle_id=' + circleId
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 0) {
            document.getElementById('exitBtn').style.display = 'none';
            document.getElementById('joinBtn').style.display = 'inline-flex';
            document.getElementById('joinBtnText').textContent = '加入圈子';
            document.getElementById('memberCount').textContent = Math.max(0, parseInt(document.getElementById('memberCount').textContent) - 1);
            
            // 刷新发布弹窗中的圈子列表
            if (typeof refreshPublishCircles === 'function') {
                refreshPublishCircles();
            }
            
            // 使用美观的对话框
            if (window.HuSNS_Dialog) {
                HuSNS_Dialog.exitSuccess();
            } 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 goBack() {
    window.history.back();
}

function goPublish() {
    document.getElementById('publishBtn').click();
}

function shareCircle() {
    var circleName = document.getElementById('circleName').textContent;
    var shareUrl = window.location.href;
    
    if (navigator.share) {
        navigator.share({
            title: circleName,
            text: '发现一个很棒的圈子：' + circleName,
            url: shareUrl
        }).catch(err => {
            copyToClipboard(shareUrl);
        });
    } else {
        copyToClipboard(shareUrl);
    }
}

function copyToClipboard(text) {
    var textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    textarea.style.opacity = '0';
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    alert('链接已复制到剪贴板');
}

function goToCircle(id) {
    window.location.href = window.HuSNS_CirclePosts.urls.circlePosts + '?circle_id=' + id;
}

document.addEventListener('DOMContentLoaded', function() {
    loadCircleInfo();
    loadPosts();
    
    var startY = 0;
    var postList = document.getElementById('postList');
    
    postList.addEventListener('touchstart', function(e) {
        startY = e.touches[0].clientY;
    });
    
    postList.addEventListener('touchend', function(e) {
        var endY = e.changedTouches[0].clientY;
        if (endY - startY > 50 && window.scrollY === 0) {
            currentPage = 1;
            loadPosts();
        }
    });
});