// 检查是否已存在BASE_URL，避免重复声明
const BASE_URL = typeof window.BASE_URL !== 'undefined' ? window.BASE_URL : 
                 (window.HuSNS_Fans?.baseUrl || window.location.origin);
const CURRENT_USER_ID = window.HuSNS_Fans?.userId || null;
let currentTab = 'following';
let followingPage = 1;
let followersPage = 1;
let isLoading = false;
let hasMoreFollowing = true;
let hasMoreFollowers = true;

document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const tabParam = urlParams.get('tab');
    if (tabParam === 'followers') {
        switchTab('followers');
    } else {
        loadFollowing();
    }
    
    document.getElementById('followingLoadMoreBtn')?.addEventListener('click', loadMoreFollowing);
    document.getElementById('followersLoadMoreBtn')?.addEventListener('click', loadMoreFollowers);
    
    // 更新标签指示器位置
    updateTabIndicator();
});

function updateTabIndicator() {
    const activeTab = document.querySelector('.follow-tab-item.active');
    const indicator = document.querySelector('.tab-indicator');
    if (activeTab && indicator) {
        const tabBar = document.querySelector('.follow-tab-bar');
        const tabRect = activeTab.getBoundingClientRect();
        const barRect = tabBar.getBoundingClientRect();
        const offset = tabRect.left - barRect.left + (tabRect.width / 2) - 16;
        indicator.style.width = (tabRect.width) + 'px';
        indicator.style.transform = `translateX(${offset}px)`;
    }
}

function switchTab(tab) {
    currentTab = tab;
    
    document.querySelectorAll('.follow-tab-item').forEach(item => {
        item.classList.toggle('active', item.dataset.tab === tab);
    });
    
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
    });
    document.getElementById('tab-' + tab)?.classList.add('active');
    
    // 更新指示器位置
    setTimeout(updateTabIndicator, 10);
    
    if (tab === 'following' && document.getElementById('followingList')?.querySelector('.empty-icon')) {
        // 检查是否只有默认的空状态（非loading状态）
        const emptyIcon = document.getElementById('followingList')?.querySelector('.empty-icon svg');
        if (emptyIcon) {
            loadFollowing();
        }
    } else if (tab === 'followers' && document.getElementById('followersList')?.querySelector('.empty-icon')) {
        const emptyIcon = document.getElementById('followersList')?.querySelector('.empty-icon svg');
        if (emptyIcon) {
            loadFollowers();
        }
    }
}

