// 首页相关功能

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

// 切换更多菜单
function toggleMoreMenu(btn, postId) {
    const dropdown = btn.nextElementSibling;
    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(window.HuSNS_Index.apiUrls.setTop, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({post_id: postId})
            }).then(r => r.json()).then(data => {
                if (data.code === 0) {
                    const item = btn.closest('.more-menu-item');
                    if (data.data && data.data.is_top) {
                        item.innerHTML = '<span class="iconify" data-icon="mdi:pin"></span> 取消置顶';
                        item.classList.add('topped');
                    } else {
                        item.innerHTML = '<span class="iconify" data-icon="mdi:pin"></span> 置顶';
                        item.classList.remove('topped');
                    }
                    showToast(data.message || '操作成功');
                } else {
                    showToast(data.message || '操作失败');
                }
            }).catch(() => showToast('操作失败'));
            break;

        case 'essence':
            fetch(window.HuSNS_Index.apiUrls.setEssence, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({post_id: postId})
            }).then(r => r.json()).then(data => {
                if (data.code === 0) {
                    const item = btn.closest('.more-menu-item');
                    if (data.data && data.data.is_essence) {
                        item.innerHTML = '<span class="iconify" data-icon="mdi:diamond-stone"></span> 取消加精';
                        item.classList.add('essenced');
                    } else {
                        item.innerHTML = '<span class="iconify" data-icon="mdi:diamond-stone"></span> 加精';
                        item.classList.remove('essenced');
                    }
                    showToast(data.message || '操作成功');
                } else {
                    showToast(data.message || '操作失败');
                }
            }).catch(() => showToast('操作失败'));
            break;

        case 'delete':
            if (!confirm('确定要删除这条动态吗？')) return;
            fetch(window.HuSNS_Index.apiUrls.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;

        case 'report':
            showToast('举报功能开发中');
            break;
    }
}

// Toast提示
function showToast(msg) {
    const t = document.createElement('div');
    t.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.75);color:#fff;padding:12px 24px;border-radius:8px;font-size:14px;z-index:10000;';
    t.textContent = msg;
    document.body.appendChild(t);
    setTimeout(() => {
        t.style.opacity = '0';
        t.style.transition = 'opacity 0.3s';
        setTimeout(() => t.remove(), 300);
    }, 2000);
}

document.addEventListener('DOMContentLoaded', function() {
    // 生成视频缩略图
    setTimeout(function() {
        if (window.HuSNS && HuSNS.generateVideoThumbnails) {
            HuSNS.generateVideoThumbnails();
        }
    }, 100);
    
    // 下拉刷新功能
    let startY = 0;
    let pullDistance = 0;
    const pullRefresh = document.getElementById('pullRefresh');
    const postList = document.getElementById('postList');
    const refreshText = document.getElementById('refreshText');

    if (postList) {
        postList.addEventListener('touchstart', function(e) {
            if (postList.scrollTop === 0) {
                startY = e.touches[0].clientY;
            }
        });

        postList.addEventListener('touchmove', function(e) {
            if (postList.scrollTop === 0 && startY > 0) {
                const currentY = e.touches[0].clientY;
                pullDistance = currentY - startY;

                if (pullDistance > 0) {
                    e.preventDefault();
                    const translateY = Math.min(pullDistance * 0.5, 60);
                    pullRefresh.style.transform = `translateY(${translateY}px)`;

                    if (pullDistance > 80) {
                        refreshText.textContent = '释放刷新';
                    } else {
                        refreshText.textContent = '下拉刷新';
                    }
                }
            }
        });

        postList.addEventListener('touchend', function() {
            if (pullDistance > 80) {
                refreshText.textContent = '刷新中...';
                pullRefresh.style.transform = 'translateY(0)';

                setTimeout(function() {
                    window.location.reload();
                }, 1500);
            } else {
                pullRefresh.style.transform = 'translateY(-100%)';
            }

            startY = 0;
            pullDistance = 0;
        });

        }
});

