/**
 * 消息加载模块
 */

window.page = 1;
window.hasMore = true;
window.isLoading = false;
window.messageCache = {}; // 消息缓存，用于判断是否可撤回

function loadMessages() {
    if (!partnerId || !baseUrl) return;
    
    fetch(baseUrl + '/?r=mobileApi/getMessages&user_id=' + partnerId + '&page=1')
        .then(r => r.json())
        .then(data => {
            if (data && data.code === 0 && data.data && data.data.items && data.data.items.length > 0) {
                renderMessages(data.data.items, true);
                hasMore = data.data.pagination && data.data.pagination.has_more;
            }
        })
        .catch(err => {
            console.error('加载消息失败:', err);
        });
}

document.addEventListener('DOMContentLoaded', function() {
    loadMessages();
    
    setTimeout(() => {
        if (typeof generateChatVideoThumbnails === 'function') {
            generateChatVideoThumbnails();
        }
    }, 500);
});

function loadMoreMessages() {
    if (!hasMore || isLoading) return;
    
    isLoading = true;
    page++;
    
    fetch(baseUrl + '/?r=mobileApi/getMessages&user_id=' + partnerId + '&page=' + page)
        .then(r => r.json())
        .then(data => {
            if (data && data.code === 0 && data.data && data.data.items && data.data.items.length > 0) {
                renderMessages(data.data.items, false);
                hasMore = data.data.pagination && data.data.pagination.has_more;
            } else {
                hasMore = false;
            }
            isLoading = false;
        })
        .catch(err => {
            isLoading = false;
        });
}

/**
 * 显示消息操作菜单
 * @param {number} msgId 消息ID
 * @param {boolean} isMe 是否是自己的消息
 * @param {HTMLElement} item 消息元素
 * @param {number} createdAt 消息创建时间戳
 */
function showMessageMenu(msgId, isMe, item, createdAt) {
    closeMessageMenu();
    
    var menu = document.createElement('div');
    menu.className = 'message-menu';
    menu.id = 'messageMenu-' + msgId;
    
    // 判断是否在撤回时间范围内（2分钟内）
    var canRecall = false;
    if (isMe && createdAt) {
        var now = Math.floor(Date.now() / 1000);
        var elapsed = now - createdAt;
        canRecall = elapsed <= 120; // 2分钟
    }
    
    // 构建菜单项
    var menuItems = '';
    
    if (isMe) {
        // 我的消息：可以撤回（2分钟内）或删除
        if (canRecall) {
            menuItems += '<div class="menu-item recall" onclick="recallMessage(' + msgId + ')"><span class="menu-icon">↩</span>撤回</div>';
        }
        menuItems += '<div class="menu-item delete" onclick="deleteMessage(' + msgId + ')"><span class="menu-icon">🗑</span>删除</div>';
    } else {
        // 对方消息：仅可删除（仅删除本地显示）
        menuItems += '<div class="menu-item delete" onclick="deleteMessageForMe(' + msgId + ')"><span class="menu-icon">🗑</span>删除</div>';
    }
    
    menu.innerHTML = menuItems;
    menu.style.position = 'fixed';
    
    // 计算菜单位置
    var rect = item.getBoundingClientRect();
    var menuWidth = 120;
    var menuHeight = isMe ? (canRecall ? 88 : 44) : 44;
    
    // 水平居中但不超过屏幕边界
    var leftPos = rect.left + rect.width / 2;
    if (leftPos - menuWidth / 2 < 10) {
        leftPos = menuWidth / 2 + 10;
    } else if (leftPos + menuWidth / 2 > window.innerWidth - 10) {
        leftPos = window.innerWidth - menuWidth / 2 - 10;
    }
    
    menu.style.left = leftPos + 'px';
    menu.style.top = (rect.top - 10) + 'px';
    menu.style.transform = 'translateX(-50%) translateY(-100%) scale(0.9)';
    menu.style.opacity = '0';
    
    document.body.appendChild(menu);
    
    // 触发动画
    requestAnimationFrame(function() {
        menu.classList.add('show');
        menu.style.transform = 'translateX(-50%) translateY(-100%) scale(1)';
        menu.style.opacity = '1';
    });
    
    // 点击其他地方关闭菜单
    setTimeout(function() {
        document.addEventListener('click', closeMessageMenu);
    }, 10);
}

function closeMessageMenu(e) {
    // 如果是点击菜单本身，不关闭
    if (e && e.target.closest('.message-menu')) {
        return;
    }
    
    var menus = document.querySelectorAll('.message-menu');
    menus.forEach(function(menu) {
        if (menu.classList.contains('show')) {
            menu.style.transform = 'translateX(-50%) translateY(-100%) scale(0.9)';
            menu.style.opacity = '0';
            setTimeout(function() {
                menu.remove();
            }, 200);
        } else {
            menu.remove();
        }
    });
    
    document.removeEventListener('click', closeMessageMenu);
}

/**
 * 撤回消息（仅对自己发送且2分钟内的消息有效）
 * @param {number} msgId 消息ID
 */
