/**
 * HuSNS - 动态列表模块
 * 处理首页动态加载、标签切换、无限滚动等功能
 */

var HuSNS = window.HuSNS || {};

/**
 * 初始化动态列表
 */
HuSNS.initFeed = function() {
    // 如果PHP没有传递posts数据，则通过API加载
    var phpPostsCount = window.POSTS_COUNT || 0;
    if (phpPostsCount === 0) {
        HuSNS.loadPostsFromAPI();
    }
    
    // 无限滚动
    if (phpPostsCount >= 10) {
        HuSNS.initInfiniteScroll();
    }
};

/**
 * 切换标签
 * @param {string} tab - 标签名称
 */
HuSNS.switchTab = function(tab) {
    if (tab === HuSNS.feedState.currentTab) return;
    
    // 关注标签需要登录
    if (tab === 'following') {
        var userId = document.body.dataset.userId;
        if (!userId) {
            HuSNS.showToast('请先登录');
            if (typeof openLoginModal === 'function') openLoginModal();
            return;
        }
    }
    
    HuSNS.feedState.currentTab = tab;
    
    // 更新标签栏样式
    document.querySelectorAll('#homeTabBar .tab-item').forEach(function(item) {
        item.classList.toggle('active', item.dataset.tab === tab);
    });
    
    // 重置列表
    var postList = document.getElementById('postList');
    postList.innerHTML = 
        '<div class="loading-state">' +
            '<div class="loading-spinner"></div>' +
            '<div class="loading-text">加载中...</div>' +
        '</div>';
    
    // 移除加载更多按钮
    var loadMoreDiv = document.querySelector('.load-more');
    if (loadMoreDiv) loadMoreDiv.remove();
    
    // 重置分页
    HuSNS.feedState.currentPage = 1;
    HuSNS.feedState.isLoading = false;
    
    // 加载新数据
    HuSNS.loadPostsFromAPI();
};

/**
 * 从API加载数据
 */
HuSNS.loadPostsFromAPI = function() {
    var tab = HuSNS.feedState.currentTab;
    var postList = document.getElementById('postList');
    var apiUrl = window.API_BASE_URL || '';
    
    // 圈子标签显示圈子列表
    if (tab === 'circles') {
        HuSNS.loadCirclesList();
        return;
    }
    
    var apiEndpoint = '/?r=mobileApi/posts&tab=' + tab + '&page=1';
    
    fetch(apiUrl + apiEndpoint)
        .then(function(response) { return response.json(); })
        .then(function(result) {
            var loadingState = postList.querySelector('.loading-state');
            if (loadingState) {
                postList.innerHTML = '';
            }
            
            var items = result.code === 0 && result.data && result.data.items ? result.data.items : [];
            
            if (items.length > 0) {
                items.forEach(function(post) {
                    var postHtml = HuSNS.createPostHTML(post);
                    postList.insertAdjacentHTML('beforeend', postHtml);
                });
                // 生成视频缩略图
                setTimeout(function() {
                    if (typeof HuSNS.generateVideoThumbnails === 'function') {
                        HuSNS.generateVideoThumbnails();
                    }
                }, 100);
            } else {
                var emptyText = '暂无内容';
                var emptySubtext = '快去发表第一条动态吧';
                if (tab === 'following') {
                    emptyText = '暂无关注动态';
                    emptySubtext = '关注更多用户，发现精彩内容';
                }
                postList.innerHTML = 
                    '<div class="empty-state">' +
                        '<div class="empty-icon"><span class="iconify" data-icon="mdi:email-open-outline"></span></div>' +
                        '<div class="empty-text">' + emptyText + '</div>' +
                        '<div class="empty-subtext">' + emptySubtext + '</div>' +
                    '</div>';
            }
        })
        .catch(function(err) {
            console.error('加载动态失败', err);
            var loadingState = postList.querySelector('.loading-state');
            if (loadingState) {
                postList.innerHTML = 
                    '<div class="empty-state">' +
                        '<div class="empty-icon"><span class="iconify" data-icon="mdi:email-open-outline"></span></div>' +
                        '<div class="empty-text">加载失败</div>' +
                        '<div class="empty-subtext">请稍后重试</div>' +
                    '</div>';
            }
        });
};