function renderUserItem(user, index = 0) {
    const isFollowing = user.is_following === 1;
    return `
        <div class="user-item" data-user-id="${user.id}" style="animation-delay: ${index * 0.05}s">
            <a href="${BASE_URL}/?r=mobile/user&id=${user.id}">
                ${user.avatar 
                    ? `<img src="${user.avatar}" alt="" class="user-item-avatar" onerror="this.outerHTML='<div class=\\'user-item-avatar default\\'>${(user.username || "用").charAt(0).toUpperCase()}</div>'">`
                    : `<div class="user-item-avatar default">${(user.username || "用").charAt(0).toUpperCase()}</div>`
                }
            </a>
            <div class="user-item-info">
                <a href="${BASE_URL}/?r=mobile/user&id=${user.id}" class="user-item-name">
                    ${escapeHtml(user.username || '用户')}
                    ${user.is_vip == 1 ? '<span class="user-item-badge vip">VIP</span>' : ''}
                </a>
                <div class="user-item-bio">${escapeHtml(user.bio || '这个人很懒，什么都没写')}</div>
            </div>
            ${user.id != CURRENT_USER_ID ? `
                <button class="follow-btn ${isFollowing ? 'following' : 'not-following'}" onclick="toggleFollow(${user.id}, this)">
                    ${isFollowing ? '<span>已关注</span>' : '关注'}
                </button>
            ` : ''}
        </div>
    `;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 更新关注数量显示
function updateFollowingCount(count) {
    const countEl = document.getElementById('followingCount');
    if (countEl) {
        countEl.textContent = count;
    }
}

// 更新粉丝数量显示
function updateFollowersCount(count) {
    const countEl = document.getElementById('followersCount');
    if (countEl) {
        countEl.textContent = count;
    }
}

function renderEmptyState(type) {
    if (type === 'following') {
        return `
            <div class="empty-state">
                <div class="empty-icon">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                        <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                    </svg>
                </div>
                <div class="empty-text">暂无关注</div>
                <div class="empty-subtext">关注更多感兴趣的用户</div>
                <a href="${BASE_URL}/?r=mobile/discover" class="empty-action">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"></circle>
                        <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                    </svg>
                    发现好友
                </a>
            </div>
        `;
    } else {
        return `
            <div class="empty-state">
                <div class="empty-icon">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                        <circle cx="9" cy="7" r="4"></circle>
                        <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                        <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                    </svg>
                </div>
                <div class="empty-text">暂无粉丝</div>
                <div class="empty-subtext">发布优质内容吸引粉丝</div>
                <a href="${BASE_URL}/?r=mobile/feed" class="empty-action">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M12 19l7-7 3 3-7 7-3-3z"></path>
                        <path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"></path>
                        <path d="M2 2l7.586 7.586"></path>
                        <circle cx="11" cy="11" r="2"></circle>
                    </svg>
                    发布动态
                </a>
            </div>
        `;
    }
}

async function loadFollowing() {
    if (isLoading) return;
    isLoading = true;
    followingPage = 1;
    
    const list = document.getElementById('followingList');
    // 显示loading状态
    list.innerHTML = `
        <div class="empty-state">
            <div class="empty-icon" style="animation: none;">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="animation: spin 1s linear infinite;">
                    <circle cx="12" cy="12" r="10" stroke-dasharray="60" stroke-dashoffset="20"></circle>
                </svg>
            </div>
            <div class="empty-text">加载中...</div>
        </div>
    `;
    
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/following&page=' + followingPage);
        const result = await response.json();
        
        if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
            list.innerHTML = result.data.items.map((user, i) => renderUserItem(user, i)).join('');
            hasMoreFollowing = result.data.items.length >= 10;
            document.getElementById('followingLoadMore').style.display = hasMoreFollowing ? 'block' : 'none';
            // 更新关注数量
            updateFollowingCount(result.data.total || result.data.items.length);
        } else {
            list.innerHTML = renderEmptyState('following');
            document.getElementById('followingLoadMore').style.display = 'none';
            updateFollowingCount(0);
        }
    } catch (error) {
        console.error('加载失败:', error);
        list.innerHTML = `
            <div class="empty-state">
                <div class="empty-icon">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                        <circle cx="12" cy="12" r="10"></circle>
                        <line x1="12" y1="8" x2="12" y2="12"></line>
                        <line x1="12" y1="16" x2="12.01" y2="16"></line>
                    </svg>
                </div>
                <div class="empty-text">加载失败</div>
                <div class="empty-subtext">请检查网络后重试</div>
            </div>
        `;
    }
    
    isLoading = false;
}

async function loadMoreFollowing() {
    if (isLoading || !hasMoreFollowing) return;
    isLoading = true;
    
    const btn = document.getElementById('followingLoadMoreBtn');
    btn.textContent = '加载中...';
    btn.style.opacity = '0.7';
    followingPage++;
    
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/following&page=' + followingPage);
        const result = await response.json();
        
        if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
            const list = document.getElementById('followingList');
            const startIndex = list.querySelectorAll('.user-item').length;
            list.innerHTML += result.data.items.map((user, i) => renderUserItem(user, startIndex + i)).join('');
            hasMoreFollowing = result.data.items.length >= 10;
        } else {
            hasMoreFollowing = false;
        }
        
        btn.textContent = hasMoreFollowing ? '加载更多' : '没有更多了';
    } catch (error) {
        console.error('加载失败:', error);
        btn.textContent = '加载失败';
        followingPage--;
    }
    
    btn.style.opacity = '1';
    isLoading = false;
}

