// 使用模板中定义的 BASE_URL，避免重复声明

// 获取当前页面类型（从URL参数或配置中获取）
function getCurrentType() {
    // 优先从URL参数获取
    const urlParams = new URLSearchParams(window.location.search);
    const urlType = urlParams.get('type');
    if (urlType) {
        return urlType.toLowerCase();
    }
    // 从配置中获取
    return window.HuSNS_Notification?.currentType || 'all';
}

let currentType = getCurrentType();

document.addEventListener('DOMContentLoaded', function() {
    // 重新获取类型，确保正确
    currentType = getCurrentType();
    
    loadNotifications();
    fetchNotificationCount();
    
    // 标签切换
    document.querySelectorAll('.category-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            const type = this.dataset.type;
            if (type && type !== currentType) {
                // 修复URL格式：使用 & 连接参数
                window.location.href = BASE_URL + '/?r=mobile/notification&type=' + type;
            }
        });
    });
});

async function loadNotifications() {
    const container = document.getElementById('notificationList');
    container.innerHTML = `
        <div class="loading-state">
            <div class="loading-spinner"></div>
            <div class="loading-text">加载中...</div>
        </div>
    `;
    
    try {
        // 如果是私信类型，加载私信对话列表
        if (currentType === 'message') {
            const response = await fetch(BASE_URL + '/?r=mobileApi/getConversations');
            const result = await response.json();
            
            if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
                renderConversations(result.data.items);
            } else {
                container.innerHTML = `
                    <div class="empty-notifications">
                        <div class="empty-icon">
                            <svg viewBox="0 0 24 24" fill="currentColor"><path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/></svg>
                        </div>
                        <div class="empty-title">暂无私信</div>
                        <div class="empty-desc">去关注用户或被关注后开始聊天吧</div>
                    </div>
                `;
            }
            return;
        }
        
        // 尝试获取通知列表
        const response = await fetch(BASE_URL + '/?r=mobileApi/notifications&type=' + currentType + '&page=1');
        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(notif => {
                html += createNotificationItem(notif);
            });
            container.innerHTML = html;
            initNotificationEvents();
            
            // 更新页脚导航的消息数量（使用通知未读数量）
            updateFooterNotificationCount(result.data.notification_unread || result.data.unread_count || 0);
        } else {
            // 如果API没有返回数据，显示对应类型的空状态
            const emptyTexts = {
                'all': '暂无消息',
                'mentions': '暂无@我的消息',
                'likes': '暂无赞消息',
                'comments': '暂无评论消息',
                'follow': '暂无关注消息'
            };
            const emptyDesc = {
                'all': '当有新消息时会显示在这里',
                'mentions': '当有人@你时会显示在这里',
                'likes': '当有人赞你的动态时会显示在这里',
                'comments': '当有人评论你的动态时会显示在这里',
                'follow': '当有人关注你时会显示在这里'
            };
            
            container.innerHTML = `
                <div class="empty-notifications">
                    <div class="empty-icon">
                        <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/></svg>
                    </div>
                    <div class="empty-title">${emptyTexts[currentType] || '暂无消息'}</div>
                    <div class="empty-desc">${emptyDesc[currentType] || '当有新消息时会显示在这里'}</div>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载通知失败:', error);
        container.innerHTML = `
            <div class="empty-notifications">
                <div class="empty-icon">
                    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/></svg>
                </div>
                <div class="empty-title">加载失败</div>
                <div class="empty-desc">请检查网络连接后重试</div>
            </div>
        `;
    }
}

// 渲染私信对话列表
function renderConversations(conversations) {
    const container = document.getElementById('notificationList');
    container.innerHTML = '';

    conversations.forEach(conv => {
        const item = document.createElement('div');
        item.className = 'conversation-item';
        item.onclick = () => openChat(conv.partner_id, conv.username, conv.avatar);
        
        // 格式化消息预览
        const preview = formatMessagePreview(conv.last_message);
        
        item.innerHTML = `
            <div class="conversation-avatar-wrap">
                <img class="conversation-avatar" src="${conv.avatar || BASE_URL + '/templates/mobile/images/avatar_default.png'}" alt="${conv.username}">
                ${conv.is_online ? '<div class="avatar-online"></div>' : ''}
            </div>
            <div class="conversation-info">
                <div class="conversation-name">${escapeHtml(conv.username)}</div>
                <div class="conversation-preview">${preview}</div>
            </div>
            <div class="conversation-meta">
                <div class="conversation-time">${conv.time_ago}</div>
                ${conv.unread_count > 0 ? `<div class="conversation-unread">${conv.unread_count}</div>` : ''}
            </div>
        `;
        
        container.appendChild(item);
    });
}

// 格式化消息预览
function formatMessagePreview(message) {
    if (!message) return '';
    
    // 如果包含图片标签
    if (message.includes('<img') || message.includes('[图片]')) {
        return '📷 图片';
    }
    // 如果包含视频标签
    if (message.includes('<video') || message.includes('[视频]')) {
        return '🎬 视频';
    }
    // 如果包含语音标签
    if (message.includes('<audio') || message.includes('[语音]')) {
        return '🎤 语音';
    }
    // 如果包含红包
    if (message.includes('red-packet') || message.includes('[红包]')) {
        return '🧧 红包';
    }
    // 如果包含礼物
    if (message.includes('gift') || message.includes('[礼物]')) {
        return '🎁 礼物';
    }
    // 如果包含位置
    if (message.includes('[位置]') || message.includes('location')) {
        return '📍 位置';
    }
    
    // 如果包含其他HTML标签，提取纯文本
    if (/<[^>]+>/.test(message)) {
        const temp = document.createElement('div');
        temp.innerHTML = message;
        return temp.textContent || temp.innerText || '[消息]';
    }
    
    return escapeHtml(message);
}

async function openChat(userId, username, avatar) {
    // 先标记消息为已读
    try {
        await fetch(BASE_URL + '/?r=mobileApi/markMessagesRead', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'user_id=' + userId
        });
    } catch (e) {
        console.error('标记消息已读失败', e);
    }
    
    // 更新页脚导航的消息数量
    await fetchNotificationCount();
    
    // 跳转到聊天页面
    window.location.href = BASE_URL + '/?r=mobile/chat&user_id=' + userId + '&username=' + encodeURIComponent(username);
}

function createNotificationItem(notif) {
    const avatar = notif.avatar ? 
        `<img class="notification-avatar" src="${escapeHtml(notif.avatar)}" alt="">` :
        `<img class="notification-avatar" src="${BASE_URL}/templates/mobile/images/avatar_default.png" alt="">`;
    
    const typeIconClass = notif.type || 'system';
    const postContent = notif.post_content ? `"${escapeHtml(notif.post_content.substring(0, 30))}..."` : '';
    const userLink = BASE_URL + '/?r=mobile/user&id=' + (notif.user_id || 0);
    const timeAgo = notif.time_ago || formatTime(notif.created_at);
    
    // 生成类型标签
    const typeLabel = {
        'like': '赞',
        'comment': '评论',
        'mention': '@我的',
        'follow': '关注',
        'system': '系统',
        'message': '私信'
    }[typeIconClass] || '系统';
    
    // 根据消息类型生成不同的内容文本
    let actionText = notif.content || '';
    if (!actionText) {
        const actionTexts = {
            'like': '赞了你的动态',
            'comment': '评论了你的动态',
            'mention': '在动态中@了你',
            'follow': '关注了你',
            'system': '系统通知'
        };
        actionText = actionTexts[typeIconClass] || '系统通知';
    }
    
    // 关注类型的通知显示回关按钮
    const isFollowType = typeIconClass === 'follow';
    const followBtn = isFollowType ? `
        <button class="notification-btn follow ${notif.is_following ? 'followed' : ''}" 
                data-user-id="${notif.user_id || 0}" 
                data-is-following="${notif.is_following ? '1' : '0'}"
                onclick="handleFollowFromNotification(${notif.user_id || 0}, this, event)">
            ${notif.is_following ? '已关注' : '回关'}
        </button>
    ` : '';
    
    // 私信类型的通知显示回复按钮
    const isMessageType = typeIconClass === 'message';
    const replyBtn = isMessageType ? `
        <button class="notification-btn reply" 
                data-user-id="${notif.user_id || 0}" 
                data-username="${escapeHtml(notif.username || '')}" 
                data-avatar="${escapeHtml(notif.avatar || '')}"
                onclick="handleReplyFromNotification(this, event)">
            回复
        </button>
    ` : '';
    
    // 操作按钮区域
    const actionsHtml = (isFollowType || isMessageType) ? `
        <div class="notification-actions">
            ${followBtn}
            ${replyBtn}
        </div>
    ` : '';
    
    return `
        <div class="notification-item ${notif.is_read ? 'read' : 'unread'}" data-id="${notif.id}" data-type="${notif.type || 'system'}" data-post-id="${notif.post_id || ''}" data-user-id="${notif.user_id || 0}">
            <div class="notification-item-inner" onclick="handleNotificationClick(${notif.id}, '${notif.type || 'system'}', ${notif.post_id || 0}, ${notif.user_id || 0}, event)">
                <a href="${userLink}" class="notification-avatar-wrap" onclick="event.stopPropagation(); markNotificationRead(${notif.id});">
                    ${avatar}
                </a>
                <div class="notification-content">
                    <span class="notification-user-name">${escapeHtml(notif.username || '')}</span>
                    <span class="notification-action-text">${escapeHtml(actionText)}</span>
                    <span class="notification-time">${timeAgo}</span>
                    <span class="notification-type-tag ${typeIconClass}">${typeLabel}</span>
                </div>
                ${actionsHtml}
            </div>
        </div>
    `;
}

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

function initNotificationEvents() {
    const notificationItems = document.querySelectorAll('.notification-item');
    notificationItems.forEach(item => {
        item.addEventListener('click', function(e) {
            if (e.target.closest('.notification-delete') || e.target.closest('.notification-reply-btn') || e.target.closest('.notification-follow-btn')) return;
            
            const notificationId = this.dataset.id;
            const notifType = this.dataset.type;
            const userId = this.dataset.userId;
            
            // 标记为已读
            markNotificationRead(notificationId);
            
            // 私信类型的通知点击打开私信弹窗
            if (notifType === 'message') {
                if (checkLogin()) {
                    openMessageModal(userId, '', '', '');
                } else {
                    openLoginModal();
                }
                return;
            }
            
            const postId = this.dataset.postId;
            if (postId) {
                window.location.href = BASE_URL + '/?r=mobile/detail&id=' + postId;
            }
        });
    });
}

// 标记单个通知为已读
function markNotificationRead(notificationId) {
    const item = document.querySelector('.notification-item[data-id="' + notificationId + '"]');
    if (item && item.classList.contains('unread')) {
        item.classList.remove('unread');
        item.classList.add('read');
        
        fetch(BASE_URL + '/?r=mobileApi/markNotificationRead&id=' + notificationId, {
            method: 'POST'
        }).catch(() => {});
    }
}

// 处理通知点击事件（跳转到帖子详情）
function handleNotificationClick(notificationId, notifType, postId, userId, event) {
    event.stopPropagation();
    
    // 先标记为已读
    markNotificationRead(notificationId);
    
    // 如果是私信类型，打开私信弹窗
    if (notifType === 'message') {
        if (checkLogin()) {
            openMessageModal(userId, '', '', '');
        } else {
            openLoginModal();
        }
        return;
    }
    
    // 跳转到帖子详情页
    if (postId) {
        window.location.href = BASE_URL + '/?r=mobile/detail&id=' + postId;
    }
}

// 回关按钮处理
function handleFollowFromNotification(userId, btn, event) {
    event.stopPropagation();
    event.preventDefault();
    
    if (!checkLoginStatus()) {
        openLoginModal();
        return;
    }
    
    const isFollowing = btn.classList.contains('followed');
    const apiUrl = isFollowing
        ? BASE_URL + '/?r=mobileApi/unfollow'
        : BASE_URL + '/?r=mobileApi/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('操作失败，请重试');
    });
}

// 从通知列表回复私信
function handleReplyFromNotification(btn, event) {
    event.stopPropagation();
    event.preventDefault();
    
    const userId = btn.dataset.userId;
    const username = btn.dataset.username || '';
    const avatar = btn.dataset.avatar || '';
    
    // 检查登录状态
    if (!checkLogin()) {
        openLoginModal();
        return;
    }
    
    // 检查是否给自己发私信
    const currentUserId = document.body.dataset.userId;
    if (currentUserId && currentUserId == userId) {
        showToast('不能给自己发私信');
        return;
    }
    
    // 打开私信弹窗
    openMessageModal(userId, username, avatar, '');
}

// 检查登录状态
function checkLoginStatus() {
    return fetch(BASE_URL + '/?r=mobileApi/userInfo')
        .then(res => res.json())
        .then(data => data.code === 0)
        .catch(() => false);
}

function deleteNotification(id, event) {
    event.stopPropagation();
    event.preventDefault();
    
    showConfirm('确定删除这条通知？', function(confirmed) {
        if (!confirmed) return;
        
        const item = document.querySelector('.notification-item[data-id="' + id + '"]');
        if (item) {
            item.style.transition = 'all 0.3s';
            item.style.transform = 'translateX(100%)';
            item.style.opacity = '0';
            
            setTimeout(() => {
                item.remove();
                
                fetch(BASE_URL + '/?r=mobileApi/deleteNotification&id=' + id, {
                    method: 'POST'
                }).catch(() => {});
                
                const list = document.querySelector('.notification-list');
                if (list && list.querySelectorAll('.notification-item').length === 0) {
                    list.innerHTML = `
                        <div class="empty-notifications">
                            <div class="empty-notifications-icon">
                                <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/></svg>
                            </div>
                            <div class="empty-notifications-text">暂无消息</div>
                            <div class="empty-notifications-subtext">当有新消息时会显示在这里</div>
                        </div>
                    `;
                }
            }, 300);
        }
    });
}

// 标记全部已读
function markAllAsRead() {
    showConfirm('确定将所有消息标记为已读？', function(confirmed) {
        if (!confirmed) return;
        
        const unreadItems = document.querySelectorAll('.notification-item.unread');
        unreadItems.forEach(item => {
            item.classList.remove('unread');
            item.classList.add('read');
        });
        
        fetch(BASE_URL + '/?r=mobileApi/markAllNotificationsRead', {
            method: 'POST'
        }).then(() => {
            showToast('已全部标记为已读');
            document.querySelectorAll('.notification-badge').forEach(badge => {
                badge.style.display = 'none';
            });
            // 更新页脚导航的消息数量
            updateFooterNotificationCount(0);
            // 更新页面顶部未读数量显示
            updateUnreadCountDisplay(0);
        }).catch(() => {
            showToast('操作失败');
        });
    });
}

// 更新页脚导航的消息数量
function updateFooterNotificationCount(count) {
    const badge = document.querySelector('.unread-badge');
    if (badge) {
        if (count > 0) {
            badge.textContent = count > 99 ? '99+' : count;
            badge.style.display = 'block';
        } else {
            badge.style.display = 'none';
        }
    }
}

// 更新页面未读消息数量显示
function updateUnreadCountDisplay(count) {
    const unreadCountEl = document.getElementById('unreadCount');
    if (unreadCountEl) {
        unreadCountEl.textContent = count;
    }
}

// 页面加载时获取消息数量
async function fetchNotificationCount() {
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/userInfo');
        const result = await response.json();
        if (result.code === 0 && result.data && result.data.stats) {
            // 页脚导航显示通知未读数量（不包含私信）
            updateFooterNotificationCount(result.data.stats.notification_unread || 0);
            updateUnreadCountDisplay(result.data.stats.notification_unread || 0);
        }
    } catch (error) {
        console.error('获取消息数量失败:', error);
    }
}