// 关闭所有下拉菜单
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(`.post-item[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 followTopic(topicId) {
    const button = document.querySelector('.topic-action-button.primary');
    const isFollowing = button.textContent.trim() === '已关注';
    
    if (isFollowing) {
        button.textContent = '关注';
        alert('已取消关注');
    } else {
        button.textContent = '已关注';
        alert('关注成功');
    }
    
    // 这里可以添加API调用
}

// 分享话题
function shareTopic(keyword) {
    const url = window.location.href;
    const title = '#' + keyword + '# 话题';
    const text = '来看看 #' + keyword + '# 话题';
    
    // 使用全局的分享弹窗
    if (typeof openShareModal === 'function') {
        openShareModal(url, title, text);
        return;
    }
    
    // 备用方案：检查浏览器是否支持原生分享API
    if (navigator.share) {
        const shareData = {
            title: title,
            text: text,
            url: url
        };
        
        // 尝试使用原生分享API（不依赖canShare，避免兼容性问题）
        navigator.share(shareData)
            .then(() => {
                console.log('分享成功');
            })
            .catch((err) => {
                // 用户取消分享(AbortError)或分享失败，都回退到复制链接
                if (err.name !== 'AbortError') {
                    console.warn('分享失败，回退到复制链接:', err);
                }
                fallbackCopy(url, title);
            });
    } else {
        // 不支持原生分享，直接复制链接
        fallbackCopy(url, title);
    }
}

// 回退方案：复制链接到剪贴板
function fallbackCopy(url, title) {
    const copyText = title ? (title + ' ' + url) : url;
    
    // 检查剪贴板API是否可用
    if (!navigator.clipboard) {
        // 降级方案：创建临时输入框复制
        const textArea = document.createElement('textarea');
        textArea.value = copyText;
        textArea.style.position = 'fixed';
        textArea.style.left = '-9999px';
        document.body.appendChild(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            showToast('链接已复制到剪贴板');
        } catch (err) {
            showToast('复制失败，请手动复制链接');
            console.error('复制失败:', err);
        }
        document.body.removeChild(textArea);
        return;
    }
    
    // 使用现代剪贴板API
    navigator.clipboard.writeText(copyText)
        .then(() => {
            showToast('链接已复制到剪贴板');
        })
        .catch(err => {
            console.error('复制失败:', err);
            showToast('复制失败，请手动复制链接');
        });
}

// 显示位置地图弹窗
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 #f0f0f0;
        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: #f5f5f5; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
            <span class="iconify" data-icon="mdi:close" style="font-size: 18px; color: #666;"></span>
        </button>
    `;
    
    const mapContainer = document.createElement('div');
    mapContainer.style.cssText = `
        height: 300px;
        position: relative;
        background: #f5f5f5;
    `;
    
    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: 60%; left: 20%; right: 30%; height: 2px; background: rgba(139, 195, 74, 0.4); transform: rotate(-15deg);"></div>
                <div style="position: absolute; top: 40%; left: 10%; right: 60%; height: 2px; background: rgba(139, 195, 74, 0.4); transform: rotate(10deg);"></div>
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
                    <div style="width: 40px; height: 40px; background: #fff; 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: #E53935; 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: #999;">
                <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: #2196F3;
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 14px;
    `;
    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;
    `;
    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 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');
            video.remove();
        });
        
        video.addEventListener('error', function() {
            console.error('无法加载视频:', videoUrl);
            video.remove();
        });
        
        video.load();
    });
}



// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 生成视频缩略图
    generateVideoThumbnails();
});