function recallMessage(msgId) {
    closeMessageMenu();
    
    fetch(baseUrl + '/?r=mobileApi/recallMessage', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'id=' + msgId
    })
    .then(r => r.json())
    .then(data => {
        if (data && data.code === 0) {
            // 撤回成功，更新消息显示
            var item = document.querySelector('[data-msg-id="' + msgId + '"]');
            if (item) {
                var bubble = item.querySelector('.message-bubble');
                if (bubble) {
                    bubble.innerHTML = '<em class="recalled-text">此消息已被撤回</em>';
                    bubble.style.color = '#999';
                    bubble.style.fontStyle = 'italic';
                }
                
                // 移除长按功能（被撤回的消息不可再操作）
                item.removeEventListener('longpress', null);
                item.removeEventListener('touchstart', null);
                item.style.pointerEvents = 'none';
            }
            showToast('已撤回');
        } else {
            showToast(data.message || '撤回失败');
        }
    })
    .catch(err => {
        showToast('撤回失败');
    });
}

/**
 * 删除消息（双向删除，发送方和接收方都看不到）
 * @param {number} msgId 消息ID
 */
function deleteMessage(msgId) {
    showToast('删除中...', 1000);
    closeMessageMenu();
    
    fetch(baseUrl + '/?r=mobileApi/deleteMessage', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'id=' + msgId
    })
    .then(r => r.json())
    .then(data => {
        if (data && data.code === 0) {
            var item = document.querySelector('[data-msg-id="' + msgId + '"]');
            if (item) {
                // 添加删除动画
                item.style.transition = 'all 0.3s ease';
                item.style.transform = 'scale(0.8)';
                item.style.opacity = '0';
                setTimeout(function() {
                    item.remove();
                }, 300);
            }
            showToast('已删除');
        } else {
            showToast(data.message || '删除失败');
        }
    })
    .catch(err => {
        showToast('删除失败');
    });
}

/**
 * 仅删除本地显示的消息（不影响对方）
 * @param {number} msgId 消息ID
 */
function deleteMessageForMe(msgId) {
    closeMessageMenu();
    
    var item = document.querySelector('[data-msg-id="' + msgId + '"]');
    if (item) {
        // 添加删除动画
        item.style.transition = 'all 0.3s ease';
        item.style.transform = 'scale(0.8)';
        item.style.opacity = '0';
        setTimeout(function() {
            item.remove();
        }, 300);
    }
    showToast('已删除');
}

