// 收藏页面功能

const BASE_URL = window.BASE_URL || window.location.origin;
let currentPage = 1;
let isLoading = false;
let hasMore = true;
let isEditMode = false;
let selectedItems = new Set();

document.addEventListener('DOMContentLoaded', function() {
    loadFavorites();
    document.getElementById('loadMoreBtn').addEventListener('click', loadMoreFavorites);
});

// ========== 编辑模式功能 ==========
function toggleEditMode() {
    isEditMode = !isEditMode;
    const items = document.querySelectorAll('.favorite-item');
    const batchActions = document.getElementById('batchActions');
    const editBtn = document.getElementById('editFavoritesBtn');
    
    if (isEditMode) {
        // 进入编辑模式
        items.forEach(item => item.classList.add('edit-mode'));
        batchActions.style.display = 'flex';
        editBtn.classList.add('active');
    } else {
        // 退出编辑模式
        items.forEach(item => item.classList.remove('edit-mode'));
        batchActions.style.display = 'none';
        editBtn.classList.remove('active');
        // 清空选择
        selectedItems.clear();
        document.querySelectorAll('.select-checkbox').forEach(cb => cb.checked = false);
    }
}

function selectAllFavorites() {
    const checkboxes = document.querySelectorAll('.select-checkbox');
    const allSelected = selectedItems.size === checkboxes.length;
    
    checkboxes.forEach(cb => {
        const postId = cb.dataset.id;
        if (allSelected) {
            // 取消全选
            selectedItems.delete(postId);
            cb.checked = false;
        } else {
            // 全选
            selectedItems.add(postId);
            cb.checked = true;
        }
    });
    
    updateBatchButton();
}

function toggleSelectItem(checkbox) {
    const postId = checkbox.dataset.id;
    if (checkbox.checked) {
        selectedItems.add(postId);
    } else {
        selectedItems.delete(postId);
    }
    updateBatchButton();
}

function updateBatchButton() {
    const deleteBtn = document.querySelector('.batch-btn.delete-batch');
    if (deleteBtn) {
        deleteBtn.disabled = selectedItems.size === 0;
        deleteBtn.textContent = selectedItems.size > 0 
            ? `删除 (${selectedItems.size})` 
            : '删除';
    }
}

async function deleteSelectedFavorites() {
    if (selectedItems.size === 0) {
        showToast('请先选择要删除的收藏');
        return;
    }
    
    const confirmed = await new Promise(resolve => {
        showConfirm(`确定要删除选中的 ${selectedItems.size} 条收藏吗？`, resolve);
    });
    
    if (!confirmed) return;
    
    let successCount = 0;
    for (const postId of selectedItems) {
        try {
            const response = await fetch(BASE_URL + '/?r=mobileApi/unfavorite', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({post_id: postId})
            });
            const data = await response.json();
            if (data.code === 0 || data.success) {
                successCount++;
                // 从DOM移除
                const card = document.querySelector(`.favorite-item[data-id="${postId}"]`);
                if (card) {
                    card.style.transition = 'all 0.3s';
                    card.style.opacity = '0';
                    card.style.transform = 'translateX(-100%)';
                    setTimeout(() => card.remove(), 300);
                }
            }
        } catch (e) {
            console.error('删除失败:', e);
        }
    }
    
    showToast(`已删除 ${successCount} 条收藏`);
    selectedItems.clear();
    updateFavoritesCount();
    
    // 退出编辑模式
    if (successCount > 0) {
        toggleEditMode();
    }
}

function updateFavoritesCount() {
    const countEl = document.getElementById('favoritesCount');
    const items = document.querySelectorAll('.favorite-item');
    if (countEl) {
        countEl.textContent = items.length;
    }
}

async function loadFavorites() {
    if (isLoading) return;
    isLoading = true;
    
    const container = document.getElementById('favoritesList');
    container.innerHTML = `
        <div class="loading-state">
            <div class="loading-spinner"></div>
            <div class="loading-text">加载中...</div>
        </div>
    `;
    
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/userPosts&page=' + currentPage + '&type=favorites');
        const result = await response.json();
        
        if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
            let html = '';
            result.data.items.forEach(post => {
                html += createFavoriteItem(post);
            });
            container.innerHTML = html;
            // 生成视频缩略图
            setTimeout(() => generateVideoThumbnails(), 100);
            // 更新收藏数量
            updateFavoritesCount();
            hasMore = result.data.has_more || false;
            
            if (hasMore) {
                document.getElementById('loadMoreContainer').style.display = 'block';
                document.getElementById('loadMoreBtn').textContent = '加载更多';
            } else {
                document.getElementById('loadMoreContainer').style.display = 'none';
            }
        } else {
            container.innerHTML = `
                <div class="empty-favorites">
                    <div class="empty-favorites-icon"><span class="iconify" data-icon="mdi:star-outline"></span></div>
                    <div class="empty-favorites-text">暂无收藏</div>
                    <div class="empty-favorites-subtext">收藏感兴趣的动态，方便后续查看</div>
                </div>
            `;
            document.getElementById('loadMoreContainer').style.display = 'none';
        }
    } catch (error) {
        console.error('加载失败:', error);
        container.innerHTML = `
            <div class="empty-favorites">
                <div class="empty-favorites-icon"><span class="iconify" data-icon="mdi:alert-circle-outline"></span></div>
                <div class="empty-favorites-text">加载失败</div>
                <div class="empty-favorites-subtext">请检查网络连接后重试</div>
            </div>
        `;
    }
    
    isLoading = false;
}

