/**
 * 聊天页面主入口模块
 */

let currentUser = null;
let pollTimer = null;
let lastMessageId = 0;

document.addEventListener('DOMContentLoaded', function() {
    loadCurrentUser();
    loadPartnerInfo();
    loadMessages();
    
    const container = document.getElementById('messagesContainer');
    container.addEventListener('scroll', function() {
        if (window.hasMore !== undefined && window.isLoading !== undefined) {
            if (container.scrollTop === 0 && window.hasMore && !window.isLoading) {
                loadMoreMessages();
            }
        }
    });

    const input = document.getElementById('messageInput');
    input.addEventListener('input', function() {
        const btn = document.getElementById('sendBtn');
        btn.disabled = !this.value.trim();
    });
    
    // 启动消息轮询
    startMessagePolling();
    
    // 页面卸载时停止轮询
    window.addEventListener('beforeunload', stopMessagePolling);
});

function startMessagePolling() {
    pollTimer = setInterval(checkNewMessages, 3000);
}

function stopMessagePolling() {
    if (pollTimer) {
        clearInterval(pollTimer);
        pollTimer = null;
    }
}

function checkNewMessages() {
    if (!partnerId || !baseUrl) return;
    
    const url = baseUrl + '/?r=mobileApi/getMessages&user_id=' + partnerId + '&page=1';
    fetch(url)
        .then(r => r.json())
        .then(data => {
            if (data && data.code === 0 && data.data && data.data.items && data.data.items.length > 0) {
                const messages = data.data.items;
                const newMessages = [];
                
                // 找出比lastMessageId新的消息，并且不在已渲染列表中的消息
                messages.forEach(msg => {
                    if (msg.id && msg.id > lastMessageId) {
                        // 检查消息是否已经在DOM中
                        const existingMsg = document.querySelector('[data-msg-id="' + msg.id + '"]');
                        if (!existingMsg) {
                            newMessages.push(msg);
                        }
                        lastMessageId = Math.max(lastMessageId, msg.id);
                    }
                });
                
                // 如果有新消息，添加到消息列表
                if (newMessages.length > 0) {
                    renderMessages(newMessages, false);
                }
                
                // 更新lastMessageId（取最大的消息ID）
                if (messages.length > 0) {
                    const maxId = Math.max(...messages.map(m => m.id || 0));
                    if (maxId > lastMessageId) {
                        lastMessageId = maxId;
                    }
                }
            }
        })
        .catch(err => {
            console.error('检查新消息失败:', err);
        });
}

function loadCurrentUser() {
    fetch(baseUrl + '/?r=mobileApi/userInfo')
        .then(r => r.json())
        .then(data => {
            if (data && data.code === 0 && data.data && data.data.user) {
                currentUser = data.data.user;
            }
        })
        .catch(err => {
            console.error('加载用户信息失败:', err);
        });
}

function loadPartnerInfo() {
    if (!partnerId) return;
    
    fetch(baseUrl + '/?r=mobileApi/userInfo&id=' + partnerId)
        .then(r => r.json())
        .then(data => {
            if (data && data.code === 0 && data.data && data.data.user) {
                const user = data.data.user;
                const avatarElement = document.getElementById('partnerAvatar');
                const nameElement = document.getElementById('partnerName');
                
                if (avatarElement) {
                    const hasValidAvatar = user.avatar && user.avatar !== 'null' && user.avatar !== 'undefined' && user.avatar.trim() !== '';
                    const avatarUrl = hasValidAvatar 
                        ? (user.avatar.startsWith('http') ? user.avatar : baseUrl + '/uploads/' + user.avatar) 
                        : baseUrl + '/templates/mobile/images/avatar_default.png';
                    avatarElement.src = avatarUrl;
                }
                
                if (nameElement) {
                    nameElement.textContent = user.nickname || user.username || partnerName;
                }
            }
        })
        .catch(err => {
            console.error('加载对方信息失败:', err);
        });
}

function sendMessage() {
    const input = document.getElementById('messageInput');
    const content = input.value.trim();
    
    if (!content) return;
    
    const btn = document.getElementById('sendBtn');
    btn.disabled = true;
    
    fetch(baseUrl + '/?r=mobileApi/sendMessage', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({user_id: partnerId, content: content})
    })
    .then(r => r.json())
    .then(data => {
        if (data.code === 0) {
            input.value = '';
            const container = document.getElementById('messagesContainer');
            const item = document.createElement('div');
            item.className = 'message-item me';
            item.innerHTML = `
                <div class="message-content">
                    <div class="message-bubble">${content}</div>
                    <div class="message-time">刚刚</div>
                </div>
            `;
            container.appendChild(item);
            scrollToBottom();
        } else {
            showToast(data.message || '发送失败');
        }
    })
    .catch(() => {
        showToast('发送失败');
    })
    .finally(() => {
        btn.disabled = false;
    });
}

function goBack() {
    window.location.href = baseUrl + '/?r=mobile/messages';
}

function handleKeyup(event) {
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
    }
}

function showUserProfile(userId, username, avatarUrl) {
    const overlay = document.createElement('div');
    overlay.className = 'profile-overlay';
    overlay.id = 'profileOverlay';
    overlay.onclick = closeProfileModal;
    
    const modal = document.createElement('div');
    modal.className = 'profile-modal';
    modal.onclick = (e) => e.stopPropagation();
    
    modal.innerHTML = `
        <div class="profile-header">
            <img class="profile-avatar" src="${avatarUrl}" alt="${username}">
            <div class="profile-name">${username}</div>
            <button class="profile-close" onclick="closeProfileModal()">×</button>
        </div>
        <div class="profile-content">
            <div class="profile-stats">
                <div class="stat-item">
                    <span class="stat-value">--</span>
                    <span class="stat-label">动态</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value">--</span>
                    <span class="stat-label">关注</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value">--</span>
                    <span class="stat-label">粉丝</span>
                </div>
            </div>
            <div class="profile-actions">
                <button class="profile-btn profile-btn-primary" onclick="goToUserProfile(${userId})">查看主页</button>
                <button class="profile-btn profile-btn-secondary" onclick="closeProfileModal()">关闭</button>
            </div>
        </div>
    `;
    
    overlay.appendChild(modal);
    document.body.appendChild(overlay);
    
    const apiUrl = baseUrl + '/?r=mobileApi/userInfo&id=' + userId;
    
    fetch(apiUrl)
        .then(r => r.json())
        .then(data => {
            if (data && data.code === 0 && data.data && data.data.stats) {
                const stats = data.data.stats;
                modal.querySelector('.stat-item:nth-child(1) .stat-value').textContent = stats.post_count || 0;
                modal.querySelector('.stat-item:nth-child(2) .stat-value').textContent = stats.following || 0;
                modal.querySelector('.stat-item:nth-child(3) .stat-value').textContent = stats.followers || 0;
            }
        })
        .catch(err => {
            console.error('加载用户信息失败:', err);
        });
}

function closeProfileModal() {
    const overlay = document.getElementById('profileOverlay');
    if (overlay) {
        overlay.remove();
    }
}

function goToUserProfile(userId) {
    closeProfileModal();
    window.location.href = baseUrl + '/?r=mobile/user&id=' + userId;
}