async function loadFollowers() {
    if (isLoading) return;
    isLoading = true;
    followersPage = 1;
    
    const list = document.getElementById('followersList');
    // 显示loading状态
    list.innerHTML = `
        <div class="empty-state">
            <div class="empty-icon" style="animation: none;">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="animation: spin 1s linear infinite;">
                    <circle cx="12" cy="12" r="10" stroke-dasharray="60" stroke-dashoffset="20"></circle>
                </svg>
            </div>
            <div class="empty-text">加载中...</div>
        </div>
    `;
    
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/followers&page=' + followersPage);
        const result = await response.json();
        
        if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
            list.innerHTML = result.data.items.map((user, i) => renderUserItem(user, i)).join('');
            hasMoreFollowers = result.data.items.length >= 10;
            document.getElementById('followersLoadMore').style.display = hasMoreFollowers ? 'block' : 'none';
            // 更新粉丝数量
            updateFollowersCount(result.data.total || result.data.items.length);
        } else {
            list.innerHTML = renderEmptyState('followers');
            document.getElementById('followersLoadMore').style.display = 'none';
            updateFollowersCount(0);
        }
    } catch (error) {
        console.error('加载失败:', error);
        list.innerHTML = `
            <div class="empty-state">
                <div class="empty-icon">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                        <circle cx="12" cy="12" r="10"></circle>
                        <line x1="12" y1="8" x2="12" y2="12"></line>
                        <line x1="12" y1="16" x2="12.01" y2="16"></line>
                    </svg>
                </div>
                <div class="empty-text">加载失败</div>
                <div class="empty-subtext">请检查网络后重试</div>
            </div>
        `;
    }
    
    isLoading = false;
}

async function loadMoreFollowers() {
    if (isLoading || !hasMoreFollowers) return;
    isLoading = true;
    
    const btn = document.getElementById('followersLoadMoreBtn');
    btn.textContent = '加载中...';
    btn.style.opacity = '0.7';
    followersPage++;
    
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/followers&page=' + followersPage);
        const result = await response.json();
        
        if (result.code === 0 && result.data && result.data.items && result.data.items.length > 0) {
            const list = document.getElementById('followersList');
            const startIndex = list.querySelectorAll('.user-item').length;
            list.innerHTML += result.data.items.map((user, i) => renderUserItem(user, startIndex + i)).join('');
            hasMoreFollowers = result.data.items.length >= 10;
        } else {
            hasMoreFollowers = false;
        }
        
        btn.textContent = hasMoreFollowers ? '加载更多' : '没有更多了';
    } catch (error) {
        console.error('加载失败:', error);
        btn.textContent = '加载失败';
        followersPage--;
    }
    
    btn.style.opacity = '1';
    isLoading = false;
}

async function toggleFollow(userId, btn) {
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/follow', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ user_id: userId }),
            credentials: 'include'
        });
        const result = await response.json();
        
        if (result.code === 0) {
            const isFollowing = result.data.is_following === 1;
            
            // 添加强制重绘以重置动画
            btn.style.animation = 'none';
            btn.offsetHeight; // 触发重绘
            btn.style.animation = '';
            
            btn.className = 'follow-btn ' + (isFollowing ? 'following' : 'not-following');
            btn.innerHTML = isFollowing ? '<span>已关注</span>' : '关注';
            
            // 显示成功提示
            showToast(isFollowing ? '关注成功' : '已取消关注');
        } else {
            showToast(result.message || '操作失败');
        }
    } catch (error) {
        console.error('操作失败:', error);
        showToast('操作失败，请稍后重试');
    }
}

// Toast提示
function showToast(message) {
    // 移除已有的toast
    const existingToast = document.querySelector('.fans-toast');
    if (existingToast) {
        existingToast.remove();
    }
    
    const toast = document.createElement('div');
    toast.className = 'fans-toast';
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 12px 24px;
        border-radius: 24px;
        font-size: 14px;
        z-index: 10000;
        animation: toastFadeIn 0.3s ease;
    `;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.style.animation = 'toastFadeOut 0.3s ease forwards';
        setTimeout(() => toast.remove(), 300);
    }, 1500);
}

// 添加toast动画样式
const toastStyle = document.createElement('style');
toastStyle.textContent = `
    @keyframes toastFadeIn {
        from { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
        to { opacity: 1; transform: translate(-50%, -50%) scale(1); }
    }
    @keyframes toastFadeOut {
        from { opacity: 1; transform: translate(-50%, -50%) scale(1); }
        to { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
    }
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
`;
document.head.appendChild(toastStyle);