function renderMessages(messages, isFirstLoad) {
    const container = document.getElementById('messagesContainer');
    
    if (isFirstLoad) {
        container.innerHTML = '';
    }

    messages.forEach(msg => {
        const item = document.createElement('div');
        const isMe = msg.is_me || msg.is_self;
        item.className = 'message-item ' + (isMe ? 'me' : 'other');
        
        const defaultAvatar = baseUrl + '/templates/mobile/images/avatar_default.png';
        const hasValidAvatar = msg.avatar && msg.avatar !== 'null' && msg.avatar !== 'undefined' && msg.avatar.trim() !== '';
        let avatarUrl = defaultAvatar;
        if (hasValidAvatar) {
            if (msg.avatar.startsWith('http')) {
                avatarUrl = msg.avatar;
            } else if (msg.avatar.startsWith('/')) {
                avatarUrl = baseUrl + msg.avatar;
            } else {
                avatarUrl = baseUrl + '/uploads/' + msg.avatar;
            }
        }
        
        let contentHtml = '';
        const isImage = (msg.type === 'image' || msg.image || (msg.content && (msg.content.endsWith('.jpg') || msg.content.endsWith('.jpeg') || msg.content.endsWith('.png') || msg.content.endsWith('.gif') || msg.content.endsWith('.webp'))));
        
        // 检测视频：包括类型标记、视频字段、文件扩展名，以及HTML视频标签
        const hasVideoTag = msg.content && msg.content.includes('<video');
        const isVideo = (msg.type === 'video' || msg.video || hasVideoTag || (msg.content && (msg.content.endsWith('.mp4') || msg.content.endsWith('.mov') || msg.content.endsWith('.avi') || msg.content.endsWith('.webm'))));
        
        if (isImage) {
            const imgUrl = msg.image || msg.content;
            const fullUrl = imgUrl.startsWith('http') ? imgUrl : baseUrl + '/uploads/' + imgUrl;
            contentHtml = `<img src="${fullUrl}" class="chat-image" onclick="openImageViewer('${fullUrl}')" style="max-width:200px;max-height:200px;border-radius:8px;">`;
        } else if (isVideo) {
            let videoUrl = msg.video || msg.content;
            let coverUrl = msg.cover || '';
            
            // 如果内容是HTML视频标签，提取src和poster
            if (hasVideoTag && msg.content) {
                const srcMatch = msg.content.match(/src=["']([^"']+)["']/);
                const posterMatch = msg.content.match(/poster=["']([^"']+)["']/);
                if (srcMatch) videoUrl = srcMatch[1];
                if (posterMatch) coverUrl = posterMatch[1];
            }
            
            // 清理URL中的无效值
            const isValidUrl = (url) => url && url !== 'null' && url !== 'undefined' && url.trim() !== '';
            videoUrl = isValidUrl(videoUrl) ? videoUrl : '';
            
            // 构建完整URL，避免重复路径
            const fullVideoUrl = videoUrl.startsWith('http') ? videoUrl : 
                                (videoUrl.startsWith('/') ? baseUrl + videoUrl : baseUrl + '/uploads/' + videoUrl);
            
            // 封面URL处理
            const hasValidCover = isValidUrl(coverUrl);
            const fullCoverUrl = hasValidCover && coverUrl.startsWith('http') ? coverUrl : 
                                (hasValidCover && coverUrl.startsWith('/') ? baseUrl + coverUrl : 
                                (hasValidCover ? baseUrl + '/uploads/' + coverUrl : ''));
            
            const hasCover = isValidUrl(fullCoverUrl);
            contentHtml = `<div class="chat-video-wrapper chat-video-thumbnail" data-video="${fullVideoUrl}" onclick="openMediaViewer('${fullVideoUrl}', 'video')"><div class="chat-video-thumb"><img class="chat-video-poster" src="${hasCover ? fullCoverUrl : ''}" style="width:100%;height:100%;object-fit:cover;border-radius:8px;background:${hasCover ? 'transparent' : '#000'};"><div class="video-overlay"><div class="video-play-icon">▶</div></div><div class="video-duration">${msg.duration || ''}</div></div></div>`;
        } else {
            contentHtml = `<div class="message-bubble">${msg.content}</div>`;
        }
        
        item.innerHTML = `
            ${!isMe ? `<img class="message-avatar cursor-pointer" src="${avatarUrl}" alt="${msg.username || ''}" onclick="showUserProfile(${msg.sender_id || 0}, '${msg.username || ''}', '${avatarUrl}')">` : ''}
            <div class="message-content">
                ${contentHtml}
                <div class="message-time">
                    ${msg.time_ago || msg.created_at || '刚刚'}
                    ${isMe ? `<span class="message-status ${msg.is_read ? 'read' : 'unread'}">${msg.is_read ? '已读' : '未读'}</span>` : ''}
                </div>
            </div>
            ${isMe ? `<img class="message-avatar cursor-pointer" src="${avatarUrl}" alt="${msg.username || ''}" onclick="showUserProfile(${msg.sender_id || 0}, '${msg.username || ''}', '${avatarUrl}')">` : ''}
        `;
        
        item.dataset.msgId = msg.id;
        item.dataset.isMe = isMe;
        item.dataset.createdAt = msg.created_at || 0;
        
        // 缓存消息时间用于撤回判断
        if (msg.id && msg.created_at) {
            messageCache[msg.id] = msg.created_at;
        }
        
        item.addEventListener('longpress', function() {
            showMessageMenu(msg.id, isMe, item, msg.created_at);
        });
        
        let touchTimer = null;
        item.addEventListener('touchstart', function(e) {
            touchTimer = setTimeout(function() {
                showMessageMenu(msg.id, isMe, item, msg.created_at);
            }, 500);
        });
        item.addEventListener('touchend', function() {
            if (touchTimer) {
                clearTimeout(touchTimer);
            }
        });
        item.addEventListener('touchcancel', function() {
            if (touchTimer) {
                clearTimeout(touchTimer);
            }
        });
        
        // 桌面端支持右键菜单
        item.addEventListener('contextmenu', function(e) {
            e.preventDefault();
            showMessageMenu(msg.id, isMe, item, msg.created_at);
        });
        
        if (!isFirstLoad) {
            container.insertBefore(item, container.firstChild);
        } else {
            container.appendChild(item);
        }
    });
    
    if (isFirstLoad) {
        scrollToBottom();
    }
    
    setTimeout(() => {
        generateChatVideoThumbnails();
    }, 100);
}

function scrollToBottom() {
    const container = document.getElementById('messagesContainer');
    setTimeout(() => {
        container.scrollTop = container.scrollHeight;
    }, 100);
}

function generateChatVideoThumbnails() {
    const videoThumbnails = document.querySelectorAll('.chat-video-thumbnail');
    videoThumbnails.forEach(container => {
        const videoUrl = container.getAttribute('data-video');
        const posterImg = container.querySelector('.chat-video-poster');
        
        if (!videoUrl || !posterImg) return;
        
        if (posterImg.src && posterImg.src !== '' && posterImg.src !== 'about:blank') {
            const isValidImageUrl = posterImg.src.match(/\.(jpg|jpeg|png|gif|webp)$/i);
            if (isValidImageUrl) return;
        }
        
        const video = document.createElement('video');
        video.src = videoUrl;
        video.crossOrigin = 'anonymous';
        video.preload = 'metadata';
        
        video.addEventListener('loadedmetadata', function() {
            video.currentTime = 0.1;
        });
        
        video.addEventListener('seeked', function() {
            try {
                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';
            } catch (e) {
                posterImg.style.background = '#333';
            }
        });
        
        video.addEventListener('error', function() {
            posterImg.style.background = '#1a1a1a';
        });
        
        video.load();
    });
}