// 热门页面功能

const BASE_URL = window.BASE_URL || window.location.origin;
let currentType = 'day';
let currentPage = 1;
let isLoading = false;
let hasMore = true;

// 关闭所有下拉菜单
function closeAllMenus() {
    document.querySelectorAll('.more-menu-dropdown.show').forEach(menu => {
        menu.classList.remove('show');
    });
}

// 切换更多菜单
function toggleMoreMenu(btn, postId) {
    const dropdown = btn.nextElementSibling;
    if (!dropdown) return;
    const isShown = dropdown.classList.contains('show');
    closeAllMenus();
    if (!isShown) {
        dropdown.classList.add('show');
    }
}

// 点击其他地方关闭菜单
document.addEventListener('click', function(e) {
    if (!e.target.closest('.post-actions')) {
        closeAllMenus();
    }
});

// 处理帖子操作
function handlePostAction(action, postId, btn) {
    closeAllMenus();

    switch(action) {
        case 'top':
            fetch(BASE_URL + '/?r=mobileApi/setTop', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({post_id: postId})
            }).then(r => r.json()).then(data => {
                showToast(data.message || (data.code === 0 ? '操作成功' : '操作失败'));
            }).catch(() => showToast('操作失败'));
            break;

        case 'essence':
            fetch(BASE_URL + '/?r=mobileApi/setEssence', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({post_id: postId})
            }).then(r => r.json()).then(data => {
                showToast(data.message || (data.code === 0 ? '操作成功' : '操作失败'));
            }).catch(() => showToast('操作失败'));
            break;

        case 'delete':
            if (!confirm('确定要删除这条动态吗？')) return;
            fetch(BASE_URL + '/?r=mobileApi/deletePost', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({post_id: postId})
            }).then(r => r.json()).then(data => {
                if (data.code === 0) {
                    const postItem = document.querySelector(`.hot-rank-wrapper[data-id="${postId}"]`);
                    if (postItem) {
                        postItem.style.transition = 'all 0.3s';
                        postItem.style.opacity = '0';
                        postItem.style.transform = 'translateX(-100%)';
                        setTimeout(() => postItem.remove(), 300);
                    }
                    showToast('删除成功');
                } else {
                    showToast(data.message || '删除失败');
                }
            }).catch(() => showToast('删除失败'));
            break;
    }
}

// 更新标签指示器位置
function updateTabIndicator() {
    const activeTab = document.querySelector('.hot-tab-item.active');
    const indicator = document.querySelector('.tab-slide-indicator');
    if (activeTab && indicator) {
        const tabRect = activeTab.getBoundingClientRect();
        const barRect = activeTab.parentElement.getBoundingClientRect();
        const offset = tabRect.left - barRect.left;
        indicator.style.left = offset + 'px';
        indicator.style.width = tabRect.width + 'px';
    }
}

// 页面加载时获取热门数据
document.addEventListener('DOMContentLoaded', function() {
    // 初始化指示器
    setTimeout(updateTabIndicator, 100);
    
    // 加载热门数据
    loadHotPosts();
    
    // 点赞功能
    bindLikeEvents();
    
    // 收藏功能
    bindFavoriteEvents();
    
    // 加载更多
    document.getElementById('loadMoreBtn').addEventListener('click', function() {
        if (hasMore && !isLoading) {
            loadHotPosts();
        }
    });
    
    // 标签切换功能
    document.querySelectorAll('.hot-tab-item').forEach(tab => {
        tab.addEventListener('click', function() {
            const newType = this.dataset.type;
            if (newType === currentType) return;
            
            // 更新活动状态
            document.querySelectorAll('.hot-tab-item').forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            
            // 更新指示器
            updateTabIndicator();
            
            // 重置分页并重新加载数据
            currentType = newType;
            currentPage = 1;
            hasMore = true;
            
            const postList = document.getElementById('hotPostList');
            postList.innerHTML = '';
            
            // 显示加载状态
            postList.innerHTML = `
                <div class="loading-spinner">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10" stroke-dasharray="60" stroke-dashoffset="20"/>
                    </svg>
                    <div class="loading-text">加载中...</div>
                </div>
            `;
            
            loadHotPosts(newType);
        });
    });
    
    // 窗口大小改变时更新指示器
    window.addEventListener('resize', updateTabIndicator);
});