// 加载更多功能
function loadMore(url) {
    const loadMoreBtn = document.getElementById('loadMoreBtn');
    if (loadMoreBtn) {
        loadMoreBtn.textContent = '加载中...';
        loadMoreBtn.disabled = true;
    }

    fetch(url)
        .then(response => response.text())
        .then(data => {
            const postList = document.getElementById('postList');
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = data;

            const newPosts = tempDiv.querySelector('.post-list').innerHTML;
            if (newPosts && !newPosts.includes('empty-state')) {
                postList.insertAdjacentHTML('beforeend', newPosts);
            }

            if (loadMoreBtn) {
                loadMoreBtn.textContent = '加载更多';
                loadMoreBtn.disabled = false;
            }
        })
        .catch(error => {
            console.error('加载失败:', error);
            if (loadMoreBtn) {
                loadMoreBtn.textContent = '加载失败';
                loadMoreBtn.disabled = false;
            }
        });
}



function showLocationMap(locationName, lat, lng) {
    var 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.85);
        z-index: 10000;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
    `;

    overlay.innerHTML = `
        <div style="position: relative; width: 90%; max-width: 400px; background: #fff; border-radius: 12px; overflow: hidden;">
            <div style="display: flex; align-items: center; justify-content: space-between; padding: 16px; border-bottom: 1px solid #eee;">
                <span style="font-size: 16px; font-weight: 600;">${escapeHtml(locationName)}</span>
                <button onclick="closeLocationMap()" style="width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border: none; background: #f5f5f5; border-radius: 50%; cursor: pointer;">
                    <span class="iconify" data-icon="mdi:close" style="font-size: 18px;"></span>
                </button>
            </div>
            <div style="width: 100%; height: 200px; 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%);">
                    <svg viewBox="0 0 48 48" style="width: 48px; height: 48px;">
                        <path fill="#E53935" d="M24 4C12.95 4 4 12.95 4 24c0 11.05 8.95 20 20 20s20-8.95 20-20c0-11.05-8.95-20-20-20zm0 2c9.94 0 18 8.06 18 18s-8.06 18-18 18-18-8.06-18-18 8.06-18 18-18zm0 10c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6z"/>
                    </svg>
                </div>
                ${lat && lng ? `<div style="position: absolute; bottom: 10px; right: 10px; background: rgba(255,255,255,0.9); padding: 4px 8px; border-radius: 4px; font-size: 12px; color: #666;">${lat}, ${lng}</div>` : ''}
            </div>
            <div style="padding: 16px; display: flex; gap: 12px;">
                <button onclick="openExternalMap('${lat}', '${lng}', '${escapeHtml(locationName)}')" style="flex: 1; padding: 10px; background: var(--primary-color); color: #fff; border: none; border-radius: 8px; font-size: 14px; font-weight: 500; cursor: pointer;">
                    在地图中打开
                </button>
            </div>
        </div>
    `;

    document.body.appendChild(overlay);
    setTimeout(function() {
        overlay.style.opacity = '1';
        overlay.style.visibility = 'visible';
    }, 10);

    overlay.addEventListener('click', function(e) {
        if (e.target === overlay) {
            closeLocationMap();
        }
    });
}

function closeLocationMap() {
    var overlay = document.querySelector('.location-map-overlay');
    if (overlay) {
        overlay.style.opacity = '0';
        overlay.style.visibility = 'hidden';
        setTimeout(function() {
            overlay.remove();
        }, 300);
    }
}

function openExternalMap(lat, lng, name) {
    if (!lat || !lng) return;
    
    var schemes = [
        `geo:${lat},${lng}`,
        `maps://maps.google.com/maps?q=${lat},${lng}(${encodeURIComponent(name)})`,
        `baidumap://map/geocoder?location=${lat},${lng}`,
        `amapuri://geo?latitude=${lat}&longitude=${lng}&name=${encodeURIComponent(name)}`
    ];

    for (var i = 0; i < schemes.length; i++) {
        window.location.href = schemes[i];
    }
}

function escapeHtml(str) {
    if (!str) return '';
    var div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}