const BASE_URL = window.BASE_URL || window.location.origin;

document.addEventListener('DOMContentLoaded', function() {
    loadBlacklist();
    
    // 搜索功能
    document.getElementById('searchBlacklist').addEventListener('input', searchBlacklist);
    
    // 添加黑名单
    document.getElementById('addBlacklistBtn').addEventListener('click', addToBlacklist);
    
    // 回车键添加
    document.getElementById('addBlacklistUsername').addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            addToBlacklist();
        }
    });
});

async function loadBlacklist() {
    const listContainer = document.getElementById('blacklistList');
    const emptyState = document.getElementById('emptyState');
    
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/getBlacklist', {
            credentials: 'include'
        });
        
        // 检查HTTP状态码
        if (!response.ok) {
            if (response.status === 401) {
                listContainer.innerHTML = '<div class="error-tip">请先登录</div>';
                showToast('请先登录');
                // 尝试打开登录弹窗
                if (typeof openModal === 'function') {
                    openModal('loginModal');
                }
                return;
            }
            throw new Error('HTTP error: ' + response.status);
        }
        
        const result = await response.json();
        
        if (result.code === 0 && result.data && result.data.list) {
            renderBlacklist(result.data.list);
            emptyState.style.display = result.data.list.length === 0 ? 'block' : 'none';
        } else if (result.code === 401) {
            // 未登录
            listContainer.innerHTML = '<div class="error-tip">请先登录</div>';
            if (typeof openModal === 'function') {
                openModal('loginModal');
            }
        } else {
            listContainer.innerHTML = '<div class="error-tip">' + (result.message || '加载失败，请重试') + '</div>';
        }
    } catch (error) {
        console.error('加载黑名单失败:', error);
        // 尝试从本地缓存加载
        const localBlacklist = localStorage.getItem('blacklist');
        if (localBlacklist) {
            const list = JSON.parse(localBlacklist);
            renderBlacklist(list);
            emptyState.style.display = list.length === 0 ? 'block' : 'none';
        } else {
            listContainer.innerHTML = '<div class="error-tip">网络异常，请稍后重试</div>';
        }
    }
}

function renderBlacklist(list) {
    const listContainer = document.getElementById('blacklistList');
    
    if (list.length === 0) {
        listContainer.innerHTML = '';
        return;
    }
    
    const items = list.map(item => `
        <div class="blacklist-item" data-user-id="${item.user_id}">
            <div class="blacklist-avatar">
                <img src="${item.avatar || '/templates/mobile/images/avatar_default.png'}" alt="${item.username}">
            </div>
            <div class="blacklist-info">
                <div class="blacklist-username">${item.username}</div>
                <div class="blacklist-time">添加于 ${item.add_time || '未知时间'}</div>
            </div>
            <button class="blacklist-remove" onclick="removeFromBlacklist(${item.user_id})">
                <span>移除</span>
            </button>
        </div>
    `).join('');
    
    listContainer.innerHTML = items;
}

function searchBlacklist() {
    const keyword = document.getElementById('searchBlacklist').value.toLowerCase();
    const items = document.querySelectorAll('.blacklist-item');
    
    items.forEach(item => {
        const username = item.querySelector('.blacklist-username').textContent.toLowerCase();
        item.style.display = username.includes(keyword) ? 'flex' : 'none';
    });
}

async function addToBlacklist() {
    const username = document.getElementById('addBlacklistUsername').value.trim();
    
    if (!username) {
        showToast('请输入用户名或ID');
        return;
    }
    
    const btn = document.getElementById('addBlacklistBtn');
    btn.disabled = true;
    btn.textContent = '添加中...';
    
    try {
        const formData = new FormData();
        formData.append('username', username);
        
        const response = await fetch(BASE_URL + '/?r=mobileApi/addBlacklist', {
            method: 'POST',
            body: formData,
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (result.code === 0) {
            showToast('添加成功');
            document.getElementById('addBlacklistUsername').value = '';
            loadBlacklist();
        } else {
            showToast(result.message || '添加失败');
        }
    } catch (error) {
        console.error('添加黑名单失败:', error);
        showToast('添加失败，请重试');
    }
    
    btn.disabled = false;
    btn.textContent = '添加';
}

async function removeFromBlacklist(userId) {
    if (!confirm('确定要从黑名单中移除该用户吗？')) {
        return;
    }
    
    try {
        const formData = new FormData();
        formData.append('user_id', userId);
        
        const response = await fetch(BASE_URL + '/?r=mobileApi/removeBlacklist', {
            method: 'POST',
            body: formData,
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (result.code === 0) {
            showToast('移除成功');
            loadBlacklist();
        } else {
            showToast(result.message || '移除失败');
        }
    } catch (error) {
        console.error('移除黑名单失败:', error);
        showToast('移除失败，请重试');
    }
}

function showToast(message) {
    // 简单的Toast提示
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 2000);
}