{% load djacore_tags default_tags static %}
<nav class="navbar navbar-expand-lg bg-body-tertiary shadow-sm">
    <div class="container-fluid">
      <a class="fw-bold navbar-brand" href="{% url 'home' %}">{% if logo %}<img src="{{ uploadpath }}{{ logo }}" alt="{{ site_name }}" style="width: 10rem;max-height: 3rem;">{% else %}{{ site_name }}{% endif %}</a>
      
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0 ms-auto me-auto">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{% get_home_url %}">首页</a>
          </li>
          {% tree_categorylist %}
          
        </ul>

        <div id="searchbox" class="position-relative ms-auto">
            <form action="/search/" class="d-flex" role="search">
              <input class="form-control me-2" id="searchinput" onkeyup="search(this.value)" type="search" name="key" placeholder="请输入关键词" aria-label="Search">
              <button class="btn btn-outline-success flex-shrink-0" type="submit">搜索</button>  
            </form>
            <div id="result-box" class="text-start"><ul id="result" class="list-group"></ul></div>
          </div>
          {% if allow_registration %}
          <ul class="navbar-nav ms-auto me-auto" id="user-navbar-container">
              <!-- 初始状态：显示登录/注册链接 -->
              <a href="{% url 'users:register' %}">注册</a> / <a href="{% url 'users:login' %}?next={{ request.path }}">登录</a>
          </ul>
          {% endif %}

<script>
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    checkAuthStatus();
});
// 爬虫检测函数 - 结合多种特征进行智能识别
function isLikelyCrawler() {
    const userAgent = navigator.userAgent.toLowerCase();
    
    // 1. 用户代理检测 - 常见爬虫关键词
    const botPatterns = [
        'bot', 'crawler', 'spider', 'scanner', 'slurp', 
        'googlebot', 'bingbot', 'baiduspider', 'yandexbot',
        'facebookexternalhit', 'twitterbot', 'linkedinbot',
        'headless', 'phantomjs', 'selenium', 'puppeteer'
    ];
    
    const isBotByUA = botPatterns.some(pattern => 
        userAgent.includes(pattern)
    );
    
    // 2. 浏览器特性检测 - 真实浏览器应具备这些特性
    const isRealBrowser = (
        'Promise' in window &&
        'Map' in window &&
        'localStorage' in window &&
        'sessionStorage' in window &&
        'addEventListener' in window &&
        navigator.cookieEnabled &&
        navigator.plugins.length > 0
    );
    
    // 3. 行为特征检测 - 检查JS执行能力
    let jsExecutionTest = false;
    try {
        const testKey = '_crawler_test_' + Date.now();
        localStorage.setItem(testKey, 'test');
        jsExecutionTest = localStorage.getItem(testKey) === 'test';
        localStorage.removeItem(testKey);
    } catch (e) {
        jsExecutionTest = false;
    }
    
    // 综合判断：如果是爬虫UA，或者不具备真实浏览器特性，或者JS执行测试失败
    return isBotByUA || !isRealBrowser || !jsExecutionTest;
}

/**
 * 检查并更新用户认证状态
 * 策略：优先使用localStorage，其次请求API验证
 */
async function checkAuthStatus() {
    const container = document.getElementById('user-navbar-container');
    if (!container) return;
    // 爬虫检测
    if (isLikelyCrawler()) {
        console.log('Crawler detected, showing guest navbar without API calls');
        return; // 直接返回，不执行后续API请求
    }

    // 1. 首先检查本地存储中是否有用户信息
    const localUserData = getLocalUserData();
    
    if (localUserData && localUserData.isAuthenticated) {
        // 本地存在登录信息，立即更新UI，提供最佳用户体验
        updateNavbarToLoggedIn(localUserData.user);
    }

    // 2. 无论本地有无数据，都向API发起请求以验证状态的准确性（例如登录已过期）
    try {
        const response = await fetch('{% url 'users:api_auth_status' %}', {
            credentials: 'include' // 重要：携带session cookie
        });
        
        if (response.ok) {
            const apiData = await response.json();
            // 根据API返回的真实状态更新UI和本地存储
            handleApiAuthResponse(apiData);
        } else {
            // 如果API请求失败，但本地有数据，保持本地状态；否则显示未登录
            if (!localUserData) {
                showGuestNavbar();
            }
            // 可选：可以记录错误日志
            console.error('Auth status API request failed.');
        }
    } catch (error) {
        console.error('Error checking auth status:', error);
        // 网络错误等，处理方式同上
        if (!localUserData) {
            showGuestNavbar();
        }
    }
}