// 从API加载热门帖子
function loadHotPosts(type) {
    type = type || currentType;
    const postList = document.getElementById('hotPostList');
    const loadMoreContainer = document.getElementById('loadMoreContainer');
    
    if (isLoading) return;
    isLoading = true;
    
    const btn = document.getElementById('loadMoreBtn');
    btn.textContent = '加载中...';
    btn.style.opacity = '0.7';
    
    fetch(BASE_URL + '/?r=mobileApi/hotPosts&page=' + currentPage + '&type=' + type)
        .then(response => response.json())
        .then(result => {
            // 移除加载状态
            const loadingSpinner = postList.querySelector('.loading-spinner');
            if (loadingSpinner) {
                loadingSpinner.remove();
            }
            
            if (result.code === 0 && result.data && result.data.items) {
                const posts = result.data.items;
                
                if (posts.length > 0) {
                    posts.forEach((post, index) => {
                        const existingCount = postList.querySelectorAll('.hot-rank-wrapper').length;
                        let rank = existingCount + 1;
                        let rankClass = rank <= 3 ? 'top' + rank : '';
                        
                        // 创建排名卡片
                        const rankBadge = rank <= 3 ? `
                            <div class="hot-rank-badge rank-${rank}">
                                <span class="badge-text">TOP ${rank}</span>
                            </div>
                        ` : '';
                        
                        let rankIcon = '';
                        if (rank === 1) {
                            rankIcon = `<span class="rank-medal"><svg viewBox="0 0 24 24" fill="currentColor" class="medal-icon gold"><path d="M12 2L9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2z"/></svg></span>`;
                        } else if (rank === 2) {
                            rankIcon = `<span class="rank-medal"><svg viewBox="0 0 24 24" fill="currentColor" class="medal-icon silver"><path d="M12 2L9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2z"/></svg></span>`;
                        } else if (rank === 3) {
                            rankIcon = `<span class="rank-medal"><svg viewBox="0 0 24 24" fill="currentColor" class="medal-icon bronze"><path d="M12 2L9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2z"/></svg></span>`;
                        } else {
                            rankIcon = `<span class="rank-number">${rank}</span>`;
                        }
                        
                        const topRankClass = rank <= 3 ? 'top-rank' : '';
                        
                        const postHtml = `<div class="hot-rank-wrapper ${topRankClass}" style="animation-delay: ${index * 0.05}s">
                            <div class="hot-rank ${rankClass}">${rankIcon}</div>
                            ${HuSNS.createPostHTML(post)}
                            ${rankBadge}
                        </div>`;
                        postList.insertAdjacentHTML('beforeend', postHtml);
                    });
                    
                    // 生成视频缩略图
                    setTimeout(() => generateVideoThumbnails(), 100);
                    
                    // 重新绑定点赞和收藏事件
                    bindLikeEvents();
                    bindFavoriteEvents();
                    
                    loadMoreContainer.style.display = 'block';
                    currentPage++;
                }
                
                // 检查是否还有更多数据
                if (!result.data.pagination || !result.data.pagination.has_more) {
                    hasMore = false;
                    loadMoreContainer.style.display = 'none';
                }
            } else {
                // 没有数据时显示空状态
                if (currentPage === 1) {
                    postList.innerHTML = `
                        <div class="hot-empty">
                            <div class="hot-empty-icon">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="64" height="64">
                                    <path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/>
                                </svg>
                            </div>
                            <p class="hot-empty-text">暂无热门内容</p>
                            <p class="hot-empty-hint">快去发布动态吧</p>
                        </div>
                    `;
                }
                hasMore = false;
                loadMoreContainer.style.display = 'none';
            }
            
            btn.textContent = hasMore ? '加载更多' : '没有更多了';
            btn.style.opacity = '1';
            isLoading = false;
        })
        .catch(err => {
            console.error('加载热门内容失败:', err);
            
            // 移除加载状态
            const loadingSpinner = postList.querySelector('.loading-spinner');
            if (loadingSpinner) {
                loadingSpinner.remove();
            }
            
            // 如果加载失败但有内容，保持现有内容
            if (!postList.querySelector('.hot-rank-wrapper') && !postList.querySelector('.hot-empty')) {
                postList.innerHTML = `
                    <div class="hot-empty">
                        <div class="hot-empty-icon">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="64" height="64">
                                <circle cx="12" cy="12" r="10"/>
                                <line x1="12" y1="8" x2="12" y2="12"/>
                                <line x1="12" y1="16" x2="12.01" y2="16"/>
                            </svg>
                        </div>
                        <p class="hot-empty-text">加载失败</p>
                        <p class="hot-empty-hint">点击按钮重试</p>
                    </div>
                `;
            }
            
            btn.textContent = '加载失败，点击重试';
            btn.style.opacity = '1';
            isLoading = false;
        });
}