function createFavoriteItem(post) {
    const avatar = post.avatar ? `<img class="avatar" src="${post.avatar}" alt="" style="width:42px;height:42px;border-radius:6px;object-fit:cover;">` : 
        `<div class="avatar" style="width:42px;height:42px;border-radius:6px;background:linear-gradient(135deg, #667eea, #764ba2);display:flex;align-items:center;justify-content:center;font-size:16px;font-weight:600;color:#fff;">${(post.username || 'U').charAt(0).toUpperCase()}</div>`;
    
    const isLiked = post.is_liked ? 'liked' : '';
    const likesCount = post.likes || 0;
    const commentsCount = post.comments || 0;
    const viewsCount = post.views || 0;
    const isOnline = post.is_online || false;
    const onlineBadgeHtml = isOnline 
        ? '<span class="online-badge" title="在线"></span>' 
        : '<span class="online-badge offline" title="离线"></span>';
    
    let imagesHtml = '';
    if (post.images && post.images.length > 0) {
        const gridClass = post.images.length === 1 ? 'single-image' : '';
        imagesHtml = `
            <div class="moment-images">
                <div class="moment-image-grid ${gridClass}">
                    ${post.images.slice(0, 9).map(img => `<img class="moment-img" src="${img}" alt="" loading="lazy">`).join('')}
                </div>
            </div>
        `;
    }
    
    let videoHtml = '';
    if (post.videos && post.videos.length > 0) {
        videoHtml = `
            <div class="moment-images">
                <div class="moment-video-thumbnail" onclick="HuSNS.openVideoPlayer('${post.videos[0]}')" data-video="${post.videos[0]}">
                    <img class="moment-video-poster" src="" alt="">
                    <div class="moment-video-play-btn">
                        <span class="iconify" data-icon="mdi:play" style="color: white; font-size: 24px;"></span>
                    </div>
                    <div class="moment-video-badge">视频</div>
                </div>
            </div>
        `;
    }
    
    let locationHtml = '';
    if (post.location && post.location.name) {
        const loc = post.location;
        const hasCoords = loc.lat && loc.lng && loc.lat !== '0' && loc.lng !== '0';
        if (hasCoords) {
            locationHtml = `
                <div class="moment-location-card" onclick="showLocationMap('${escapeHtml(loc.name)}', '${loc.lat}', '${loc.lng}')">
                    <span class="location-pin">
                        <svg viewBox="0 0 24 24">
                            <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>
                    <span class="location-text">${escapeHtml(loc.name)}</span>
                </div>
            `;
        } else {
            locationHtml = `
                <a class="moment-location-link" href="${BASE_URL}/?r=mobile/hot&location=${encodeURIComponent(loc.name)}">
                    <span class="location-pin">
                        <svg viewBox="0 0 24 24">
                            <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>
                    <span class="location-text">${escapeHtml(loc.name)}</span>
                </a>
            `;
        }
    }
    
    const contentShort = escapeHtml(post.content ? post.content.replace(/<[^>]*>/g, '').substring(0, 30) : '');
    
    return `
        <div class="favorite-item moment-card" data-id="${post.id}">
            <input type="checkbox" class="select-checkbox" data-id="${post.id}" onclick="toggleSelectItem(this)">
            <div class="moment-header">
                <a href="${BASE_URL}/?r=mobile/user&id=${post.user_id}">${avatar}</a>
                <div class="moment-user-info">
                    <a href="${BASE_URL}/?r=mobile/user&id=${post.user_id}" class="moment-username">${escapeHtml(post.username || '')} ${onlineBadgeHtml}</a>
                    <div class="moment-meta">
                        <div class="moment-time">${post.time_ago || ''}</div>
                        ${post.ip ? '<div class="moment-ip">' + post.ip.replace(/^中国\s*/, '').replace(/^CHINA\s*/i, '') + '</div>' : ''}
                    </div>
                </div>
                <div class="moment-more-btn" onclick="HuSNS.toggleDropdown(this, event)">
                    <span class="moment-more">⋮</span>
                    <div class="moment-dropdown">
                        <button class="moment-dropdown-item" onclick="showConfirm('确定要移除收藏吗？', function(r){if(r){removeFavorite(${post.id});}})">
                            <span class="item-icon"><span class="iconify" data-icon="mdi:star"></span></span>取消收藏
                        </button>
                        <button class="moment-dropdown-item" onclick="openShareModal('${BASE_URL}/?r=mobile/detail&id=${post.id}', '${contentShort}')">
                            <span class="item-icon"><span class="iconify" data-icon="mdi:share-outline"></span></span>分享
                        </button>
                        <div class="dropdown-divider"></div>
                        <button class="moment-dropdown-item" onclick="HuSNS.reportPost(${post.id})">
                            <span class="item-icon"><span class="iconify" data-icon="mdi:flag-outline"></span></span>举报
                        </button>
                    </div>
                </div>
            </div>
            <div class="moment-content-link">
                <div class="moment-content">${post.content || ''}</div>
                ${imagesHtml}
                ${videoHtml}
                ${locationHtml}
            </div>
            <div class="moment-actions">
                <button class="moment-action ${isLiked}" data-action="like" data-id="${post.id}">
                    <span class="moment-action-icon"><span class="iconify" data-icon="${isLiked ? 'mdi:heart' : 'mdi:heart-outline'}"></span></span>
                    <span class="moment-action-count">${likesCount}</span>
                    <span class="moment-action-text">赞</span>
                </button>
                <button class="moment-action comment-btn" data-post-id="${post.id}">
                    <span class="moment-action-icon"><span class="iconify" data-icon="mdi:comment-outline"></span></span>
                    <span class="moment-action-count">${commentsCount}</span>
                    <span class="moment-action-text">评论</span>
                </button>
                <button class="moment-action" onclick="openShareModal('${BASE_URL}/?r=mobile/detail&id=${post.id}', '${contentShort}')">
                    <span class="moment-action-icon"><span class="iconify" data-icon="mdi:share-outline"></span></span>
                    <span class="moment-action-text">分享</span>
                </button>
                <button class="moment-action" onclick="window.location.href='${BASE_URL}/?r=mobile/detail&id=${post.id}'">
                    <span class="moment-action-icon"><span class="iconify" data-icon="mdi:eye-outline"></span></span>
                    <span class="moment-action-count">${viewsCount}</span>
                    <span class="moment-action-text">阅读</span>
                </button>
            </div>
        </div>
    `;
}

