<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>元库 - 底层能力 AI 工具库</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- FontAwesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Google Fonts: Inter -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* Custom styles for animations and overrides */
        * {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', sans-serif;
        }

        /* Fade-in animation for page load */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .fade-in {
            animation: fadeIn 0.5s ease-out;
        }

        /* Hide scrollbar but keep functionality */
        .scrollbar-hide {
            -ms-overflow-style: none;
            scrollbar-width: none;
        }
        .scrollbar-hide::-webkit-scrollbar {
            display: none;
        }

        /* Custom colors as per design system */
        .bg-primary { background-color: #4A90E2; }
        .text-primary { color: #4A90E2; }
        .border-primary { border-color: #4A90E2; }
        .bg-light { background-color: #F3F4F6; }
        .text-dark { color: #111827; }
        .text-muted { color: #4B5563; }
        .text-light-muted { color: #9CA3AF; }

        /* Scale effect on hover */
        .scale-hover:hover {
            transform: scale(1.05);
            transition: transform 0.2s ease;
        }

        /* Focus style for search */
        .search-focus:focus {
            border-color: #4A90E2;
            outline: none;
        }

        /* Modal styles */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.6);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }

        .modal-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .modal-container {
            background-color: #FFFFFF;
            border-radius: 0.75rem; /* rounded-xl */
            padding: 1.5rem; /* p-6 */
            width: 100%;
            max-width: 400px; /* w-[400px] */
            box-shadow: 0 0 0 1px rgba(74, 144, 226, 0.1), 0 10px 25px rgba(74, 144, 226, 0.2);
            transform: translateY(-10px);
            transition: transform 0.3s ease;
        }

        .modal-overlay.active .modal-container {
            transform: translateY(0);
        }

        /* Tab styles */
        .modal-tabs {
            display: flex;
            border-bottom: 1px solid #E5E7EB;
            margin-bottom: 1.5rem;
        }

        .modal-tab {
            flex: 1;
            text-align: center;
            padding: 0.75rem;
            font-weight: 600;
            color: #4B5563;
            background: none;
            border: none;
            cursor: pointer;
            position: relative;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', sans-serif;
            font-size: 1rem;
        }

        .modal-tab.active {
            color: #4A90E2;
        }

        .modal-tab.active::after {
            content: '';
            position: absolute;
            bottom: -1px;
            left: 0;
            right: 0;
            height: 2px;
            background-color: #4A90E2;
        }

        /* Form styles */
        .modal-form {
            display: none;
        }

        .modal-form.active {
            display: block;
        }

        .modal-input {
            width: 100%;
            padding: 0.5rem;
            background-color: #F3F4F6;
            border-radius: 0.375rem; /* rounded-md */
            border: 1px solid #E5E7EB;
            margin-bottom: 1rem;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', sans-serif;
            font-size: 0.875rem;
            transition: border-color 0.2s ease;
        }

        .modal-input:focus {
            border-color: #4A90E2;
            outline: none;
        }

        .modal-input::placeholder {
            color: #9CA3AF;
        }

        /* Button styles */
        .modal-primary-btn {
            width: 100%;
            background-color: #4A90E2;
            color: white;
            padding: 0.5rem;
            border-radius: 0.375rem;
            border: none;
            font-weight: 600;
            font-size: 0.875rem;
            cursor: pointer;
            transition: transform 0.2s ease, background-color 0.2s ease;
            margin-bottom: 0.75rem;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', sans-serif;
        }

        .modal-primary-btn:hover {
            transform: scale(1.05);
            background-color: #3b82f6;
        }

        .modal-secondary-link {
            display: block;
            text-align: center;
            color: #6B7280;
            font-size: 0.75rem;
            text-decoration: none;
            margin-bottom: 1.5rem;
            cursor: pointer;
            transition: color 0.2s ease;
        }

        .modal-secondary-link:hover {
            color: #4A90E2;
        }

        /* Close button */
        .modal-close-btn {
            width: 100%;
            background-color: white;
            color: #4B5563;
            padding: 0.5rem;
            border-radius: 0.375rem;
            border: 1px solid #E5E7EB;
            font-size: 0.875rem;
            cursor: pointer;
            transition: background-color 0.2s ease;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', sans-serif;
        }

        .modal-close-btn:hover {
            background-color: #F9FAFB;
        }

        /* Form message styles */
        .form-message {
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Responsive adjustments */
        @media (max-width: 640px) {
            .modal-container {
                margin: 1rem;
                max-width: calc(100% - 2rem);
                padding: 1rem;
            }

            .modal-tab {
                padding: 0.5rem;
                font-size: 0.875rem;
            }
        }
    </style>
</head>
<body class="bg-white text-dark fade-in">
    <!-- Header / Navigation -->
    <header class="sticky top-0 z-10 bg-white border-b border-gray-200">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <!-- Logo -->
            <div class="flex items-center space-x-2">
                <!-- Database icon SVG -->
                <div id="siteLogoContainer">
                    <svg class="w-8 h-8 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"></path>
                    </svg>
                </div>
                <span class="text-xl font-bold" id="siteTitleLogo">元库</span>
            </div>

            <!-- Search Box (hidden on small screens, shown from md up) -->
            <div class="hidden md:flex flex-1 max-w-lg mx-6">
                <div class="relative w-full">
                    <input type="text"
                           id="searchInput"
                           placeholder="搜索 AI 工具..."
                           class="w-full pl-10 pr-4 py-2 rounded-md bg-light text-muted border border-gray-300 search-focus">
                    <i class="fas fa-search absolute left-3 top-3 text-primary"></i>
                </div>
            </div>

            <!-- Login/Register Button -->
            <button id="authModalBtn" class="bg-primary text-white px-4 py-2 rounded-md font-medium hover:opacity-90 transition-opacity">
                登录/注册
            </button>

            <!-- Mobile search icon (visible only on small screens) -->
            <button id="mobileSearchBtn" class="md:hidden text-primary">
                <i class="fas fa-search text-xl"></i>
            </button>
        </div>

        <!-- Mobile search bar (hidden by default) -->
        <div id="mobileSearchBar" class="hidden md:hidden container mx-auto px-4 py-3 border-t border-gray-200">
            <div class="relative">
                <input type="text"
                       placeholder="搜索 AI 工具..."
                       class="w-full pl-10 pr-4 py-2 rounded-md bg-light text-muted border border-gray-300 search-focus">
                <i class="fas fa-search absolute left-3 top-3 text-primary"></i>
            </div>
        </div>
    </header>

    <!-- Hero Section -->
    <section class="container mx-auto px-4 py-12 md:py-16">
        <div class="border border-primary rounded-xl max-w-3xl mx-auto p-8 md:p-12">
            <h1 class="text-4xl md:text-6xl font-bold text-center mb-4" id="siteTitleHero">元库</h1>
            <p class="text-lg md:text-xl text-muted text-center" id="siteContent">汇聚全球顶尖AI,让效率提升一个维度</p>
            <p class="text-muted text-center mt-6" >多元 AI 工具库</p>
        </div>
    </section>

    <!-- Filter Tabs Section -->
    <section class="container mx-auto px-4 py-6">
        <!-- Industry Filter -->
        <div class="mb-8">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-lg font-semibold">按行业划分</h2>
            </div>
            <div class="scrollbar-hide overflow-x-auto whitespace-nowrap pb-2">
                <div class="inline-flex space-x-2" id="industryTabsContainer">
                    <!-- Industry tabs will be populated by JS -->
                </div>
            </div>
        </div>

        <!-- Role Filter -->
        <div>
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-lg font-semibold">按职位划分</h2>
            </div>
            <div class="scrollbar-hide overflow-x-auto whitespace-nowrap pb-2">
                <div class="inline-flex space-x-2" id="roleTabsContainer">
                    <!-- Role tabs will be dynamically populated by JS -->
                </div>
            </div>
        </div>
    </section>

    <!-- Tool Grid Section -->
    <section class="container mx-auto px-4 py-8">
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4" id="toolGrid">
        </div>
    </section>

    <!-- Footer -->
    <footer class="border-t border-gray-200 mt-12 py-6">
        <div class="container mx-auto px-4 text-center space-y-1">
            <p class="text-light-muted text-sm">
                <a href="https://beian.miit.gov.cn/" target="_blank" class="hover:text-primary transition-colors">粤ICP备2026033966号-1</a>
            </p>
            <p class="text-light-muted text-sm">
                <a href="https://www.beian.gov.cn/" target="_blank" class="hover:text-primary transition-colors">粤公网安备44011302005379号</a>
            </p>
        </div>
    </footer>

    <!-- Auth Modal -->
    <div class="modal-overlay" id="authModalOverlay">
        <div class="modal-container relative">
            <!-- 关闭按钮 -->
            <button id="modalCloseBtn" class="absolute top-4 right-4 text-gray-400 hover:text-primary transition-colors text-xl">
                <i class="fas fa-times"></i>
            </button>
            <!-- Tab Switch -->
            <div class="modal-tabs">
                <button class="modal-tab active" data-tab="login">登录</button>
                <button class="modal-tab" data-tab="register">注册</button>
            </div>

            <!-- Login Form -->
            <form class="modal-form active" id="loginForm">
                <input type="email" class="modal-input" placeholder="邮箱" required>
                <input type="password" class="modal-input" placeholder="密码" required>
                <button type="submit" class="modal-primary-btn">登录</button>
                <a class="modal-secondary-link" id="switchToRegister">没有账号？去注册</a>
            </form>

            <!-- Register Form -->
            <form class="modal-form" id="registerForm">
                <input type="email" class="modal-input" placeholder="邮箱" required>
                <input type="password" class="modal-input" placeholder="密码（至少 6 位）" minlength="6" required>
                <input type="password" class="modal-input" placeholder="确认密码" required>
                <button type="submit" class="modal-primary-btn">注册</button>
                <a class="modal-secondary-link" id="switchToLogin">已有账号？去登录</a>
            </form>

            <!-- Third-party Login -->
            <div class="mt-6">
                <div class="relative">
                    <div class="absolute inset-0 flex items-center">
                        <div class="w-full border-t border-gray-300"></div>
                    </div>
                    <div class="relative flex justify-center text-sm">
                        <span class="px-2 bg-white text-gray-500">其他登录方式</span>
                    </div>
                </div>
                <div class="mt-6 flex justify-center gap-3">
                    <button type="button" id="qqLoginBtn" class="inline-flex justify-center items-center py-2 px-4 border border-gray-300 rounded-md shadow-sm bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors">
                        <i class="fab fa-qq text-blue-500 text-xl"></i>
                        <span class="ml-2">QQ</span>
                    </button>
                    <!-- <button type="button" id="wechatLoginBtn" class="inline-flex justify-center items-center py-2 px-4 border border-gray-300 rounded-md shadow-sm bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors">
                        <i class="fab fa-weixin text-green-500 text-xl"></i>
                        <span class="ml-2">微信</span>
                    </button>
                    <button type="button" id="douyinLoginBtn" class="inline-flex justify-center items-center py-2 px-4 border border-gray-300 rounded-md shadow-sm bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors">
                        <i class="fab fa-tiktok text-black text-xl"></i>
                        <span class="ml-2">抖音</span>
                    </button> -->
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // Tool data - loaded from API, with static fallback tools
        let tools = [
        ];

        // DOM elements
        const toolGrid = document.getElementById('toolGrid');
        const roleTabsContainer = document.getElementById('roleTabsContainer');
        const searchInput = document.getElementById('searchInput');
        const mobileSearchBtn = document.getElementById('mobileSearchBtn');
        const mobileSearchBar = document.getElementById('mobileSearchBar');

        // State
        let activeIndustry = 'all';
        let activeRole = 'all';
        let searchQuery = '';
        // 行业数据
        let industries = [];
        let selectedIndustryId = null;
        // 工具热度缓存
        let toolRankMap = new Map();

        // Generate role tabs based on selected industry
        function generateRoleTabs(industryId) {
            // Clear existing role tabs
            roleTabsContainer.innerHTML = '';

            // Always add "全部展示" button
            const allButton = document.createElement('button');
            allButton.className = 'role-tab active bg-primary text-white px-4 py-2 rounded-md font-medium';
            allButton.setAttribute('data-role', 'all');
            allButton.textContent = '全部展示';
            allButton.addEventListener('click', () => {
                activateRoleTab('all');
            });
            roleTabsContainer.appendChild(allButton);

            // If "全部" industry is selected, only show "全部展示" role tab
            if (industryId === 'all') {
                return;
            }

            // Get selected industry
            const industry = industries.find(i => i.id === industryId);
            if (!industry) return;

            // Create role buttons for each role in the industry
            industry.roles.forEach(role => {
                const roleButton = document.createElement('button');
                roleButton.className = 'role-tab bg-light text-muted px-4 py-2 rounded-md font-medium hover:bg-gray-300';
                roleButton.setAttribute('data-role', role.name);
                roleButton.textContent = role.name + "工具";
                roleButton.addEventListener('click', () => {
                    activateRoleTab(role.name);
                });
                roleTabsContainer.appendChild(roleButton);
            });
        }

        // 获取API基础URL
        function getToolApiBaseUrl() {
            // 如果当前页面通过文件协议打开，使用 localhost:20000
            if (window.location.protocol === 'file:') {
                return 'http://localhost:20000/api';
            }
            // 如果通过 HTTP 打开，使用相对路径
            return '/api';
        }

        // 加载工具热度数据
        async function loadToolRank() {
            try {
                const API_BASE_URL = getToolApiBaseUrl();
                const response = await fetch(`${API_BASE_URL}/tools/rank?limit=50`);
                if (response.ok) {
                    const data = await response.json();
                    if (data.success && data.data) {
                        toolRankMap = new Map(data.data.map(item => [item.tool_name, item.use_count]));
                    }
                }
            } catch (error) {
                console.warn('加载工具热度数据失败:', error);
                // 加载失败时使用空Map，不影响正常功能
                toolRankMap = new Map();
            }
        }

        // 加载行业列表
        async function loadIndustries() {
            try {
                const API_BASE_URL = getToolApiBaseUrl();
                const response = await fetch(`${API_BASE_URL}/public/industries/list`);
                if (response.ok) {
                    const result = await response.json();
                    if (result.success && result.data) {
                        industries = result.data;
                        renderIndustryTabs();
                        // 默认选中"全部展示"
                        activateIndustryTab('all');
                    }
                }
            } catch (error) {
                console.warn('加载行业列表失败:', error);
                // 加载失败时使用默认数据
                industries = [
                    {
                        id: 1,
                        name: '游戏',
                        roles: [
                            { id: 1, name: '程序' },
                            { id: 2, name: '美术' },
                            { id: 3, name: '策划' }
                        ]
                    }
                ];
                renderIndustryTabs();
                activateIndustryTab('all');
            }
        }

        // 渲染行业标签
        function renderIndustryTabs() {
            const container = document.getElementById('industryTabsContainer');
            container.innerHTML = '';

            // Add "全部展示" button first
            const allButton = document.createElement('button');
            allButton.className = 'industry-tab bg-light text-muted px-4 py-2 rounded-md font-medium hover:bg-gray-300';
            allButton.setAttribute('data-industry-id', 'all');
            allButton.textContent = '全部展示';
            allButton.addEventListener('click', () => {
                activateIndustryTab('all');
            });
            container.appendChild(allButton);

            industries.forEach(industry => {
                const button = document.createElement('button');
                button.className = 'industry-tab bg-light text-muted px-4 py-2 rounded-md font-medium hover:bg-gray-300';
                button.setAttribute('data-industry-id', industry.id);
                button.textContent = industry.name;
                button.addEventListener('click', () => {
                    activateIndustryTab(industry.id);
                });
                container.appendChild(button);
            });
        }

        // 加载工具列表
        async function loadTools() {
            try {
                const API_BASE_URL = getToolApiBaseUrl();
                const response = await fetch(`${API_BASE_URL}/tools/list`);
                if (response.ok) {
                    const result = await response.json();
                    if (result.success && result.data) {
                        // 转换数据结构，适配现有逻辑
                        tools = result.data.map(tool => {
                            // 解析category字段，格式为 "行业-职位"，例如 "游戏-程序"
                            const [industryName, roleName] = tool.category.split('-');
                            let industry = 'game';
                            let role = 'programming';

                            // 映射行业
                            if (industryName === '游戏') industry = 'game';
                            else industry = 'other';

                            // 映射职位
                            if (roleName === '程序') role = 'programming';
                            else if (roleName === '美术') role = 'art';
                            else if (roleName === '策划') role = 'planning';

                            return {
                                id: tool.id,
                                title: tool.name,
                                description: tool.description,
                                url: tool.url,
                                isExternal: tool.is_external || tool.isExternal || false,
                                industry,
                                role,
                                industryName,
                                roleName
                            };
                        });
                    }
                }
            } catch (error) {
                console.warn('加载工具列表失败:', error);
                // 加载失败时使用默认空数组，不影响页面显示
                tools = [];
            }
        }

        // 记录工具使用
        function recordToolUsage(toolName) {
            // 异步记录，不阻塞跳转
            const API_BASE_URL = getToolApiBaseUrl();
            fetch(`${API_BASE_URL}/tools/record-usage`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    tool_key: toolName.replace(/\s+/g, '_').toLowerCase(),
                    tool_name: toolName
                })
            }).catch(error => {
                console.warn('记录工具使用失败:', error);
                // 静默失败，不影响用户体验
            });
        }

        // Initialize tool grid
        function renderTools() {
            toolGrid.innerHTML = '';

            const filteredTools = tools.filter(tool => {
                // Filter by industry
                if (activeIndustry !== 'all' && tool.industryName !== activeIndustry) {
                    return false;
                }

                // Filter by role
                if (activeRole !== 'all' && tool.roleName !== activeRole) {
                    return false;
                }

                // Filter by search query
                if (searchQuery) {
                    const query = searchQuery.toLowerCase();
                    return tool.title.toLowerCase().includes(query) ||
                           tool.description.toLowerCase().includes(query) ||
                           tool.industryName.toLowerCase().includes(query) ||
                           tool.roleName.toLowerCase().includes(query);
                }

                return true;
            });

            // Create tool cards
            filteredTools.forEach(tool => {
                const toolCard = document.createElement('div');
                toolCard.className = 'tool-card bg-light rounded-xl p-4 border border-gray-200 scale-hover';
                toolCard.setAttribute('data-industry', tool.industry);
                toolCard.setAttribute('data-role', tool.role);

                toolCard.innerHTML = `
                    <div class="flex justify-between items-start mb-3">
                        <div>
                            <h3 class="font-bold text-lg mb-1 flex items-center gap-1.5">
                                ${tool.title}
                                ${(tool.isExternal || tool.is_external || tool.isExternal === 1 || tool.is_external === 1) ? '<span class="bg-primary text-white text-[10px] px-2 py-0.5 rounded-full font-medium">外部</span>' : ''}
                            </h3>
                            <p class="text-sm text-muted mb-2">${tool.description}</p>
                        </div>
                        <button class="tool-btn bg-primary text-white w-8 h-8 rounded-full flex items-center justify-center hover:opacity-90 aspect-square" data-tool-id="${tool.id}">
                            ${(tool.isExternal || tool.is_external || tool.isExternal === 1 || tool.is_external === 1) ? '<i class="fas fa-external-link-alt"></i>' : '<i class="fas fa-arrow-right"></i>'}
                        </button>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-xs text-muted bg-white rounded-full px-2 py-1 inline-block">
                            ${tool.industryName}-${tool.roleName}
                        </span>
                        <span class="text-xs text-orange-500 font-medium flex items-center">
                            <i class="fas fa-fire mr-1"></i> ${toolRankMap.get(tool.title) || 0}
                        </span>
                    </div>
                `;

                toolGrid.appendChild(toolCard);
            });

            // Add click events to tool buttons
            document.querySelectorAll('.tool-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    // 检查用户是否已登录
                    const token = localStorage.getItem('auth_token');
                    if (!token) {
                        // 未登录，打开登录弹窗
                        document.getElementById('authModalBtn').click();
                        return;
                    }

                    const toolId = parseInt(this.getAttribute('data-tool-id'));
                    const tool = tools.find(t => t.id === toolId);
                    if (!tool) return;

                    console.log(`跳转到工具: ${tool.title}`);

                    // 优先使用后台配置的url
                    if (tool.url) {
                        // 如果标记为外部链接，或者是http/https开头的链接，打开新窗口
                        if ((tool.isExternal || tool.is_external || tool.isExternal === 1 || tool.is_external === 1) || tool.url.startsWith('http://') || tool.url.startsWith('https://')) {
                            window.open(tool.url, '_blank');
                        } else {
                            // 内部链接处理：强制从当前目录跳转，去掉所有前缀路径
                            let url = tool.url;
                            // 去掉所有前面的路径，只保留文件名
                            const fileName = url.split('/').pop();
                            // 使用./前缀强制从当前目录跳转
                            window.location.href = './' + fileName;
                        }
                    } else {
                        // 没有配置url的情况显示提示
                        alert(`即将跳转到 ${tool.title} 工具页面 (演示)`);
                    }
                });
            });
        }

        // Tab activation functions
        function activateIndustryTab(industryId) {
            const industryTabs = document.querySelectorAll('.industry-tab');
            industryTabs.forEach(tab => {
                const tabIndustryId = tab.getAttribute('data-industry-id');
                if (tabIndustryId === String(industryId) || (industryId === 'all' && tabIndustryId === 'all')) {
                    tab.classList.remove('bg-light', 'text-muted');
                    tab.classList.add('bg-primary', 'text-white');
                    tab.classList.add('active');
                } else {
                    tab.classList.remove('bg-primary', 'text-white', 'active');
                    tab.classList.add('bg-light', 'text-muted');
                }
            });

            selectedIndustryId = industryId;
            if (industryId === 'all') {
                activeIndustry = 'all';
            } else {
                const industry = industries.find(i => i.id === industryId);
                activeIndustry = industry ? industry.name : 'all';
            }
            activeRole = 'all'; // Reset role filter when industry changes
            generateRoleTabs(industryId);
            renderTools();
        }

        function activateRoleTab(role) {
            const roleButtons = roleTabsContainer.querySelectorAll('.role-tab');
            roleButtons.forEach(tab => {
                if (tab.getAttribute('data-role') === role) {
                    tab.classList.remove('bg-light', 'text-muted');
                    tab.classList.add('bg-primary', 'text-white');
                    tab.classList.add('active');
                } else {
                    tab.classList.remove('bg-primary', 'text-white', 'active');
                    tab.classList.add('bg-light', 'text-muted');
                }
            });
            activeRole = role;
            renderTools();
        }

        // Event Listeners

        // Search functionality
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                searchQuery = this.value.trim();
                renderTools();
            });
        }

        // Mobile search toggle
        if (mobileSearchBtn && mobileSearchBar) {
            mobileSearchBtn.addEventListener('click', () => {
                mobileSearchBar.classList.toggle('hidden');
                if (!mobileSearchBar.classList.contains('hidden')) {
                    mobileSearchBar.querySelector('input').focus();
                }
            });
        }

        // 监听页面可见性变化，回到页面时自动刷新热度数据
        document.addEventListener('visibilitychange', async () => {
            if (document.visibilityState === 'visible') {
                // 页面变为可见时，重新加载热度数据
                await loadToolRank();
                renderTools();
            }
        });

        // 加载系统设置
        async function loadSystemSettings() {
            try {
                const API_BASE_URL = getToolApiBaseUrl();
                const response = await fetch(`${API_BASE_URL}/tools/settings`);
                if (response.ok) {
                    const result = await response.json();
                    if (result.success && result.data) {
                        // 更新页面标题
                        if (result.data.site_title) {
                            document.title = result.data.site_title;
                            // 更新hero标题
                            const siteTitleHero = document.getElementById('siteTitleHero');
                            if (siteTitleHero) siteTitleHero.textContent = result.data.site_title;
                        }
                        // 更新网站Logo
                        if (result.data.site_logo) {
                            const logoContainer = document.querySelector('#siteLogoContainer');
                            if (logoContainer) {
                                let logoUrl = result.data.site_logo;
                                // 如果是相对路径，补全API地址
                                if (!logoUrl.startsWith('http')) {
                                    logoUrl = getToolApiBaseUrl().replace('/api', '') + logoUrl;
                                }
                                logoContainer.innerHTML = `<img src="${logoUrl}" alt="Logo" class="w-8 h-8 object-contain">`;
                            }
                        }
                        // 更新网站Logo名称
                        if (result.data.site_logo_name) {
                            const siteTitleLogo = document.getElementById('siteTitleLogo');
                            if (siteTitleLogo) siteTitleLogo.textContent = result.data.site_logo_name;
                        } else if (result.data.site_title) {
                            // 如果没有设置logo名称，使用网站标题
                            const siteTitleLogo = document.getElementById('siteTitleLogo');
                            if (siteTitleLogo) siteTitleLogo.textContent = result.data.site_title;
                        }
                        // 更新网站内容
                        if (result.data.announcement) {
                            const siteContent = document.getElementById('siteContent');
                            if (siteContent) siteContent.textContent = result.data.announcement;
                        }
                    }
                }
            } catch (error) {
                console.warn('加载系统设置失败:', error);
                // 加载失败时使用默认内容
            }
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', async () => {
            // 加载系统设置
            await loadSystemSettings();
            // 加载行业列表
            await loadIndustries();
            // 加载工具列表
            await loadTools();
            // 加载工具热度数据
            await loadToolRank();
            renderTools();

            // Add fade-in effect to tool cards
            setTimeout(() => {
                document.querySelectorAll('.tool-card').forEach((card, index) => {
                    card.style.animationDelay = `${index * 0.05}s`;
                    card.classList.add('fade-in');
                });
            }, 100);

            // Auth Modal functionality
            const authModalBtn = document.getElementById('authModalBtn');
            const authModalOverlay = document.getElementById('authModalOverlay');
            const modalTabs = document.querySelectorAll('.modal-tab');
            const loginForm = document.getElementById('loginForm');
            const registerForm = document.getElementById('registerForm');
            const switchToRegister = document.getElementById('switchToRegister');
            const switchToLogin = document.getElementById('switchToLogin');

            // Open modal
            authModalBtn.addEventListener('click', (e) => {
                // 检查用户是否已登录
                const token = localStorage.getItem('auth_token');
                if (token) {
                    // 如果已登录，检查是否点击的是登出按钮
                    const logoutBtn = e.target.closest('#logoutBtn');
                    if (!logoutBtn) {
                        // 点击的不是登出按钮，不打开登录/注册弹窗
                        // 阻止默认行为和事件冒泡
                        e.preventDefault();
                        e.stopPropagation();
                        return;
                    }
                    // 点击的是登出按钮，执行登出操作
                    logout();
                    return;
                }

                // 用户未登录，打开登录/注册弹窗
                authModalOverlay.classList.add('active');
                // Reset to login tab
                switchTab('login');
                // Clear form inputs when opening modal
                clearFormInputs();
            });

            // 关闭弹窗：点击右上角X按钮
            const modalCloseBtn = document.getElementById('modalCloseBtn');
            modalCloseBtn.addEventListener('click', closeModal);

            // 注释掉点击遮罩层关闭逻辑，现在点击半透明区域不会关闭弹窗
            // // Close modal via overlay click
            // authModalOverlay.addEventListener('click', (e) => {
            //     if (e.target === authModalOverlay) {
            //         closeModal();
            //     }
            // });

            // Close modal via ESC key
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && authModalOverlay.classList.contains('active')) {
                    closeModal();
                }
            });

            // Tab switching
            modalTabs.forEach(tab => {
                tab.addEventListener('click', () => {
                    const tabName = tab.getAttribute('data-tab');
                    switchTab(tabName);
                });
            });

            // Switch to register link
            switchToRegister.addEventListener('click', (e) => {
                e.preventDefault();
                switchTab('register');
            });

            // Switch to login link
            switchToLogin.addEventListener('click', (e) => {
                e.preventDefault();
                switchTab('login');
            });

            // API 配置
            function getApiBaseUrl() {
                // 如果当前页面通过文件协议打开，使用 localhost:15000
                if (window.location.protocol === 'file:') {
                    return 'http://localhost:20000/api';
                }

                // 如果通过 HTTP 打开，使用相对路径（假设 API 在同一域名下）
                // 公网访问默认走80端口，内网可使用完整路径：return 'http://' + window.location.hostname + ':15000/api';
                return '/api'; // 假设有反向代理将 /api 转发到后端15000端口
            }

            const API_BASE_URL = getApiBaseUrl();
            console.log('API 基础 URL:', API_BASE_URL);

            // 显示消息函数
            function showMessage(type, message) {
                // 移除现有消息
                const existingMessages = document.querySelectorAll('.form-message');
                existingMessages.forEach(msg => msg.remove());

                // 创建新消息元素
                const messageDiv = document.createElement('div');
                messageDiv.className = `form-message p-3 rounded-md mb-4 ${
                    type === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                }`;
                messageDiv.textContent = message;

                // 插入到表单顶部
                const activeForm = document.querySelector('.modal-form.active');
                if (activeForm) {
                    activeForm.insertBefore(messageDiv, activeForm.firstChild);
                }

                // 自动移除消息（如果是错误消息）
                if (type === 'error') {
                    setTimeout(() => {
                        messageDiv.remove();
                    }, 5000);
                }
            }

            // Form submission
            loginForm.addEventListener('submit', async (e) => {
                e.preventDefault();

                const email = loginForm.querySelector('input[type="email"]').value;
                const password = loginForm.querySelector('input[type="password"]').value;

                // 基础验证
                if (!email || !password) {
                    showMessage('error', '邮箱和密码不能为空');
                    return;
                }

                // 邮箱格式验证
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    showMessage('error', '邮箱格式不正确');
                    return;
                }

                try {
                    // 显示加载状态
                    const submitBtn = loginForm.querySelector('button[type="submit"]');
                    const originalText = submitBtn.textContent;
                    submitBtn.textContent = '登录中...';
                    submitBtn.disabled = true;

                    // 检查是否有第三方登录数据，有则一起提交进行绑定
                    const thirdPartyData = localStorage.getItem('third_party_data');
                    const requestBody = { email, password };
                    if (thirdPartyData) {
                        requestBody.thirdParty = JSON.parse(thirdPartyData);
                    }

                    const response = await fetch(`${API_BASE_URL}/auth/login`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestBody)
                    });

                    const data = await response.json();

                    if (!response.ok) {
                        throw new Error(data.error || data.errors?.[0] || '登录失败');
                    }

                    // 登录成功
                    showMessage('success', data.message || '登录成功');
                    console.log('登录成功:', data);

                    // 保存 token 到 localStorage（实际应用中可能需要更安全的存储）
                    if (data.token) {
                        localStorage.setItem('auth_token', data.token);
                        localStorage.setItem('user_email', data.user.email);
                        localStorage.setItem('user_id', data.user.id);
                    }

                    // 清除第三方登录数据（如果存在）
                    localStorage.removeItem('third_party_data');

                    // 立即重置按钮状态（即使弹窗即将关闭）
                    submitBtn.textContent = '登录';
                    submitBtn.disabled = false;

                    // 0.5秒后关闭弹窗
                    setTimeout(() => {
                        closeModal();
                        // 更新界面显示登录状态
                        updateAuthUI(true, data.user.email);
                    }, 500);

                } catch (error) {
                    console.error('登录错误详情:', error);

                    let errorMessage = '登录失败，请检查网络连接';

                    if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
                        errorMessage = '无法连接到服务器。请检查：<br>1. 后端服务是否运行 (http://localhost:20000)<br>2. 是否通过 HTTP 服务器打开此页面';
                        console.log('API 基础 URL:', API_BASE_URL);
                    } else if (error.message) {
                        errorMessage = error.message;
                    }

                    showMessage('error', errorMessage);

                    // 恢复按钮状态
                    const submitBtn = loginForm.querySelector('button[type="submit"]');
                    submitBtn.textContent = '登录';
                    submitBtn.disabled = false;
                }
            });

            registerForm.addEventListener('submit', async (e) => {
                e.preventDefault();

                const email = registerForm.querySelector('input[type="email"]').value;
                const password = registerForm.querySelector('input[type="password"]').value;
                const confirmPassword = registerForm.querySelectorAll('input[type="password"]')[1].value;

                // 基础验证
                if (!email || !password || !confirmPassword) {
                    showMessage('error', '所有字段都是必填的');
                    return;
                }

                // 邮箱格式验证
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    showMessage('error', '邮箱格式不正确');
                    return;
                }

                // 密码长度验证
                if (password.length < 6) {
                    showMessage('error', '密码长度至少为6位');
                    return;
                }

                // 确认密码验证
                if (password !== confirmPassword) {
                    showMessage('error', '密码与确认密码不一致');
                    return;
                }

                try {
                    // 显示加载状态
                    const submitBtn = registerForm.querySelector('button[type="submit"]');
                    const originalText = submitBtn.textContent;
                    submitBtn.textContent = '注册中...';
                    submitBtn.disabled = true;

                    // 检查是否有第三方登录数据
                    const thirdPartyData = localStorage.getItem('third_party_data');
                    const requestBody = { email, password, confirmPassword };

                    if (thirdPartyData) {
                        requestBody.thirdParty = JSON.parse(thirdPartyData);
                    }

                    const response = await fetch(`${API_BASE_URL}/auth/register`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestBody)
                    });

                    const data = await response.json();

                    if (!response.ok) {
                        throw new Error(data.error || data.errors?.[0] || '注册失败');
                    }

                    // 注册成功
                    showMessage('success', data.message || '注册成功');
                    console.log('注册成功:', data);

                    // 保存 token 到 localStorage
                    if (data.token) {
                        localStorage.setItem('auth_token', data.token);
                        localStorage.setItem('user_email', data.user.email);
                        localStorage.setItem('user_id', data.user.id);
                    }

                    // 清除第三方登录数据（如果存在）
                    if (thirdPartyData) {
                        localStorage.removeItem('third_party_data');
                    }

                    // 立即重置按钮状态（即使即将切换到登录表单）
                    submitBtn.textContent = '注册';
                    submitBtn.disabled = false;

                    if (thirdPartyData) {
                        // 第三方绑定注册成功，直接登录
                        showMessage('success', '注册并绑定成功，正在登录...');
                        setTimeout(() => {
                            closeModal();
                            updateAuthUI(true, data.user.email);
                        }, 1000);
                    } else {
                        // 普通注册，2秒后切换到登录表单
                        setTimeout(() => {
                            showMessage('success', '注册成功！请登录');
                            switchTab('login');
                            // 清除注册表单
                            registerForm.querySelectorAll('input').forEach(input => {
                                input.value = '';
                            });

                            // 按钮状态已经重置，这里不需要再次重置
                        }, 2000);
                    }

                } catch (error) {
                    console.error('注册错误详情:', error);

                    let errorMessage = '注册失败，请稍后重试';

                    if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
                        errorMessage = '无法连接到服务器。请检查：<br>1. 后端服务是否运行 (http://localhost:20000)<br>2. 是否通过 HTTP 服务器打开此页面';
                        console.log('API 基础 URL:', API_BASE_URL);
                    } else if (error.message) {
                        errorMessage = error.message;
                    }

                    showMessage('error', errorMessage);

                    // 恢复按钮状态
                    const submitBtn = registerForm.querySelector('button[type="submit"]');
                    submitBtn.textContent = '注册';
                    submitBtn.disabled = false;
                }
            });

            // 第三方登录处理
            const qqLoginBtn = document.getElementById('qqLoginBtn');
            const wechatLoginBtn = document.getElementById('wechatLoginBtn');
            const douyinLoginBtn = document.getElementById('douyinLoginBtn');

            // 保存第三方登录窗口和定时器引用
            let authWindow = null;
            let windowCloseTimer = null;

            // 第三方登录通用处理函数
            async function handleThirdPartyLogin(provider) {
                try {
                    // 先清除之前的定时器和窗口，避免重复打开
                    if (windowCloseTimer) clearInterval(windowCloseTimer);
                    if (authWindow && !authWindow.closed) authWindow.close();

                    // 显示加载状态
                    showMessage('info', `正在跳转到${provider}扫码登录...`);

                    // 1. 调用后端接口获取第三方登录授权链接
                    const response = await fetch(`${API_BASE_URL}/auth/third-party/login`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ provider })
                    });

                    const data = await response.json();

                    if (!response.ok) {
                        throw new Error(data.error || `获取${provider}登录链接失败`);
                    }

                    // 2. 打开授权弹窗
                    authWindow = window.open(
                        data.authUrl,
                        `${provider}登录`,
                        'width=600,height=700,top=100,left=200,menubar=no,toolbar=no,status=no,scrollbars=yes'
                    );

                    // 3. 监听授权窗口的回调消息
                    const messageListener = async (event) => {
                        console.log('收到第三方登录回调消息:', event);

                        // 收到回调先清除关闭检测定时器
                        if (windowCloseTimer) clearInterval(windowCloseTimer);

                        // 临时关闭origin验证方便调试，生产环境建议开启
                        // if (event.origin !== window.location.origin) {
                        //     console.warn('消息来源不合法:', event.origin);
                        //     return;
                        // }

                        try {
                            if (event.data.type === 'THIRD_PARTY_AUTH_SUCCESS') {
                                console.log('登录成功回调:', event.data.payload);
                                // 关闭授权窗口
                                authWindow.close();
                                window.removeEventListener('message', messageListener);

                                const { code, state, provider: callbackProvider, openId, userInfo } = event.data.payload;

                                if (callbackProvider !== provider) {
                                    throw new Error('登录提供商不匹配');
                                }

                                // 4. 直接使用GET回调返回的openId，避免code重复使用问题
                                showMessage('info', '正在验证登录信息...');

                                // 直接提交openId到后端
                                const verifyResponse = await fetch(`${API_BASE_URL}/auth/third-party/callback`, {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json'
                                    },
                                    body: JSON.stringify({
                                        provider,
                                        openId,
                                        userInfo,
                                        code,
                                        state
                                    })
                                });

                                const verifyData = await verifyResponse.json();
                                console.log('后端验证返回:', verifyData);

                                if (!verifyResponse.ok) {
                                    throw new Error(verifyData.error || `${provider}登录验证失败`);
                                }

                                if (verifyData.status === 'existing_user') {
                                    // 已有关联账号，直接登录
                                    localStorage.setItem('auth_token', verifyData.token);
                                    localStorage.setItem('user_email', verifyData.user.email);
                                    localStorage.setItem('user_id', verifyData.user.id);

                                    showMessage('success', `${provider}登录成功`);
                                    setTimeout(() => {
                                        closeModal();
                                        updateAuthUI(true, verifyData.user.email);
                                    }, 800);
                                } else if (verifyData.status === 'new_user') {
                                    // 无关联账号，直接跳转到注册流程
                                    showMessage('info', '检测到您是首次使用第三方登录，请完成注册');

                                    // 保存第三方登录信息到localStorage
                                    localStorage.setItem('third_party_data', JSON.stringify({
                                        provider,
                                        openId: verifyData.openId,
                                        userInfo: verifyData.userInfo
                                    }));

                                    // 切换到注册表单
                                    setTimeout(() => {
                                        switchTab('register');
                                        // 预填邮箱（如果第三方返回了的话）
                                        const emailInput = registerForm.querySelector('input[type="email"]');
                                        if (verifyData.userInfo && verifyData.userInfo.email) {
                                            emailInput.value = verifyData.userInfo.email;
                                        }
                                    }, 800);
                                } else if (verifyData.status === 'auto_registered') {
                                    // 自动注册并登录成功
                                    localStorage.setItem('auth_token', verifyData.token);
                                    localStorage.setItem('user_email', verifyData.user.email);
                                    localStorage.setItem('user_id', verifyData.user.id);

                                    showMessage('success', '登录成功');
                                    setTimeout(() => {
                                        closeModal();
                                        updateAuthUI(true, verifyData.user.email);
                                    }, 800);
                                }

                            } else if (event.data.type === 'THIRD_PARTY_AUTH_ERROR') {
                                // 授权失败
                                authWindow.close();
                                window.removeEventListener('message', messageListener);
                                console.error('第三方登录错误:', event.data.payload);
                                showMessage('error', event.data.payload.error || `${provider}登录失败，请稍后重试`);
                            } else if (event.data.type === 'THIRD_PARTY_AUTH_CANCEL') {
                                // 用户取消授权
                                authWindow.close();
                                window.removeEventListener('message', messageListener);
                                showMessage('info', `${provider}登录已取消`);
                            } else if (event.data.type === 'THIRD_PARTY_AUTH_EXPIRED') {
                                // 授权过期，需要重新登录
                                authWindow.close();
                                window.removeEventListener('message', messageListener);
                                // 清除登录状态
                                localStorage.removeItem('auth_token');
                                localStorage.removeItem('user_id');
                                localStorage.removeItem('user_email');
                                updateAuthUI(false);
                                showMessage('error', event.data.payload?.error || `${provider}授权已过期，请重新登录`);
                            }
                        } catch (error) {
                            console.error(`${provider}登录处理错误:`, error);
                            showMessage('error', error.message || `${provider}登录失败，请稍后重试`);
                            // 确保窗口关闭
                            try { authWindow.close(); } catch (e) {}
                            window.removeEventListener('message', messageListener);
                        }
                    };

                    window.addEventListener('message', messageListener);

                    // 检测用户是否手动关闭授权窗口
                    windowCloseTimer = setInterval(() => {
                        if (authWindow && authWindow.closed) {
                            clearInterval(windowCloseTimer);
                            window.removeEventListener('message', messageListener);
                            // 清除所有提示信息，恢复界面
                            const existingMessages = document.querySelectorAll('.form-message');
                            existingMessages.forEach(msg => msg.remove());
                        }
                    }, 500);

                } catch (error) {
                    console.error(`${provider}登录错误:`, error);
                    showMessage('error', error.message || `${provider}登录失败，请稍后重试`);
                }
            }

            // 绑定第三方登录按钮事件
            qqLoginBtn?.addEventListener('click', () => handleThirdPartyLogin('qq'));
            // wechatLoginBtn?.addEventListener('click', () => handleThirdPartyLogin('wechat'));
            // douyinLoginBtn?.addEventListener('click', () => handleThirdPartyLogin('douyin'));

            // 更新认证 UI 状态
            function updateAuthUI(isLoggedIn, userEmail = '') {
                const authBtn = document.getElementById('authModalBtn');
                if (!authBtn) return;

                // 确保按钮有正确的样式类
                const buttonClasses = ['bg-primary', 'text-white', 'px-4', 'py-2', 'rounded-md', 'font-medium', 'hover:opacity-90', 'transition-opacity'];
                buttonClasses.forEach(cls => authBtn.classList.add(cls));

                if (isLoggedIn && userEmail) {
                    // 显示用户邮箱和登出按钮
                    authBtn.innerHTML = `
                        <div class="flex items-center space-x-2">
                            <i class="fas fa-user-circle"></i>
                            <span class="truncate max-w-[150px]">${userEmail}</span>
                            <span class="text-xs">|</span>
                            <span class="text-xs hover:underline cursor-pointer" id="logoutBtn">登出</span>
                        </div>
                    `;

                } else {
                    // 显示登录/注册按钮
                    authBtn.innerHTML = '登录/注册';
                }
            }

            // 登出函数
            function logout() {
                localStorage.removeItem('auth_token');
                localStorage.removeItem('user_email');
                localStorage.removeItem('user_id');
                updateAuthUI(false);
                showMessage('success', '已成功登出');
            }

            // 页面加载时检查登录状态
            function checkAuthStatus() {
                const token = localStorage.getItem('auth_token');
                const userEmail = localStorage.getItem('user_email');

                if (token && userEmail) {
                    updateAuthUI(true, userEmail);

                    // 可选：验证 token 是否有效
                    // verifyToken(token);
                }
            }

            // 初始化检查
            checkAuthStatus();

            // // 检查是否通过文件协议打开
            // if (window.location.protocol === 'file:') {
            //     console.warn('⚠️ 当前通过文件协议 (file://) 打开页面');
            //     console.warn('📢 建议：使用 HTTP 服务器打开页面以避免跨域问题');
            //     console.warn('   在终端中运行: python -m http.server 5500');
            //     console.warn('   然后访问: http://localhost:5500');

            //     // 在页面顶部显示友好的提示
            //     const fileProtocolWarning = document.createElement('div');
            //     fileProtocolWarning.className = 'bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 mb-4';
            //     fileProtocolWarning.innerHTML = `
            //         <div class="flex">
            //             <div class="flex-shrink-0">
            //                 <i class="fas fa-exclamation-triangle"></i>
            //             </div>
            //             <div class="ml-3">
            //                 <p class="font-medium">提示：检测到通过文件协议打开页面</p>
            //                 <p class="text-sm mt-1">这可能导致无法连接到后端服务。建议：</p>
            //                 <ul class="text-sm mt-1 list-disc list-inside">
            //                     <li>使用 HTTP 服务器打开此页面</li>
            //                     <li>在终端中运行: <code class="bg-gray-100 px-1 rounded">python -m http.server 5500</code></li>
            //                     <li>然后访问: <a href="http://localhost:5500" class="text-blue-600 hover:underline">http://localhost:5500</a></li>
            //                 </ul>
            //             </div>
            //         </div>
            //     `;

            //     // 插入到页面顶部（header之后）
            //     const header = document.querySelector('header');
            //     if (header) {
            //         header.parentNode.insertBefore(fileProtocolWarning, header.nextSibling);
            //     }
            // }

            // 测试后端连接
            async function testBackendConnection() {
                try {
                    const response = await fetch(`${API_BASE_URL}/health`, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    });

                    if (response.ok) {
                        console.log('✅ 后端连接正常');
                    } else {
                        console.warn('⚠️ 后端连接异常，状态码:', response.status);
                    }
                } catch (error) {
                    console.warn('⚠️ 无法连接到后端服务，请确保后端正在运行 (http://localhost:20000)');
                    console.warn('错误详情:', error.message);

                    // 如果后端不可用，在控制台显示启动指南
                    console.log('🚀 启动后端服务指南:');
                    console.log('   1. 打开终端，进入 back 目录: cd back');
                    console.log('   2. 安装依赖: npm install');
                    console.log('   3. 启动服务: npm run dev');
                    console.log('   4. 验证服务: 访问 http://localhost:20000/api/health');
                }
            }

            // 延迟执行健康检查，避免阻塞页面加载
            setTimeout(testBackendConnection, 1000);

            // Tab switching function
            function switchTab(tabName) {
                // Clear all form messages when switching tabs
                const existingMessages = document.querySelectorAll('.form-message');
                existingMessages.forEach(msg => msg.remove());

                // Clear inputs of the form that will be hidden
                if (tabName === 'login') {
                    // Switching to login, clear register form inputs
                    registerForm.querySelectorAll('input').forEach(input => {
                        input.value = '';
                    });
                } else {
                    // Switching to register, clear login form inputs
                    loginForm.querySelectorAll('input').forEach(input => {
                        input.value = '';
                    });
                }

                // Update tab styles
                modalTabs.forEach(tab => {
                    if (tab.getAttribute('data-tab') === tabName) {
                        tab.classList.add('active');
                    } else {
                        tab.classList.remove('active');
                    }
                });

                // Show/hide forms
                if (tabName === 'login') {
                    loginForm.classList.add('active');
                    registerForm.classList.remove('active');
                } else {
                    loginForm.classList.remove('active');
                    registerForm.classList.add('active');
                }
            }

            // Clear form inputs and messages function
            function clearFormInputs() {
                // Clear login form inputs
                loginForm.querySelectorAll('input').forEach(input => {
                    input.value = '';
                });

                // Clear register form inputs
                registerForm.querySelectorAll('input').forEach(input => {
                    input.value = '';
                });

                // Clear all form messages
                const existingMessages = document.querySelectorAll('.form-message');
                existingMessages.forEach(msg => msg.remove());

                // Reset button states
                const loginSubmitBtn = loginForm.querySelector('button[type="submit"]');
                if (loginSubmitBtn) {
                    loginSubmitBtn.textContent = '登录';
                    loginSubmitBtn.disabled = false;
                }

                const registerSubmitBtn = registerForm.querySelector('button[type="submit"]');
                if (registerSubmitBtn) {
                    registerSubmitBtn.textContent = '注册';
                    registerSubmitBtn.disabled = false;
                }

                console.log('Form inputs, messages and button states cleared');
            }

            // Close modal function
            function closeModal() {
                authModalOverlay.classList.remove('active');
                clearFormInputs();
            }
        });
    </script>
</body>
</html>