// ========== 视频缩略图生成功能 ==========
function generateVideoThumbnails() {
    const videoThumbnails = document.querySelectorAll('.moment-video-thumbnail');
    videoThumbnails.forEach(container => {
        const videoUrl = container.getAttribute('data-video');
        const posterImg = container.querySelector('.moment-video-poster');
        
        if (!videoUrl || !posterImg) return;
        
        const video = document.createElement('video');
        video.src = videoUrl;
        video.crossOrigin = 'anonymous';
        
        video.addEventListener('loadedmetadata', function() {
            video.currentTime = 0.5;
        });
        
        video.addEventListener('seeked', function() {
            const canvas = document.createElement('canvas');
            canvas.width = video.videoWidth || 320;
            canvas.height = video.videoHeight || 180;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            
            posterImg.src = canvas.toDataURL('image/png');
            posterImg.style.background = 'transparent';
        });
        
        video.addEventListener('error', function() {
            posterImg.src = '';
            posterImg.style.background = '#f5f5f5';
        });
    });
}

// ========== 位置地图弹窗功能 ==========
function showLocationMap(name, lat, lng) {
    const overlay = document.createElement('div');
    overlay.className = 'location-map-overlay';
    overlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        z-index: 10000;
        display: flex;
        align-items: center;
        justify-content: center;
    `;
    
    const modal = document.createElement('div');
    modal.style.cssText = `
        width: 90%;
        max-width: 500px;
        background: white;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
        max-height: 80vh;
    `;
    
    const header = document.createElement('div');
    header.style.cssText = `
        padding: 16px;
        border-bottom: 1px solid var(--border-color);
        display: flex;
        justify-content: space-between;
        align-items: center;
    `;
    header.innerHTML = `
        <span style="font-size: 16px; font-weight: 600; color: #333;">📍 ${name}</span>
        <button onclick="this.parentElement.parentElement.parentElement.remove()" style="width: 32px; height: 32px; border: none; background: var(--background-color); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
            <span style="font-size: 18px; color: #666;">×</span>
        </button>
    `;
    
    const mapContainer = document.createElement('div');
    mapContainer.style.cssText = `
        height: 300px;
        position: relative;
        background: var(--background-color);
    `;
    
    if (lat && lng) {
        mapContainer.innerHTML = `
            <div style="width: 100%; height: 100%; background: linear-gradient(135deg, #87CEEB 0%, #E0F7FA 50%, #81D4FA 100%); position: relative; overflow: hidden;">
                <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-image: linear-gradient(rgba(0,0,0,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(0,0,0,0.03) 1px, transparent 1px); background-size: 20px 20px;"></div>
                <div style="position: absolute; top: 30%; left: 0; right: 0; height: 3px; background: rgba(139, 195, 74, 0.6);"></div>
                <div style="position: absolute; top: 0; bottom: 0; left: 50%; width: 3px; background: rgba(139, 195, 74, 0.6);"></div>
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
                    <div style="width: 40px; height: 40px; background: white; border-radius: 50%; box-shadow: 0 4px 12px rgba(0,0,0,0.2); display: flex; align-items: center; justify-content: center;">
                        <div style="width: 24px; height: 24px; background: #ff5252; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                            <svg viewBox="0 0 24 24" fill="#fff" style="width: 14px; height: 14px;">
                                <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                            </svg>
                        </div>
                    </div>
                </div>
            </div>
        `;
    } else {
        mapContainer.innerHTML = `
            <div style="width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; color: var(--text-secondary);">
                <svg viewBox="0 0 24 24" fill="currentColor" style="width: 48px; height: 48px; margin-bottom: 12px;">
                    <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                </svg>
                <span style="font-size: 14px;">暂无精确位置信息</span>
            </div>
        `;
    }
    
    const footer = document.createElement('div');
    footer.style.cssText = `
        padding: 12px 16px;
        display: flex;
        gap: 12px;
    `;
    
    const openBtn = document.createElement('button');
    openBtn.textContent = '在地图应用中打开';
    openBtn.style.cssText = `
        flex: 1;
        padding: 10px;
        background: #ff6b6b;
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 14px;
        cursor: pointer;
    `;
    openBtn.onclick = function() {
        if (lat && lng) {
            window.location.href = `geo:${lat},${lng}`;
            setTimeout(() => {
                window.open(`https://maps.google.com/maps?q=${lat},${lng}&z=15`, '_blank');
            }, 500);
        }
    };
    
    const closeBtn = document.createElement('button');
    closeBtn.textContent = '关闭';
    closeBtn.style.cssText = `
        flex: 1;
        padding: 10px;
        background: #f5f5f5;
        color: #666;
        border: none;
        border-radius: 8px;
        font-size: 14px;
        cursor: pointer;
    `;
    closeBtn.onclick = function() {
        overlay.remove();
    };
    
    footer.appendChild(openBtn);
    footer.appendChild(closeBtn);
    
    modal.appendChild(header);
    modal.appendChild(mapContainer);
    modal.appendChild(footer);
    overlay.appendChild(modal);
    
    document.body.appendChild(overlay);
    
    overlay.addEventListener('click', function(e) {
        if (e.target === overlay) {
            overlay.remove();
        }
    });
    
    document.addEventListener('keydown', function handleEsc(e) {
        if (e.key === 'Escape') {
            overlay.remove();
            document.removeEventListener('keydown', handleEsc);
        }
    });
}