function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/[<>\"'&]/g, function(c) {
        return {'<':'&lt;','>':'&gt;','\"':'&quot;',"'":"&#39;",'&':'&amp;'}[c];
    });
}

async function loadMoreFavorites() {
    if (isLoading || !hasMore) return;
    currentPage++;
    isLoading = true;
    
    const btn = document.getElementById('loadMoreBtn');
    btn.textContent = '加载中...';
    
    await loadFavorites();
    
    btn.textContent = hasMore ? '加载更多' : '没有更多了';
    isLoading = false;
}

// 取消收藏
function removeFavorite(postId) {
    fetch(BASE_URL + '/?r=mobileApi/unfavorite', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({post_id: postId})
    })
    .then(res => res.json())
    .then(data => {
        if (data.code === 0 || data.success) {
            showToast('已取消收藏');
            const card = document.querySelector('.moment-card[data-id="' + postId + '"]');
            if (card) {
                card.style.transition = 'all 0.3s';
                card.style.opacity = '0';
                card.style.transform = 'translateX(-100%)';
                setTimeout(() => card.remove(), 300);
            }
        } else {
            showToast(data.message || '操作失败');
        }
    })
    .catch(() => showToast('操作失败'));
}

// 点赞功能
document.addEventListener('click', function(e) {
    const btn = e.target.closest('[data-action="like"]');
    if (!btn) return;
    
    const postId = btn.dataset.id;
    const isLiked = btn.classList.contains('liked');
    const countEl = btn.querySelector('.moment-action-count');
    const count = parseInt(countEl.textContent) || 0;
    
    btn.classList.toggle('liked');
    countEl.textContent = isLiked ? Math.max(0, count - 1) : count + 1;
    
    // 调用API - 取消点赞调用unlike，点赞调用like
    const apiUrl = isLiked ? BASE_URL + '/?r=mobileApi/unlike' : BASE_URL + '/?r=mobileApi/like';
    fetch(apiUrl, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({id: postId})
    }).then(r => r.json()).then(data => {
        if (data.code !== 0) {
            // 失败回滚
            btn.classList.toggle('liked');
            countEl.textContent = count;
            showToast(data.message || '操作失败');
        }
    }).catch(() => {
        btn.classList.toggle('liked');
        countEl.textContent = count;
    });
});

// ========== 视频缩略图生成功能 ==========
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 #f0f0f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
    `;
    header.innerHTML = `
        <span style="font-size: 16px; font-weight: 600; color: #333;">📍 ${escapeHtml(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);
        }
    });
}