/**
 * 从localStorage获取用户数据
 */
function getLocalUserData() {
    try {
        const data = localStorage.getItem('userAuthData');
        return data ? JSON.parse(data) : null;
    } catch (e) {
        console.error("Error reading from localStorage:", e);
        return null;
    }
}

/**
 * 将用户数据保存到localStorage
 */
function setLocalUserData(authData) {
    try {
        localStorage.setItem('userAuthData', JSON.stringify(authData));
    } catch (e) {
        console.error("Error saving to localStorage:", e);
    }
}

/**
 * 处理API返回的认证数据
 */
function handleApiAuthResponse(apiData) {
    if (apiData.isAuthenticated && apiData.user) {
        // API确认已登录，保存数据并更新UI
        setLocalUserData(apiData);
        updateNavbarToLoggedIn(apiData.user);
    } else {
        // API确认未登录，清除本地数据并更新UI
        clearLocalUserData();
        showGuestNavbar();
    }
}

/**
 * 将导航栏更新为已登录状态
 */
function updateNavbarToLoggedIn(userData) {
    const container = document.getElementById('user-navbar-container');
    const displayName = userData.displayName || userData.username;
    
    container.innerHTML = `
        <li class="dropdown nav-item">
            <a class="dropdown-toggle nav-link" href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
                ${displayName}
            </a>
            <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
                <li><a class="dropdown-item" href="{% url 'users:user_index' %}">用户信息</a></li>
                <li><a class="dropdown-item" href="{% url 'users:change_password' %}">修改密码</a></li>
                <li class="border-top"><a class="dropdown-item" href="#" onclick="handleLogout(); return false;">退出</a></li>
            </ul>
        </li>
    `;
}

/**
 * 将导航栏更新为游客（未登录）状态
 */
function showGuestNavbar() {
    const container = document.getElementById('user-navbar-container');
    // 注意：next参数需要动态获取当前路径，因为页面可能是静态的
    const currentPath = encodeURIComponent(window.location.pathname);
    container.innerHTML = `<a href="/users/register/">注册</a> / <a href="/users/login/?next=${currentPath}">登录</a>`;
}

/**
 * 清除本地存储的用户数据
 */
function clearLocalUserData() {
    try {
        localStorage.removeItem('userAuthData');
    } catch (e) {
        console.error("Error clearing localStorage:", e);
    }
}

/**
 * 处理用户退出
 */
async function handleLogout() {
    if (!confirm('确定要退出登录吗？')) return;

    try {
        const response = await fetch('{% url 'users:api_logout' %}', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCSRFToken(), // 需要从cookie中获取CSRF token
            },
            credentials: 'include'
        });

        if (response.ok) {
            // 退出成功，清除本地状态并更新UI
            clearLocalUserData();
            showGuestNavbar();
            // 可以重定向到首页或显示消息
            // window.location.href = '/';
        } else {
            alert('退出失败，请重试。');
        }
    } catch (error) {
        console.error('Logout error:', error);
        alert('退出过程中发生错误。');
    }
}

/**
 * 辅助函数：获取CSRF Token（Django需要）
 */
function getCSRFToken() {
    const name = 'csrftoken';
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// --- 在登录成功后的回调中调用此函数 ---
// 这个函数需要在用户登录成功后（例如，在登录页面的表单提交成功后的回调里）被调用。
function onLoginSuccess(userDataFromServer) {
    // 构建与api_auth_status返回格式一致的数据对象
    const authData = {
        isAuthenticated: true,
        user: userDataFromServer // 这个对象应至少包含 username 和 displayName
    };
    // 保存到本地并立即更新UI
    setLocalUserData(authData);
    updateNavbarToLoggedIn(userDataFromServer);
}
</script>
          
      </div>
    </div>
  </nav>