/**
 * 加载圈子列表
 */
HuSNS.loadCirclesList = function() {
    var postList = document.getElementById('postList');
    var apiUrl = window.API_BASE_URL || '';
    
    fetch(apiUrl + '/?r=mobileApi/getCirclesList')
        .then(function(response) { return response.json(); })
        .then(function(result) {
            var loadingState = postList.querySelector('.loading-state');
            if (loadingState) {
                postList.innerHTML = '';
            }
            
            var circles = result.code === 0 && result.data ? (result.data.circles || result.data) : [];
            
            if (circles.length > 0) {
                circles.forEach(function(circle) {
                    var circleHtml = HuSNS.createCircleHTML(circle);
                    postList.insertAdjacentHTML('beforeend', circleHtml);
                });
            } else {
                postList.innerHTML = 
                    '<div class="empty-state">' +
                        '<div class="empty-icon"><span class="iconify" data-icon="mdi:users"></span></div>' +
                        '<div class="empty-text">暂无圈子</div>' +
                        '<div class="empty-subtext">快来创建或发现第一个圈子吧</div>' +
                    '</div>';
            }
        })
        .catch(function(err) {
            console.error('加载圈子失败', err);
            var loadingState = postList.querySelector('.loading-state');
            if (loadingState) {
                postList.innerHTML = 
                    '<div class="empty-state">' +
                        '<div class="empty-icon"><span class="iconify" data-icon="mdi:users"></span></div>' +
                        '<div class="empty-text">加载失败</div>' +
                        '<div class="empty-subtext">请稍后重试</div>' +
                    '</div>';
            }
        });
};

/**
 * 创建圈子卡片HTML
 */
HuSNS.createCircleHTML = function(circle) {
    var avatar = circle.avatar ? circle.avatar : window.THEME_URL + '/images/default-circle.png';
    var joinedClass = circle.joined ? 'joined' : '';
    var buttonText = circle.joined ? '已加入' : '加入';
    
    var verifyTypes = ['', '官方', '企业', '个人'];
    var verifyType = circle.verify_type ? verifyTypes[circle.verify_type] || '' : '';
    var verifyInfo = circle.verify_info || '';
    
    var verifiedHtml = '';
    if (circle.is_verified) {
        var verifyLabel = verifyType ? verifyType + '认证' : '已认证';
        verifiedHtml = '<span class="circle-verified-badge" title="' + verifyLabel + (verifyInfo ? ' - ' + verifyInfo : '') + '">' +
            '<svg viewBox="0 0 24 24" fill="#007AFF"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/></svg>' +
            (verifyType ? '<span class="verify-type">' + verifyType + '</span>' : '') +
            (verifyInfo ? '<span class="verify-info">' + verifyInfo + '</span>' : '') +
        '</span>';
    }
    
    return '<div class="circle-card" onclick="HuSNS.viewCircle(' + circle.id + ')">' +
        '<img class="circle-avatar" src="' + avatar + '" alt="' + circle.name + '">' +
        '<div class="circle-info">' +
            '<div class="circle-name-row">' +
                '<h3 class="circle-name">' + circle.name + '</h3>' +
                verifiedHtml +
            '</div>' +
            '<p class="circle-desc">' + (circle.description || '暂无简介') + '</p>' +
            '<div class="circle-stats">' +
                '<span>' + (circle.member_count || 0) + ' 成员</span>' +
                '<span class="stat-divider">·</span>' +
                '<span>' + (circle.post_count || 0) + ' 动态</span>' +
            '</div>' +
        '</div>' +
        '<button class="circle-join-btn ' + joinedClass + '" onclick="event.stopPropagation(); HuSNS.joinCircle(' + circle.id + ', this)">' + buttonText + '</button>' +
    '</div>';
};

/**
 * 查看圈子详情
 */
HuSNS.viewCircle = function(circleId) {
    window.location.href = '/?r=mobile/circlePosts&circle_id=' + circleId;
};

/**
 * 加入圈子
 */
