/**
 * 用户页面 JavaScript
 * 包含用户资料加载、关注功能、内容切换等
 */

(function() {
    'use strict';

    // 配置参数，由页面传入
    window.HuSNS_User = window.HuSNS_User || {
        apiUrls: {
            userProfile: '/?r=mobileApi/userProfile',
            userPosts: '/?r=mobileApi/userPosts',
            userComments: '/?r=mobileApi/userComments',
            userFavorites: '/?r=mobileApi/userFavorites',
            follow: '/?r=mobileApi/follow',
            unfollow: '/?r=mobileApi/unfollow',
            like: '/mobile/api/like',
            unlike: '/mobile/api/unlike'
        },
        themeUrl: '',
        baseUrl: '',
        targetUserId: 0,
        currentUserId: 0,
        targetUsername: '',
        tab: 'posts'
    };

    // 辅助函数
    const getBaseUrl = () => window.HuSNS_User.baseUrl;
    const escapeHtml = (str) => str ? str.replace(/[<>"'&]/g, (c) => ({'<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;",'&':'&amp;'}[c])) : '';

    // 加载用户信息
    async function loadUserProfile() {
        const { targetUserId, targetUsername } = window.HuSNS_User;
        
        if (!targetUserId && !targetUsername) {
            document.querySelector('.user-page-content').innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon"><span class="iconify" data-icon="mdi:account-off-outline"></span></div>
                    <div class="empty-title">用户不存在</div>
                    <div class="empty-desc">该用户可能已被删除或不存在</div>
                </div>
            `;
            return;
        }
        
        try {
            let url = `${getBaseUrl()}${window.HuSNS_User.apiUrls.userProfile}`;
            if (targetUserId) {
                url += `&id=${targetUserId}`;
            } else if (targetUsername) {
                url += `&username=${encodeURIComponent(targetUsername)}`;
            }
            
            const response = await fetch(url);
            const result = await response.json();
            
            if (result.code === 0 && result.data && result.data.user) {
                renderUserProfile(result.data);
                // 用户信息加载完成后加载帖子
                loadUserPosts();
            } else {
                document.querySelector('.user-page-content').innerHTML = `
                    <div class="empty-state">
                        <div class="empty-icon"><span class="iconify" data-icon="mdi:account-off-outline"></span></div>
                        <div class="empty-title">用户不存在</div>
                        <div class="empty-desc">该用户可能已被删除或不存在</div>
                    </div>
                `;
            }
        } catch (err) {
            console.error('加载用户信息失败:', err);
            document.querySelector('.user-page-content').innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon"><span class="iconify" data-icon="mdi:alert-circle-outline"></span></div>
                    <div class="empty-title">加载失败</div>
                    <div class="empty-desc">请稍后重试</div>
                </div>
            `;
        }
    }
    
    // 渲染用户资料卡片
    function renderUserProfile(data) {
        const user = data.user;
        const uid = user.id;
        const isFollowing = data.is_following;
        const postsCount = data.stats ? data.stats.post_count : 0;
        const followsCount = data.stats ? data.stats.following : 0;
        const fansCount = data.stats ? data.stats.followers : 0;

        window.currentUserData = user;
        
        const avatarHtml = user.avatar && user.avatar.trim()
            ? `<img class="avatar" src="${user.avatar}" alt="${escapeHtml(user.username)}" onerror="this.src='${getBaseUrl()}/templates/mobile/images/avatar_default.png';">`
            : `<img class="avatar" src="${getBaseUrl()}/templates/mobile/images/avatar_default.png" alt="${escapeHtml(user.username)}">`;
        
        const bioText = user.bio ? escapeHtml(user.bio) : '这个人很懒，什么都没写';
        
        const vipBadge = user.is_vip ? '<span class="user-vip-badge">VIP</span>' : '';
        const onlineBadge = user.is_online ? '<span class="user-online-badge" title="在线"></span>' : '<span class="user-online-badge offline" title="离线"></span>';
        
        let actionBtns = '';
        const { currentUserId, settings } = window.HuSNS_User;
        
        if (currentUserId && uid === currentUserId) {
            actionBtns = '<a href="' + getBaseUrl() + '/?r=mobile/editProfile" class="user-action-btn primary">编辑资料</a>';
        } else if (uid) {
            actionBtns = `
                <button class="user-action-btn primary ${isFollowing ? 'followed' : ''}" id="followBtn" onclick="handleFollow(parseInt(${uid}))">
                    ${isFollowing ? '已关注' : '+ 关注'}
                </button>
                ${settings && settings.messageEnabled ? '<button class="user-action-btn secondary" onclick="handleMessage(' + uid + ')">私信</button>' : ''}
            `;
        }
        
        const activeTab = window.HuSNS_User.tab;
        
        const backgroundHtml = user.background ? `
            <div class="user-profile-background" style="background-image: url('${user.background}'); background-repeat: no-repeat; background-size: 100% 100%; background-position: center;"></div>
        ` : `
            <div class="user-profile-background"></div>
        `;
        
        const profileHtml = `
            <div class="user-profile-card">
                ${backgroundHtml}
                <div class="user-profile-header">
                    <div class="user-avatar-wrap">
                        <a href="${getBaseUrl()}/?r=mobile/user&id=${encodeURIComponent(uid)}">${avatarHtml}</a>
                    </div>
                    <div class="user-info">
                        <div class="user-name-row">
                            <span class="user-label">用户名：</span>
                            <span class="user-nickname">${escapeHtml(user.username)}</span>
                            ${vipBadge}
                            ${onlineBadge}
                        </div>
                        <div class="user-bio-row">
                            <span class="user-bio-label">个人简介：</span>
                            <span class="user-bio-text">${bioText}</span>
                        </div>
                        <div class="user-meta">ID: ${uid}</div>
                    </div>
                </div>
                
                <div class="user-stats-actions-row">
                    <div class="user-stats-row">
                        <a href="${getBaseUrl()}/?r=mobile/user&id=${encodeURIComponent(uid)}&tab=posts" class="user-stat-item">
                            <div class="user-stat-num">${postsCount}</div>
                            <div class="user-stat-label">帖子</div>
                        </a>
                        <a href="${getBaseUrl()}/?r=mobile/fans&tab=following" class="user-stat-item">
                            <div class="user-stat-num">${followsCount}</div>
                            <div class="user-stat-label">关注</div>
                        </a>
                        <a href="${getBaseUrl()}/?r=mobile/fans&tab=followers" class="user-stat-item">
                            <div class="user-stat-num">${fansCount}</div>
                            <div class="user-stat-label">粉丝</div>
                        </a>
                        <a href="${getBaseUrl()}/?r=mobile/favorites" class="user-stat-item">
                            <div class="user-stat-num">${data.stats?.favorites || 0}</div>
                            <div class="user-stat-label">收藏</div>
                        </a>
                    </div>
                    <div class="user-action-btns">
                        ${actionBtns}
                    </div>
                </div>
            </div>
            
            <div class="user-profile-card">
                <div class="content-tab-nav">
                    <a href="${getBaseUrl()}/?r=mobile/user&id=${uid}&tab=posts" class="content-tab-link ${activeTab === 'posts' || activeTab === '' ? 'active' : ''}">帖子</a>
                    <a href="${getBaseUrl()}/?r=mobile/user&id=${encodeURIComponent(uid)}&tab=replies" class="content-tab-link ${activeTab === 'replies' ? 'active' : ''}">回复</a>
                    <a href="${getBaseUrl()}/?r=mobile/user&id=${encodeURIComponent(uid)}&tab=favorites" class="content-tab-link ${activeTab === 'favorites' ? 'active' : ''}">收藏</a>
                </div>
            </div>
        `;
        
        document.querySelector('.user-page-content').innerHTML = profileHtml + `
            <div id="postListContainer">
                <div class="loading-state">
                    <div class="loading-spinner"></div>
                    <div class="loading-text">加载中...</div>
                </div>
            </div>
        `;
    }
    
    // 生成头像HTML
    function getAvatarHtml(avatar, username, size = 42) {
        const baseUrl = getBaseUrl();
        if (avatar && typeof avatar === 'string' && avatar.trim()) {
            return `<img class="avatar post-header-avatar" src="${avatar}" alt="${escapeHtml(username)}" style="width:${size}px;height:${size}px;border-radius:6px;object-fit:cover;" onerror="this.src='${baseUrl}/templates/mobile/images/avatar_default.png';">`;
        } else {
            return `<img class="avatar post-header-avatar" src="${baseUrl}/templates/mobile/images/avatar_default.png" alt="${escapeHtml(username)}" style="width:${size}px;height:${size}px;border-radius:6px;object-fit:cover;">`;
        }
    }
    
    // 生成评论卡片HTML（用于回复列表）
    function createCommentCard(comment) {
        const avatarHtml = getAvatarHtml(comment.avatar, comment.username);
        const postLink = `${getBaseUrl()}/?r=mobile/detail&id=${comment.post_id}`;
        const userLink = `${getBaseUrl()}/?r=mobile/user&id=${comment.user_id}`;
        const isOnline = comment.is_online || false;
        const onlineBadgeHtml = isOnline 
            ? '<span class="user-online-badge" title="在线"></span>' 
            : '<span class="user-online-badge offline" title="离线"></span>';
        
        // 被评论的帖子作者信息
        const postUserLink = `${getBaseUrl()}/?r=mobile/user&id=${comment.post_user_id}`;
        const postAvatarHtml = getAvatarHtml(comment.post_avatar, comment.post_username, 32);
        
        return `
            <div class="post-card" data-id="${comment.id}">
                <div class="post-header">
                    <a href="${userLink}">${avatarHtml}</a>
                    <div class="post-header-info">
                        <a href="${userLink}" class="post-header-username">${escapeHtml(comment.username || '')} ${onlineBadgeHtml}</a>
                        <div class="post-meta">
                            <div class="post-header-time">${comment.time_ago || ''}</div>
                        </div>
                    </div>
                </div>
                <div style="text-decoration: none; display: block;">
                    <div class="post-body">${comment.content || ''}</div>
                </div>
                <div style="padding: 8px 16px 12px 70px; background: var(--background-color); border-radius: 8px; margin: 0 16px 12px;">
                    <div style="font-size: 13px; color: #666; display: flex; align-items: center; gap: 8px;">
                        <span>回复</span>
                        <a href="${postUserLink}" style="text-decoration: none; color: var(--primary-color);">@${escapeHtml(comment.post_username || '')}</a>
                        <span style="color: #999;">:</span>
                        <span style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${escapeHtml(comment.post_content || '')}</span>
                    </div>
                </div>
            </div>
        `;
    }
    
    // 根据tab加载不同内容
    function loadUserContent(tab) {
        const { targetUserId, currentUserId } = window.HuSNS_User;
        if (!targetUserId) return;
        
        const container = document.getElementById('postListContainer');
        container.innerHTML = `
            <div class="loading-state">
                <div class="loading-spinner"></div>
                <div class="loading-text">加载中...</div>
            </div>
        `;
        
        let apiUrl = '';
        let emptyMsg = '';
        
        switch(tab) {
            case 'posts':
                apiUrl = `${getBaseUrl()}${window.HuSNS_User.apiUrls.userPosts}&user_id=${targetUserId}&page=1`;
                emptyMsg = currentUserId && targetUserId === currentUserId ? '快来发布你的第一条内容吧' : '该用户还没有发布任何内容';
                break;
            case 'replies':
                apiUrl = `${getBaseUrl()}${window.HuSNS_User.apiUrls.userComments}&user_id=${targetUserId}&page=1`;
                emptyMsg = currentUserId && targetUserId === currentUserId ? '你还没有评论过任何内容' : '该用户还没有评论过任何内容';
                break;
            case 'favorites':
                apiUrl = `${getBaseUrl()}${window.HuSNS_User.apiUrls.userFavorites}&user_id=${targetUserId}&page=1`;
                emptyMsg = currentUserId && targetUserId === currentUserId ? '你还没有收藏任何内容' : '该用户还没有收藏任何内容';
                break;
            default:
                apiUrl = `${getBaseUrl()}${window.HuSNS_User.apiUrls.userPosts}&user_id=${targetUserId}&page=1`;
                emptyMsg = '暂无内容';
        }
        
        fetch(apiUrl)
            .then(response => response.json())
            .then(result => {
                if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
                    let html = '';
                    result.data.items.forEach(item => {
                        if (tab === 'replies') {
                            html += createCommentCard(item);
                        } else {
                            html += HuSNS.createPostHTML(item);
                        }
                    });
                    container.innerHTML = html;
                    // 生成视频缩略图
                    setTimeout(() => generateVideoThumbnails(), 100);
                } else {
                    container.innerHTML = `
                        <div class="empty-state">
                            <div class="empty-icon"><span class="iconify" data-icon="mdi:email-open-outline"></span></div>
                            <div class="empty-title">暂无内容</div>
                            <div class="empty-desc">${emptyMsg}</div>
                        </div>
                    `;
                }
            })
            .catch(err => {
                console.error('加载内容失败:', err);
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-icon"><span class="iconify" data-icon="mdi:alert-circle-outline"></span></div>
                        <div class="empty-title">加载失败</div>
                        <div class="empty-desc">请稍后重试</div>
                    </div>
                `;
            });
    }
    
    // 从API加载用户帖子（兼容旧代码）
    function loadUserPosts() {
        loadUserContent(window.HuSNS_User.tab);
    }
    
    // 页面加载完成后获取用户信息和帖子
    document.addEventListener('DOMContentLoaded', function() {
        loadUserProfile();
        
        // 标签切换事件
        document.addEventListener('click', function(e) {
            const tab = e.target.closest('.content-tab-link');
            if (tab) {
                const href = tab.getAttribute('href');
                if (href && href.includes('tab=')) {
                    const match = href.match(/tab=(\w+)/);
                    if (match) {
                        const tabName = match[1];
                        // 更新active状态
                        document.querySelectorAll('.content-tab-link').forEach(t => t.classList.remove('active'));
                        tab.classList.add('active');
                        // 加载内容
                        loadUserContent(tabName);
                    }
                }
            }
        });
    });
    
    // 显示位置地图弹窗
    window.showLocationMap = function(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;">📍 ${escapeHtml(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 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: 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: 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: var(--card-color); 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: var(--danger-color); 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: var(--primary-color);
            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: var(--background-color);
            color: var(--text-color);
            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);
            }
        });
    };
    
    // 关注/取消关注
    window.handleFollow = function(userId) {
        // 检查登录状态
        if (!checkLogin()) {
            if (typeof openLoginModal === 'function') {
                openLoginModal();
            } else if (typeof openModal === 'function') {
                openModal('loginModal');
            } else {
                showToast('请先登录');
            }
            return;
        }
        const btn = document.getElementById('followBtn');
        if (!btn) return;
        
        const isFollowing = btn.textContent.includes('已关注');
        
        // 根据当前状态决定调用关注还是取消关注接口
        const apiUrl = isFollowing 
            ? `${getBaseUrl()}${window.HuSNS_User.apiUrls.unfollow}`
            : `${getBaseUrl()}${window.HuSNS_User.apiUrls.follow}`;
        
        fetch(apiUrl, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({user_id: userId})
        })
        .then(res => res.json())
        .then(data => {
            if (data.success || data.code === 0) {
                if (isFollowing) {
                    btn.textContent = '+ 关注';
                    btn.classList.remove('followed');
                    showToast('已取消关注');
                } else {
                    btn.textContent = '已关注';
                    btn.classList.add('followed');
                    showToast('关注成功');
                }
            } else {
                showToast(data.message || '操作失败');
            }
        })
        .catch(() => {
            showToast('操作失败，请重试');
        });
    };
    
    // 私信
    window.handleMessage = function(userId) {
        // 检查登录状态
        if (!checkLogin()) {
            if (typeof openLoginModal === 'function') {
                openLoginModal();
            } else if (typeof openModal === 'function') {
                openModal('loginModal');
            } else {
                showToast('请先登录');
            }
            return;
        }
        // 检查是否给自己发私信
        if (window.user_id && window.user_id == userId) {
            showToast('不能给自己发私信');
            return;
        }
        const user = window.currentUserData;
        const avatar = user && user.avatar ? user.avatar : `${getBaseUrl()}/templates/mobile/images/avatar_default.png`;
        const username = user && user.username ? user.username : '';
        const bio = user && user.bio ? user.bio : '';
        openMessageModal(userId, username, avatar, bio);
    };
    
    // 分享弹窗
    function openShareModal(url, title) {
        if (navigator.share) {
            navigator.share({
                title: '分享动态',
                text: title,
                url: url
            }).catch(() => {});
        } else {
            showToast('链接：' + url);
        }
    }
    
    // 点赞功能由 app-layout.js 统一处理，此处不再重复绑定
    
    // ========== 视频缩略图生成功能 ==========
    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';
            });
        });
    }
    
    })();