// ========== 点赞和收藏事件绑定 ==========
function bindLikeEvents() {
    document.querySelectorAll('[data-action="like"]').forEach(button => {
        if (!button.dataset.bound) {
            button.dataset.bound = '1';
            button.addEventListener('click', function() {
                const isLiked = this.classList.contains('liked');
                
                this.classList.toggle('liked');
                
                if (isLiked) {
                    const svg = this.querySelector('.action-icon');
                    if (svg) svg.setAttribute('fill', 'currentColor');
                } else {
                    const svg = this.querySelector('.action-icon');
                    if (svg) svg.setAttribute('fill', '#ff6b6b');
                }
            });
        }
    });
}

function bindFavoriteEvents() {
    document.querySelectorAll('[data-action="favorite"]').forEach(button => {
        if (!button.dataset.bound) {
            button.dataset.bound = '1';
            button.addEventListener('click', function() {
                const isFavorited = this.classList.contains('favorited');
                
                this.classList.toggle('favorited');
                
                if (isFavorited) {
                    const svg = this.querySelector('.action-icon');
                    if (svg) svg.setAttribute('fill', 'currentColor');
                } else {
                    const svg = this.querySelector('.action-icon');
                    if (svg) svg.setAttribute('fill', '#ffa502');
                }
            });
        }
    });
}

// 评论按钮事件委托
document.addEventListener('click', function(e) {
    const btn = e.target.closest('.comment-btn');
    if (btn) {
        const postId = parseInt(btn.dataset.postId);
        const commentCount = parseInt(btn.closest('.post-item, .post-card')?.querySelector('.action-btn.comment-btn .action-count')?.textContent) || 0;
        openCommentModal(postId, null, commentCount);
    }
});