HuSNS.joinCircle = function(circleId, btn) {
    if (btn.classList.contains('joined')) {
        alert('您已加入该圈子');
        return;
    }
    
    var apiUrl = window.API_BASE_URL || '';
    
    fetch(apiUrl + '/?r=mobileApi/joinCircle', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'circle_id=' + circleId
    })
    .then(function(response) { return response.json(); })
    .then(function(result) {
        if (result.code === 0) {
            btn.textContent = '已加入';
            btn.classList.add('joined');
            alert('加入成功');
            
            // 更新成员数
            var stats = btn.parentElement.querySelector('.circle-stats');
            if (stats) {
                var memberSpan = stats.querySelector('span:first-child');
                if (memberSpan) {
                    var currentCount = parseInt(memberSpan.textContent);
                    memberSpan.textContent = (currentCount + 1) + ' 成员';
                }
            }
        } else {
            alert(result.message || '加入失败');
        }
    })
    .catch(function(err) {
        console.error('加入圈子失败', err);
        alert('加入失败');
    });
};

/**
 * 初始化无限滚动
 */
HuSNS.initInfiniteScroll = function() {
    var lastPost = document.querySelector('.moment-card:last-child');
    if (!lastPost) return;
    
    var observer = new IntersectionObserver(function(entries) {
        if (entries[0].isIntersecting && !HuSNS.feedState.isLoading) {
            HuSNS.feedState.isLoading = true;
            HuSNS.feedState.currentPage++;
            
            var apiUrl = window.API_BASE_URL || '';
            fetch(apiUrl + '/?r=mobileApi/posts&tab=' + HuSNS.feedState.currentTab + '&page=' + HuSNS.feedState.currentPage)
                .then(function(response) { return response.json(); })
                .then(function(result) {
                    if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
                        HuSNS.renderPosts(result.data.items);
                    }
                    HuSNS.feedState.isLoading = false;
                })
                .catch(function() {
                    HuSNS.feedState.isLoading = false;
                });
        }
    }, { threshold: 0.1 });
    
    observer.observe(lastPost);
};

/**
 * 渲染帖子列表
 * @param {Array} posts - 帖子数组
 */
HuSNS.renderPosts = function(posts) {
    var postList = document.getElementById('postList');
    posts.forEach(function(post) {
        var postHtml = HuSNS.createPostHTML(post);
        postList.insertAdjacentHTML('beforeend', postHtml);
    });
    
    // 重新初始化无限滚动
    setTimeout(function() {
        HuSNS.initInfiniteScroll();
    }, 100);
};

/**
 * 加载更多（按钮方式）
 * @param {string} url - 加载URL
 */
function loadMore(url) {
    var btn = document.getElementById('loadMoreBtn');
    if (!btn) return;
    
    btn.textContent = '加载中...';
    btn.disabled = true;
    
    fetch(url)
        .then(function(response) { return response.text(); })
        .then(function(html) {
            var parser = new DOMParser();
            var doc = parser.parseFromString(html, 'text/html');
            var newPosts = doc.querySelectorAll('.moment-card');
            
            if (newPosts.length > 0) {
                var postList = document.getElementById('postList');
                newPosts.forEach(function(post) {
                    postList.insertAdjacentHTML('beforeend', post.outerHTML);
                });
                
                // 生成视频缩略图
                if (typeof HuSNS.generateVideoThumbnails === 'function') {
                    HuSNS.generateVideoThumbnails();
                }
            }
            
            // 更新或移除加载更多按钮
            var newLoadMore = doc.querySelector('.load-more');
            if (newLoadMore) {
                var oldLoadMore = document.querySelector('.load-more');
                if (oldLoadMore) {
                    oldLoadMore.innerHTML = newLoadMore.innerHTML;
                }
            } else {
                var oldLoadMore = document.querySelector('.load-more');
                if (oldLoadMore) oldLoadMore.remove();
            }
        })
        .catch(function() {
            btn.textContent = '加载失败，点击重试';
            btn.disabled = false;
        });
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    HuSNS.initFeed();
});

// 全局暴露
window.HuSNS = HuSNS;
window.switchTab = HuSNS.switchTab;
window.loadMore = loadMore;
