<?php
/**
 * 新标签页首页 (PHP版本)
 * 优先从JSON/缓存加载首页标签
 */
error_reporting(0);
ini_set('display_errors', 0);

$originalLinks = [];

// 尝试读取JSON文件（最优先）
$jsonFile = __DIR__ . '/index-links.json';
if (file_exists($jsonFile)) {
    $jsonContent = @file_get_contents($jsonFile);
    $jsonData = @json_decode($jsonContent, true);
    if ($jsonData && is_array($jsonData)) {
        $originalLinks = $jsonData;
    }
}

// 如果JSON不存在，尝试从数据库读取
if (empty($originalLinks)) {
    try {
        require_once __DIR__ . '/config/config.php';
        require_once __DIR__ . '/includes/functions.php';
        
        $db = Database::getInstance();
        
        // 检查is_homepage字段是否存在
        $columns = $db->fetchAll("SHOW COLUMNS FROM tag_library LIKE 'is_homepage'");
        
        if (!empty($columns)) {
            $homepageTags = $db->fetchAll(
                "SELECT id, name, url, domain, icon, icon_type 
                 FROM tag_library 
                 WHERE status = 1 AND is_homepage = 1 
                 ORDER BY sort_order ASC, id ASC"
            );
        } else {
            // 兼容旧版本，使用is_featured
            $homepageTags = $db->fetchAll(
                "SELECT id, name, url, domain, icon, icon_type 
                 FROM tag_library 
                 WHERE status = 1 AND is_featured = 1 
                 ORDER BY sort_order ASC, id ASC 
                 LIMIT 20"
            );
        }
        
        if (!empty($homepageTags)) {
            $originalLinks = array_map(function($tag) {
                return [
                    'id' => 'homepage-' . $tag['id'],
                    'name' => $tag['name'],
                    'url' => $tag['url'],
                    'icon' => $tag['icon'] ?: '',
                    'iconType' => $tag['icon_type'] ?: 'letter',
                    'isFixed' => true
                ];
            }, $homepageTags);
        }
    } catch (Exception $e) {
        // 数据库错误，使用默认
    }
}

// 如果仍然为空，使用默认链接
if (empty($originalLinks)) {
    $originalLinks = [
        ['id' => 'baidu', 'name' => '百度', 'url' => 'https://www.baidu.com', 'icon' => '', 'iconType' => 'letter', 'isFixed' => true],
        ['id' => 'taobao', 'name' => '淘宝', 'url' => 'https://www.taobao.com', 'icon' => '', 'iconType' => 'letter', 'isFixed' => true],
        ['id' => 'zhihu', 'name' => '知乎', 'url' => 'https://www.zhihu.com', 'icon' => '', 'iconType' => 'letter', 'isFixed' => true],
        ['id' => 'bilibili', 'name' => '哔哩哔哩', 'url' => 'https://www.bilibili.com', 'icon' => '', 'iconType' => 'letter', 'isFixed' => true],
    ];
}

$originalLinksJson = json_encode($originalLinks, JSON_UNESCAPED_UNICODE);
$apiBase = '/api';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新标签页</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; min-height: 100vh; }
        
        /* 用户区域 */
        .user-area { position: fixed; top: 15px; right: 20px; z-index: 100; display: flex; align-items: center; gap: 10px; }
        .login-btn { padding: 8px 20px; background: #4299e1; color: white; border: none; border-radius: 20px; cursor: pointer; font-size: 14px; transition: all 0.3s; display: flex; align-items: center; gap: 5px; }
        .login-btn:hover { background: #3182ce; }
        .user-avatar-btn { width: 40px; height: 40px; border-radius: 50%; border: 2px solid #4299e1; cursor: pointer; overflow: hidden; background: #4299e1; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 16px; transition: all 0.3s; }
        .user-avatar-btn:hover { transform: scale(1.05); }
        .user-avatar-btn img { width: 100%; height: 100%; object-fit: cover; }
        
        /* 用户弹窗 */
        .user-popup { position: absolute; top: 50px; right: 0; width: 320px; background: white; border-radius: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); display: none; z-index: 1000; overflow: hidden; }
        .user-popup.show { display: block; }
        .user-popup-header { padding: 20px; text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .user-popup-avatar { width: 80px; height: 80px; border-radius: 50%; margin: 0 auto 15px; background: white; display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: bold; color: #667eea; overflow: hidden; }
        .user-popup-avatar img { width: 100%; height: 100%; object-fit: cover; }
        .user-popup-name { font-size: 18px; font-weight: 600; }
        .user-popup-email { font-size: 13px; opacity: 0.9; }
        .user-popup-body { padding: 15px; }
        .user-popup-item { display: flex; align-items: center; padding: 12px 15px; border-radius: 8px; cursor: pointer; transition: background 0.2s; color: #4a5568; font-size: 14px; }
        .user-popup-item:hover { background: #f7fafc; }
        .user-popup-item svg { margin-right: 12px; color: #718096; }
        
        /* 历史数据下拉 */
        .history-container { position: relative; }
        .history-dropdown { background: #f7fafc; border-radius: 8px; margin-top: 5px; display: none; max-height: 250px; overflow-y: auto; }
        .history-dropdown.show { display: block; }
        .history-item { padding: 10px 15px; cursor: pointer; border-bottom: 1px solid #e2e8f0; transition: background 0.2s; }
        .history-item:hover { background: #edf2f7; }
        .history-item:last-child { border-bottom: none; }
        .history-date { font-size: 12px; color: #718096; }
        .history-version { font-weight: 500; color: #4a5568; }
        .history-loading { padding: 15px; text-align: center; color: #718096; }
        
        /* 认证弹窗 */
        .auth-modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 2000; opacity: 0; visibility: hidden; transition: all 0.3s; }
        .auth-modal.show { opacity: 1; visibility: visible; }
        .auth-modal-content { background: white; border-radius: 16px; width: 90%; max-width: 400px; padding: 40px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); position: relative; }
        .auth-modal-close { position: absolute; top: 15px; right: 20px; background: none; border: none; font-size: 28px; cursor: pointer; color: #a0aec0; }
        .auth-modal-title { text-align: center; font-size: 24px; font-weight: 600; color: #2d3748; margin-bottom: 10px; }
        .auth-modal-subtitle { text-align: center; color: #718096; margin-bottom: 30px; font-size: 14px; }
        .auth-tabs { display: flex; margin-bottom: 25px; border-bottom: 2px solid #e2e8f0; }
        .auth-tab { flex: 1; padding: 12px; text-align: center; cursor: pointer; color: #718096; font-weight: 500; border-bottom: 2px solid transparent; margin-bottom: -2px; }
        .auth-tab.active { color: #4299e1; border-bottom-color: #4299e1; }
        .auth-form { display: none; }
        .auth-form.active { display: block; }
        .auth-input-group { margin-bottom: 20px; }
        .auth-input-group label { display: block; margin-bottom: 8px; font-weight: 500; color: #4a5568; font-size: 14px; }
        .auth-input { width: 100%; padding: 12px 15px; border: 2px solid #e2e8f0; border-radius: 10px; font-size: 15px; }
        .auth-input:focus { outline: none; border-color: #4299e1; }
        .auth-submit { width: 100%; padding: 14px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 10px; font-size: 16px; font-weight: 600; cursor: pointer; }
        .auth-submit:disabled { opacity: 0.6; cursor: not-allowed; }
        .auth-error { color: #e53e3e; font-size: 13px; margin-top: 10px; text-align: center; display: none; }
        .auth-error.show { display: block; }
        
        /* 搜索框样式 */
        .search-box { display: flex; position: relative; margin: 100px auto 50px; width: 100%; max-width: 650px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .engine-selector { position: relative; width: 120px; }
        .selected-engine { display: flex; align-items: center; padding: 0 15px; height: 45px; background: #f8f9fa; border: 2px solid #e2e8f0; border-right: none; border-radius: 30px 0 0 30px; cursor: pointer; transition: all 0.3s ease; }
        .selected-engine:hover { background: #edf2f7; }
        .engine-icon { width: 16px; height: 16px; margin-right: 10px; }
        .down-arrow { margin-left: auto; width: 16px; height: 16px; color: #718096; }
        .engine-options { position: absolute; top: 100%; left: 0; width: 100%; background: white; border: 2px solid #e2e8f0; border-top: none; border-radius: 0 0 12px 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); display: none; z-index: 11; }
        .engine-option { display: flex; align-items: center; padding: 12px 15px; cursor: pointer; transition: background 0.2s ease; }
        .engine-option:hover { background: #f7fafc; }
        .engine-option img { width: 16px; height: 16px; margin-right: 10px; }
        #search-input { flex: 1; padding: 0 20px; border: 2px solid #e2e8f0; border-left: none; border-right: none; font-size: 17px; outline: none; height: 45px; }
        #search-button { width: 60px; background: transparent; color: #4a5568; border: 2px solid #e2e8f0; border-left: none; border-radius: 0 30px 30px 0; cursor: pointer; font-size: 20px; transition: all 0.3s; }
        #search-button:hover { color: #4299e1; background: #f7fafc; }
        .suggestion-box { position: absolute; top: 100%; left: 120px; right: 60px; background: white; border: 2px solid #e2e8f0; border-top: none; border-radius: 0 0 12px 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); display: none; z-index: 10; max-height: 400px; overflow-y: auto; }
        .suggestion-item { padding: 12px 20px; cursor: pointer; transition: background 0.2s ease; text-align: left; }
        .suggestion-item:hover, .suggestion-item.active { background: #f1f5f9; }
        
        /* 链接容器样式 */
        .linkbox, .linkbox * { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }
        .linkbox { position: relative; margin: 0 auto; width: 100%; max-width: 1000px; background: rgba(255, 255, 255, 0.8); border-radius: 20px; padding: 30px; backdrop-filter: blur(10px); }
        .links-container { display: flex; flex-wrap: wrap; padding: 0; margin: 0; position: relative; width: 100%; }
        
        /* 链接项样式 - 圆形图标 */
        .link-item { position: relative; width: 90px; height: 120px; margin: 15px; transition: all 0.3s ease; cursor: grab; z-index: 1; border-radius: 15px; overflow: hidden; }
        .link-item:active { cursor: grabbing; }
        .link-item a { display: flex; flex-direction: column; align-items: center; justify-content: center; text-decoration: none; color: #333; width: 100%; height: 100%; transition: all 0.3s ease; border-radius: 15px; background: rgba(255, 255, 255, 0.9); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05); }
        .link-item a:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1); background: white; }
        .link-item img { width: 50px; height: 50px; display: block; border-radius: 50%; transition: transform 0.3s; margin-bottom: 10px; object-fit: cover; }
        .link-item .letter-icon { width: 50px; height: 50px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: bold; color: white; margin-bottom: 10px; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); }
        .link-item p { margin: 5px 0; width: 90px; height: 25px; overflow: hidden; text-align: center; font-size: 14px; line-height: 25px; font-weight: 500; text-overflow: ellipsis; white-space: nowrap; }
        
        /* 添加按钮样式 */
        .add-link-btn { position: relative; width: 90px; height: 120px; margin: 15px; cursor: pointer; border-radius: 15px; display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(255, 255, 255, 0.9); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05); transition: all 0.3s ease; border: 2px dashed #cbd5e0; }
        .add-link-btn:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1); background: white; border-color: #4299e1; }
        .add-link-btn .plus-icon { font-size: 30px; color: #718096; margin-bottom: 10px; transition: color 0.3s; }
        .add-link-btn:hover .plus-icon { color: #4299e1; }
        .add-link-btn p { margin: 5px 0; width: 90px; height: 25px; overflow: hidden; text-align: center; font-size: 14px; line-height: 25px; font-weight: 500; color: #718096; }
        
        /* 拖拽样式 */
        .sortable-ghost { opacity: 0.4; transform: scale(0.95); }
        .sortable-chosen { transform: scale(1.05); box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2); z-index: 1000; }
        .sortable-drag { transform: rotate(5deg); box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2); }
        
        /* 模态框样式 */
        .modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; opacity: 0; visibility: hidden; transition: all 0.3s; }
        .modal-overlay.active { opacity: 1; visibility: visible; }
        .modal-content { background: white; border-radius: 12px; padding: 30px; width: 90%; max-width: 500px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2); transform: translateY(-20px); transition: transform 0.3s; }
        .modal-overlay.active .modal-content { transform: translateY(0); }
        .modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .modal-title { font-size: 20px; font-weight: 600; color: #2d3748; }
        .close-btn { background: none; border: none; font-size: 24px; cursor: pointer; color: #718096; transition: color 0.3s; }
        .close-btn:hover { color: #2d3748; }
        .form-group { margin-bottom: 20px; position: relative; }
        .form-label { display: block; margin-bottom: 8px; font-weight: 500; color: #4a5568; }
        .form-input { width: 100%; padding: 10px 15px; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 16px; transition: border-color 0.3s; box-sizing: border-box; }
        .form-input:focus { outline: none; border-color: #4299e1; }
        .form-hint { font-size: 12px; color: #718096; margin-top: 5px; }
        .modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 25px; }
        .btn { padding: 10px 20px; border-radius: 8px; font-size: 16px; cursor: pointer; transition: all 0.3s; border: none; }
        .btn-cancel { background: #e2e8f0; color: #4a5568; }
        .btn-cancel:hover { background: #cbd5e0; }
        .btn-submit { background: #4299e1; color: white; }
        .btn-submit:hover { background: #3182ce; }
        
        /* 图标预览样式 */
        .icon-preview { width: 50px; height: 50px; border-radius: 50%; margin: 10px auto; display: flex; align-items: center; justify-content: center; background: #e2e8f0; overflow: hidden; }
        .icon-preview img { width: 100%; height: 100%; object-fit: cover; border-radius: 50%; }
        .icon-preview .letter-icon { width: 50px; height: 50px; border-radius: 50%; font-size: 24px; font-weight: bold; color: white; display: flex; align-items: center; justify-content: center; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); }
        .icon-actions { display: flex; gap: 10px; margin-top: 10px; }
        .icon-action-btn { flex: 1; padding: 8px 10px; font-size: 14px; background: #718096; color: white; border: none; border-radius: 6px; cursor: pointer; transition: background 0.3s; }
        .icon-action-btn:hover { background: #4a5568; }
        .file-upload-container { margin-top: 10px; border: 2px dashed #cbd5e0; border-radius: 8px; padding: 15px; text-align: center; transition: border-color 0.3s; }
        .file-upload-container:hover { border-color: #4299e1; }
        .file-upload-label { display: block; cursor: pointer; color: #4299e1; font-weight: 500; }
        .file-upload-input { display: none; }
        
        /* 标签搜索建议 */
        .tag-suggestions { position: absolute; top: 100%; left: 0; right: 0; background: white; border: 2px solid #e2e8f0; border-top: none; border-radius: 0 0 8px 8px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); display: none; z-index: 100; max-height: 200px; overflow-y: auto; }
        .tag-suggestions.show { display: block; }
        .tag-suggestion-item { padding: 10px 15px; cursor: pointer; display: flex; align-items: center; gap: 10px; transition: background 0.2s; }
        .tag-suggestion-item:hover { background: #f7fafc; }
        .tag-suggestion-item img { width: 24px; height: 24px; border-radius: 50%; }
        .tag-suggestion-item .letter-icon { width: 24px; height: 24px; border-radius: 50%; font-size: 12px; font-weight: bold; color: white; display: flex; align-items: center; justify-content: center; }
        .tag-suggestion-item span { flex: 1; }
        .tag-suggestion-item small { color: #718096; font-size: 12px; }
        
        /* 右键菜单 */
        .context-menu { position: fixed; background: white; border-radius: 8px; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); z-index: 1001; display: none; overflow: hidden; }
        .context-menu-item { padding: 12px 20px; cursor: pointer; transition: background 0.2s; font-size: 14px; color: #4a5568; }
        .context-menu-item:hover { background: #f7fafc; }
        .context-menu-item.delete { color: #e53e3e; }
        .context-menu-item.delete:hover { background: #fed7d7; }
    </style>
</head>
<body>
    <div class="user-area">
        <div id="userAreaContent">
            <button class="login-btn" onclick="showAuthModal()">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                登录
            </button>
        </div>
        <div class="user-popup" id="userPopup">
            <div class="user-popup-header">
                <div class="user-popup-avatar" id="popupAvatar">U</div>
                <div class="user-popup-name" id="popupName">用户名</div>
                <div class="user-popup-email" id="popupEmail">email@example.com</div>
            </div>
            <div class="user-popup-body">
                <div class="user-popup-item" onclick="showAvatarUpload()">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
                    更换头像
                </div>
                <div class="user-popup-item" onclick="syncToCloud()">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
                    同步到云端
                </div>
                <div class="user-popup-item" onclick="syncFromCloud()">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                    从云端同步
                </div>
                <div class="history-container">
                    <div class="user-popup-item" onclick="toggleHistoryDropdown()">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
                        <span id="historyBtnText">历史数据 ▼</span>
                    </div>
                    <div class="history-dropdown" id="historyDropdown"></div>
                </div>
                <div class="user-popup-item" onclick="logout()" style="color: #e53e3e;">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path><polyline points="16 17 21 12 16 7"></polyline><line x1="21" y1="12" x2="9" y2="12"></line></svg>
                    退出登录
                </div>
            </div>
        </div>
    </div>
    
    <!-- 认证弹窗 -->
    <div class="auth-modal" id="authModal">
        <div class="auth-modal-content">
            <button class="auth-modal-close" onclick="hideAuthModal()">&times;</button>
            <div class="auth-modal-title">欢迎回来</div>
            <div class="auth-modal-subtitle">登录以同步您的数据到云端</div>
            <div class="auth-tabs">
                <div class="auth-tab active" onclick="switchAuthTab('login')">登录</div>
                <div class="auth-tab" onclick="switchAuthTab('register')">注册</div>
            </div>
            <form class="auth-form active" id="loginForm" onsubmit="handleLogin(event)">
                <div class="auth-input-group"><label>邮箱</label><input type="email" class="auth-input" id="loginEmail" required></div>
                <div class="auth-input-group"><label>密码</label><input type="password" class="auth-input" id="loginPassword" required></div>
                <button type="submit" class="auth-submit" id="loginSubmit">登录</button>
                <div class="auth-error" id="loginError"></div>
            </form>
            <form class="auth-form" id="registerForm" onsubmit="handleRegister(event)">
                <div class="auth-input-group"><label>用户名</label><input type="text" class="auth-input" id="registerUsername" required></div>
                <div class="auth-input-group"><label>邮箱</label><input type="email" class="auth-input" id="registerEmail" required></div>
                <div class="auth-input-group"><label>密码</label><input type="password" class="auth-input" id="registerPassword" required minlength="6"></div>
                <button type="submit" class="auth-submit" id="registerSubmit">注册</button>
                <div class="auth-error" id="registerError"></div>
            </form>
        </div>
    </div>
    
    <!-- 头像上传弹窗 -->
    <div class="auth-modal" id="avatarModal">
        <div class="auth-modal-content">
            <button class="auth-modal-close" onclick="hideAvatarModal()">&times;</button>
            <div class="auth-modal-title">更换头像</div>
            <div style="text-align: center; margin: 20px 0;">
                <div id="avatarPreviewContainer" style="width: 150px; height: 150px; margin: 0 auto; border-radius: 50%; overflow: hidden; background: #e2e8f0; display: flex; align-items: center; justify-content: center;">
                    <span style="color: #a0aec0;">预览</span>
                </div>
            </div>
            <div class="file-upload-container">
                <label class="file-upload-label" for="avatarFileInput">📷 点击选择图片</label>
                <input type="file" id="avatarFileInput" class="file-upload-input" accept="image/*">
            </div>
            <div class="modal-actions" style="margin-top: 20px;">
                <button class="btn btn-cancel" onclick="hideAvatarModal()">取消</button>
                <button class="btn btn-submit" id="avatarSubmitBtn" onclick="uploadAvatar()" disabled>上传</button>
            </div>
        </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-box">
        <div class="engine-selector">
            <div class="selected-engine" id="selectedEngine" onclick="toggleEngineOptions()">
                <img src="https://www.baidu.com/favicon.ico" class="engine-icon" id="currentEngineIcon">
                <span id="currentEngineName">百度</span>
                <svg class="down-arrow" viewBox="0 0 24 24"><path d="M6 9l6 6 6-6z" fill="currentColor"/></svg>
            </div>
            <div class="engine-options" id="engineOptions">
                <div class="engine-option" onclick="selectEngine('baidu', 'https://www.baidu.com/s?wd=')"><img src="https://www.baidu.com/favicon.ico">百度</div>
                <div class="engine-option" onclick="selectEngine('google', 'https://www.google.com/search?q=')"><img src="https://www.google.com/favicon.ico">Google</div>
                <div class="engine-option" onclick="selectEngine('bing', 'https://www.bing.com/search?q=')"><img src="https://www.bing.com/favicon.ico">必应</div>
            </div>
        </div>
        <input type="text" id="search-input" placeholder="输入搜索内容..." autocomplete="off">
        <button id="search-button" onclick="doSearch()">
            <svg viewBox="0 0 24 24" width="20" height="20"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" fill="currentColor"/></svg>
        </button>
        <div class="suggestion-box" id="suggestionBox"></div>
    </div>

    <!-- 链接容器 -->
    <div class="linkbox">
        <div class="links-container" id="linksContainer"></div>
    </div>

    <!-- 添加链接弹窗 -->
    <div class="modal-overlay" id="addLinkModal">
        <div class="modal-content">
            <div class="modal-header">
                <span class="modal-title">添加链接</span>
                <button class="close-btn" onclick="closeAddLinkModal()">&times;</button>
            </div>
            <form id="addLinkForm" onsubmit="submitAddLink(event)">
                <div class="form-group">
                    <label class="form-label">网站名称</label>
                    <input type="text" class="form-input" id="linkName" required placeholder="例如：百度" autocomplete="off">
                    <div class="tag-suggestions" id="tagSuggestions"></div>
                </div>
                <div class="form-group">
                    <label class="form-label">网站地址</label>
                    <input type="text" class="form-input" id="linkUrl" required placeholder="https://www.baidu.com">
                    <div class="form-hint">请输入完整的URL地址，包含 http:// 或 https://</div>
                </div>
                <div class="form-group">
                    <label class="form-label">图标</label>
                    <div class="icon-preview" id="iconPreview">
                        <div class="letter-icon" id="letterIconPreview" style="background: #667eea;">网</div>
                    </div>
                    <div class="icon-actions">
                        <button type="button" class="icon-action-btn" onclick="fetchWebsiteIcon()">自动获取</button>
                        <button type="button" class="icon-action-btn" onclick="generateLetterIcon()">使用文字</button>
                    </div>
                    <div class="file-upload-container">
                        <label class="file-upload-label" for="iconUpload">📷 上传图标</label>
                        <input type="file" id="iconUpload" class="file-upload-input" accept="image/*">
                    </div>
                </div>
                <div class="modal-actions">
                    <button type="button" class="btn btn-cancel" onclick="closeAddLinkModal()">取消</button>
                    <button type="submit" class="btn btn-submit">添加</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 右键菜单 -->
    <div class="context-menu" id="contextMenu">
        <div class="context-menu-item delete" onclick="deleteSelectedLink()">删除链接</div>
    </div>

    <!-- Sortable.js -->
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
    
    <script>
        // XSS防护
        function escapeHtml(str) {
            if (!str) return '';
            const div = document.createElement('div');
            div.textContent = str;
            return div.innerHTML;
        }
        
        // 配置
        const API_BASE = '<?= $apiBase ?>';
        const originalLinks = <?= $originalLinksJson ?>;
        
        // 状态
        let currentUser = null, authToken = null, dataVersion = 0, isSyncing = false;
        let selectedAvatarData = null, currentIconUrl = '', currentIconType = 'letter';
        let contextMenuTarget = null, historyLoaded = false;
        
        // 颜色生成
        function getColorForChar(char) {
            const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9', '#F8C471', '#82E0AA', '#F1948A', '#D7BDE2'];
            return colors[(char || 'A').charCodeAt(0) % colors.length];
        }
        
        // 链接管理
        function getCustomLinks() { return JSON.parse(localStorage.getItem('customLinks') || '[]'); }
        function saveCustomLinks(links) { localStorage.setItem('customLinks', JSON.stringify(links)); }
        
        function getAllLinks() {
            const custom = getCustomLinks();
            const customUrls = custom.map(l => l.url.replace(/\/$/, '').toLowerCase());
            const filtered = originalLinks.filter(link => !customUrls.includes(link.url.replace(/\/$/, '').toLowerCase()));
            return [...filtered, ...custom];
        }
        
        // 渲染链接
        function renderLinks() {
            const container = document.getElementById('linksContainer');
            const layout = JSON.parse(localStorage.getItem('linkboxLayout') || '[]');
            let links = getAllLinks();
            
            if (layout.length > 0) {
                const sorted = [], remaining = [...links];
                layout.forEach(id => {
                    const idx = remaining.findIndex(l => l.id === id);
                    if (idx !== -1) sorted.push(remaining.splice(idx, 1)[0]);
                });
                links = [...sorted, ...remaining];
            }
            
            container.innerHTML = '';
            
            links.forEach(link => {
                const div = document.createElement('div');
                div.className = 'link-item';
                div.dataset.id = link.id;
                if (link.isFixed) div.dataset.fixed = 'true';
                
                const a = document.createElement('a');
                a.href = link.url;
                a.target = '_blank';
                
                if (link.icon && (link.icon.startsWith('http') || link.icon.startsWith('/') || link.icon.startsWith('data:'))) {
                    const img = document.createElement('img');
                    img.src = link.icon;
                    img.alt = escapeHtml(link.name);
                    img.onerror = function() {
                        const letter = link.name.charAt(0);
                        this.outerHTML = '<div class="letter-icon" style="background:' + getColorForChar(letter) + '">' + escapeHtml(letter) + '</div>';
                    };
                    a.appendChild(img);
                } else {
                    const letterIcon = document.createElement('div');
                    letterIcon.className = 'letter-icon';
                    letterIcon.style.background = getColorForChar(link.name.charAt(0));
                    letterIcon.textContent = link.name.charAt(0);
                    a.appendChild(letterIcon);
                }
                
                const p = document.createElement('p');
                p.textContent = link.name;
                a.appendChild(p);
                
                div.appendChild(a);
                container.appendChild(div);
            });
            
            // 添加按钮
            const addBtn = document.createElement('div');
            addBtn.className = 'add-link-btn';
            addBtn.id = 'addLinkBtn';
            addBtn.onclick = openAddLinkModal;
            addBtn.innerHTML = '<span class="plus-icon">+</span><p>添加链接</p>';
            container.appendChild(addBtn);
            
            initSortable();
        }
        
        // 拖拽排序
        function initSortable() {
            if (typeof Sortable === 'undefined') {
                setTimeout(initSortable, 100);
                return;
            }
            new Sortable(document.getElementById('linksContainer'), {
                animation: 150,
                ghostClass: 'sortable-ghost',
                chosenClass: 'sortable-chosen',
                dragClass: 'sortable-drag',
                filter: '.add-link-btn',
                onEnd: function(evt) {
                    const container = document.getElementById('linksContainer');
                    const addBtn = document.getElementById('addLinkBtn');
                    if (addBtn && addBtn.parentNode === container) {
                        container.appendChild(addBtn);
                    }
                    const layout = Array.from(container.querySelectorAll('.link-item')).map(el => el.dataset.id);
                    localStorage.setItem('linkboxLayout', JSON.stringify(layout));
                    autoSync();
                }
            });
        }
        
        // 右键菜单
        document.addEventListener('contextmenu', function(e) {
            const linkItem = e.target.closest('.link-item');
            if (linkItem && linkItem.dataset.fixed !== 'true') {
                e.preventDefault();
                contextMenuTarget = linkItem.dataset.id;
                const menu = document.getElementById('contextMenu');
                menu.style.display = 'block';
                menu.style.left = e.pageX + 'px';
                menu.style.top = e.pageY + 'px';
            }
        });
        
        document.addEventListener('click', function(e) {
            document.getElementById('contextMenu').style.display = 'none';
            if (!e.target.closest('.user-popup') && !e.target.closest('.user-avatar-btn')) {
                document.getElementById('userPopup').classList.remove('show');
            }
            if (!e.target.closest('.engine-selector')) {
                document.getElementById('engineOptions').style.display = 'none';
            }
            if (!e.target.closest('.search-box')) {
                document.getElementById('suggestionBox').style.display = 'none';
            }
            if (!e.target.closest('.form-group')) {
                document.getElementById('tagSuggestions').classList.remove('show');
            }
        });
        
        function deleteSelectedLink() {
            if (!contextMenuTarget) return;
            const links = getCustomLinks().filter(l => l.id !== contextMenuTarget);
            saveCustomLinks(links);
            const layout = JSON.parse(localStorage.getItem('linkboxLayout') || '[]').filter(id => id !== contextMenuTarget);
            localStorage.setItem('linkboxLayout', JSON.stringify(layout));
            renderLinks();
            autoSync();
        }
        
        // 用户认证
        function restoreAuth() {
            const token = localStorage.getItem('authToken');
            const user = localStorage.getItem('currentUser');
            if (token && user) {
                authToken = token;
                currentUser = JSON.parse(user);
                dataVersion = parseInt(localStorage.getItem('dataVersion') || '0');
                updateUserUI();
                setTimeout(() => smartSync(), 500);
            }
        }
        
        function updateUserUI() {
            const userAreaContent = document.getElementById('userAreaContent');
            if (currentUser) {
                const initial = currentUser.username ? currentUser.username.charAt(0).toUpperCase() : 'U';
                userAreaContent.innerHTML = '<div class="user-avatar-btn" onclick="toggleUserPopup()">' + 
                    (currentUser.avatar ? '<img src="' + escapeHtml(currentUser.avatar) + '">' : escapeHtml(initial)) + '</div>';
                document.getElementById('popupAvatar').innerHTML = currentUser.avatar ? 
                    '<img src="' + escapeHtml(currentUser.avatar) + '">' : escapeHtml(initial);
                document.getElementById('popupName').textContent = currentUser.username || '用户';
                document.getElementById('popupEmail').textContent = currentUser.email || '';
            } else {
                userAreaContent.innerHTML = '<button class="login-btn" onclick="showAuthModal()"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>登录</button>';
            }
        }
        
        function toggleUserPopup() { document.getElementById('userPopup').classList.toggle('show'); }
        function showAuthModal() { document.getElementById('authModal').classList.add('show'); }
        function hideAuthModal() { document.getElementById('authModal').classList.remove('show'); }
        function switchAuthTab(tab) {
            document.querySelectorAll('.auth-tab').forEach((t, i) => t.classList.toggle('active', (tab === 'login' ? i === 0 : i === 1)));
            document.querySelectorAll('.auth-form').forEach((f, i) => f.classList.toggle('active', (tab === 'login' ? i === 0 : i === 1)));
        }
        
        async function handleLogin(e) {
            e.preventDefault();
            const email = document.getElementById('loginEmail').value;
            const password = document.getElementById('loginPassword').value;
            const btn = document.getElementById('loginSubmit');
            const err = document.getElementById('loginError');
            btn.disabled = true; btn.textContent = '登录中...'; err.classList.remove('show');
            try {
                const res = await fetch(API_BASE + '/auth.php?action=login', {
                    method: 'POST', headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({email, password})
                });
                const data = await res.json();
                if (data.code === 0) {
                    authToken = data.data.token;
                    currentUser = data.data.user;
                    localStorage.setItem('authToken', authToken);
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    updateUserUI();
                    hideAuthModal();
                    smartSync();
                } else {
                    err.textContent = data.message || '登录失败';
                    err.classList.add('show');
                }
            } catch (e) {
                err.textContent = '网络错误'; err.classList.add('show');
            }
            btn.disabled = false; btn.textContent = '登录';
        }
        
        async function handleRegister(e) {
            e.preventDefault();
            const username = document.getElementById('registerUsername').value;
            const email = document.getElementById('registerEmail').value;
            const password = document.getElementById('registerPassword').value;
            const btn = document.getElementById('registerSubmit');
            const err = document.getElementById('registerError');
            btn.disabled = true; btn.textContent = '注册中...'; err.classList.remove('show');
            try {
                const res = await fetch(API_BASE + '/auth.php?action=register', {
                    method: 'POST', headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({username, email, password})
                });
                const data = await res.json();
                if (data.code === 0) {
                    authToken = data.data.token;
                    currentUser = data.data.user;
                    localStorage.setItem('authToken', authToken);
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    updateUserUI();
                    hideAuthModal();
                    syncToCloud();
                } else {
                    err.textContent = data.message || '注册失败';
                    err.classList.add('show');
                }
            } catch (e) {
                err.textContent = '网络错误'; err.classList.add('show');
            }
            btn.disabled = false; btn.textContent = '注册';
        }
        
        function logout() {
            authToken = null; currentUser = null; historyLoaded = false;
            localStorage.removeItem('authToken');
            localStorage.removeItem('currentUser');
            localStorage.removeItem('dataVersion');
            updateUserUI();
            document.getElementById('userPopup').classList.remove('show');
            document.getElementById('historyDropdown').classList.remove('show');
            document.getElementById('historyBtnText').textContent = '历史数据 ▼';
        }
        
        // 同步功能（静默）
        async function smartSync() {
            if (!authToken || isSyncing) return;
            isSyncing = true;
            try {
                const localLinks = getCustomLinks();
                const localLayout = JSON.parse(localStorage.getItem('linkboxLayout') || '[]');
                const res = await fetch(API_BASE + '/sync.php?action=smart_sync', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + authToken},
                    body: JSON.stringify({links: localLinks, layout: localLayout, version: dataVersion})
                });
                const data = await res.json();
                if (data.code === 0) {
                    if (data.data.links) saveCustomLinks(data.data.links);
                    if (data.data.layout && data.data.layout.length > 0) {
                        localStorage.setItem('linkboxLayout', JSON.stringify(data.data.layout));
                    }
                    dataVersion = data.data.version;
                    localStorage.setItem('dataVersion', dataVersion);
                    renderLinks();
                }
            } catch (e) {}
            isSyncing = false;
        }
        
        async function syncToCloud() {
            if (!authToken || isSyncing) return;
            isSyncing = true;
            document.getElementById('userPopup').classList.remove('show');
            try {
                const res = await fetch(API_BASE + '/sync.php?action=upload', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + authToken},
                    body: JSON.stringify({
                        links: getCustomLinks(),
                        layout: JSON.parse(localStorage.getItem('linkboxLayout') || '[]')
                    })
                });
                const data = await res.json();
                if (data.code === 0) {
                    dataVersion = data.data.version;
                    localStorage.setItem('dataVersion', dataVersion);
                    if (data.data.links) saveCustomLinks(data.data.links);
                }
            } catch (e) {}
            isSyncing = false;
        }
        
        async function syncFromCloud() {
            if (!authToken || isSyncing) return;
            isSyncing = true;
            document.getElementById('userPopup').classList.remove('show');
            try {
                const res = await fetch(API_BASE + '/sync.php?action=download', {
                    headers: {'Authorization': 'Bearer ' + authToken}
                });
                const data = await res.json();
                if (data.code === 0 && data.data.hasData) {
                    const cloudLinks = data.data.links || [];
                    const localLinks = getCustomLinks();
                    const merged = [...localLinks];
                    const localUrls = localLinks.map(l => l.url.replace(/\/$/, '').toLowerCase());
                    cloudLinks.forEach(link => {
                        if (!localUrls.includes(link.url.replace(/\/$/, '').toLowerCase())) merged.push(link);
                    });
                    saveCustomLinks(merged);
                    if (data.data.layout && data.data.layout.length > 0) {
                        localStorage.setItem('linkboxLayout', JSON.stringify(data.data.layout));
                    }
                    dataVersion = data.data.version;
                    localStorage.setItem('dataVersion', dataVersion);
                    renderLinks();
                }
            } catch (e) {}
            isSyncing = false;
        }
        
        // 历史数据（懒加载）
        async function toggleHistoryDropdown() {
            const dropdown = document.getElementById('historyDropdown');
            const btnText = document.getElementById('historyBtnText');
            
            if (dropdown.classList.contains('show')) {
                dropdown.classList.remove('show');
                btnText.textContent = '历史数据 ▼';
                return;
            }
            
            btnText.textContent = '历史数据 ▲';
            dropdown.classList.add('show');
            
            if (!historyLoaded) {
                dropdown.innerHTML = '<div class="history-loading">加载中...</div>';
                try {
                    const res = await fetch(API_BASE + '/sync.php?action=history', {
                        headers: {'Authorization': 'Bearer ' + authToken}
                    });
                    const data = await res.json();
                    if (data.code === 0 && data.data.history && data.data.history.length > 0) {
                        dropdown.innerHTML = data.data.history.map(h => 
                            '<div class="history-item" onclick="restoreHistory(' + h.id + ')">' +
                            '<div class="history-version">版本 ' + h.version + '</div>' +
                            '<div class="history-date">' + h.created_at + '</div>' +
                            '</div>'
                        ).join('');
                        historyLoaded = true;
                    } else {
                        dropdown.innerHTML = '<div class="history-loading">暂无历史数据</div>';
                    }
                } catch (e) {
                    dropdown.innerHTML = '<div class="history-loading" style="color:#e53e3e;">加载失败</div>';
                }
            }
        }
        
        async function restoreHistory(historyId) {
            if (!confirm('确定要恢复到该版本吗？')) return;
            try {
                const res = await fetch(API_BASE + '/sync.php?action=restore', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + authToken},
                    body: JSON.stringify({history_id: historyId})
                });
                const data = await res.json();
                if (data.code === 0) {
                    saveCustomLinks(data.data.links || []);
                    if (data.data.layout) localStorage.setItem('linkboxLayout', JSON.stringify(data.data.layout));
                    dataVersion = data.data.version;
                    localStorage.setItem('dataVersion', dataVersion);
                    renderLinks();
                    document.getElementById('historyDropdown').classList.remove('show');
                    document.getElementById('historyBtnText').textContent = '历史数据 ▼';
                    historyLoaded = false;
                } else {
                    alert(data.message || '恢复失败');
                }
            } catch (e) {
                alert('网络错误');
            }
        }
        
        let syncTimeout = null;
        function autoSync() {
            if (!authToken) return;
            if (syncTimeout) clearTimeout(syncTimeout);
            syncTimeout = setTimeout(() => syncToCloud(), 2000);
        }
        
        // 头像上传
        function showAvatarUpload() {
            document.getElementById('userPopup').classList.remove('show');
            document.getElementById('avatarModal').classList.add('show');
            selectedAvatarData = null;
            document.getElementById('avatarFileInput').value = '';
            document.getElementById('avatarPreviewContainer').innerHTML = '<span style="color: #a0aec0;">预览</span>';
            document.getElementById('avatarSubmitBtn').disabled = true;
        }
        function hideAvatarModal() { document.getElementById('avatarModal').classList.remove('show'); }
        
        document.getElementById('avatarFileInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;
            if (file.size > 5 * 1024 * 1024) { alert('图片大小不能超过5MB'); return; }
            const reader = new FileReader();
            reader.onload = function(event) {
                const img = new Image();
                img.onload = function() {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    const size = Math.min(img.width, img.height);
                    canvas.width = 200; canvas.height = 200;
                    ctx.drawImage(img, (img.width - size) / 2, (img.height - size) / 2, size, size, 0, 0, 200, 200);
                    selectedAvatarData = canvas.toDataURL('image/jpeg', 0.9);
                    document.getElementById('avatarPreviewContainer').innerHTML = '<img src="' + selectedAvatarData + '" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">';
                    document.getElementById('avatarSubmitBtn').disabled = false;
                };
                img.src = event.target.result;
            };
            reader.readAsDataURL(file);
        });
        
        async function uploadAvatar() {
            if (!selectedAvatarData || !authToken) return;
            const btn = document.getElementById('avatarSubmitBtn');
            btn.disabled = true; btn.textContent = '上传中...';
            try {
                const res = await fetch(API_BASE + '/avatar.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + authToken},
                    body: JSON.stringify({avatar: selectedAvatarData})
                });
                const data = await res.json();
                if (data.code === 0) {
                    currentUser.avatar = data.data.avatar;
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    updateUserUI();
                    hideAvatarModal();
                } else {
                    alert(data.message || '上传失败');
                }
            } catch (e) {
                alert('网络错误');
            }
            btn.disabled = false; btn.textContent = '上传';
        }
        
        // 添加链接
        function openAddLinkModal() {
            document.getElementById('addLinkModal').classList.add('active');
            document.getElementById('addLinkForm').reset();
            currentIconUrl = ''; currentIconType = 'letter';
            updateLetterIconPreview();
        }
        function closeAddLinkModal() { document.getElementById('addLinkModal').classList.remove('active'); }
        
        function updateLetterIconPreview() {
            const name = document.getElementById('linkName').value;
            const char = name.trim() ? name.charAt(0).toUpperCase() : '网';
            const preview = document.getElementById('letterIconPreview');
            if (preview) {
                preview.textContent = char;
                preview.style.background = getColorForChar(char);
            }
            currentIconUrl = ''; currentIconType = 'letter';
        }
        
        function generateLetterIcon() { 
            const char = document.getElementById('linkName').value.charAt(0) || '网';
            document.getElementById('iconPreview').innerHTML = '<div class="letter-icon" id="letterIconPreview" style="background:' + getColorForChar(char) + '">' + char + '</div>';
            currentIconUrl = ''; 
            currentIconType = 'letter'; 
        }
        
        async function fetchWebsiteIcon() {
            const url = document.getElementById('linkUrl').value;
            if (!url) { alert('请先输入网址'); return; }
            try {
                const urlObj = new URL(url.startsWith('http') ? url : 'https://' + url);
                const faviconUrl = 'https://icons.duckduckgo.com/ip3/' + urlObj.hostname + '.ico';
                document.getElementById('iconPreview').innerHTML = '<img src="' + faviconUrl + '" onerror="generateLetterIcon()">';
                currentIconUrl = faviconUrl; currentIconType = 'url';
            } catch (e) { alert('无效的网址'); }
        }
        
        document.getElementById('iconUpload').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;
            if (file.size > 512 * 1024) { alert('图片不能超过512KB'); return; }
            const reader = new FileReader();
            reader.onload = function(event) {
                document.getElementById('iconPreview').innerHTML = '<img src="' + event.target.result + '">';
                currentIconUrl = event.target.result;
                currentIconType = 'base64';
            };
            reader.readAsDataURL(file);
        });
        
        // 标签搜索
        let tagSearchTimeout = null;
        document.getElementById('linkName').addEventListener('input', function() {
            updateLetterIconPreview();
            const query = this.value.trim();
            if (query.length < 1) {
                document.getElementById('tagSuggestions').classList.remove('show');
                return;
            }
            if (tagSearchTimeout) clearTimeout(tagSearchTimeout);
            tagSearchTimeout = setTimeout(() => searchTags(query), 300);
        });
        
        async function searchTags(query) {
            try {
                const res = await fetch(API_BASE + '/tags.php?action=search&keyword=' + encodeURIComponent(query));
                const data = await res.json();
                if (data.code === 0 && data.data && data.data.length > 0) {
                    const suggestions = document.getElementById('tagSuggestions');
                    suggestions.innerHTML = data.data.slice(0, 8).map(tag => {
                        let iconHtml = tag.icon ? 
                            '<img src="' + escapeHtml(tag.icon) + '" onerror="this.style.display=\'none\'">' :
                            '<div class="letter-icon" style="background:' + getColorForChar(tag.name.charAt(0)) + '">' + escapeHtml(tag.name.charAt(0)) + '</div>';
                        return '<div class="tag-suggestion-item" onclick="selectTag(\'' + escapeHtml(tag.name).replace(/'/g, "\\'") + '\',\'' + escapeHtml(tag.url).replace(/'/g, "\\'") + '\',\'' + escapeHtml(tag.icon || '').replace(/'/g, "\\'") + '\')">' +
                            iconHtml + '<span>' + escapeHtml(tag.name) + '</span><small>' + escapeHtml(tag.domain) + '</small></div>';
                    }).join('');
                    suggestions.classList.add('show');
                } else {
                    document.getElementById('tagSuggestions').classList.remove('show');
                }
            } catch (e) {
                document.getElementById('tagSuggestions').classList.remove('show');
            }
        }
        
        function selectTag(name, url, icon) {
            document.getElementById('linkName').value = name;
            document.getElementById('linkUrl').value = url;
            document.getElementById('tagSuggestions').classList.remove('show');
            if (icon) {
                document.getElementById('iconPreview').innerHTML = '<img src="' + icon + '">';
                currentIconUrl = icon;
                currentIconType = 'url';
            } else {
                updateLetterIconPreview();
            }
        }
        
        function submitAddLink(e) {
            e.preventDefault();
            let name = document.getElementById('linkName').value.trim();
            let url = document.getElementById('linkUrl').value.trim();
            if (!name || !url) { alert('请填写完整信息'); return; }
            if (!url.startsWith('http://') && !url.startsWith('https://')) url = 'https://' + url;
            
            const link = { id: 'custom-' + Date.now(), name, url, icon: currentIconUrl, iconType: currentIconType };
            const links = getCustomLinks();
            links.push(link);
            saveCustomLinks(links);
            closeAddLinkModal();
            renderLinks();
            autoSync();
        }
        
        // 搜索功能
        const engines = { baidu: 'https://www.baidu.com/s?wd=', google: 'https://www.google.com/search?q=', bing: 'https://www.bing.com/search?q=' };
        let currentEngine = localStorage.getItem('searchEngine') || 'baidu';
        
        function toggleEngineOptions() {
            document.getElementById('engineOptions').style.display = 
                document.getElementById('engineOptions').style.display === 'block' ? 'none' : 'block';
        }
        
        function selectEngine(engine, url) {
            currentEngine = engine;
            engines[engine] = url;
            localStorage.setItem('searchEngine', engine);
            document.getElementById('currentEngineName').textContent = {baidu: '百度', google: 'Google', bing: '必应'}[engine];
            document.getElementById('currentEngineIcon').src = 'https://www.' + (engine === 'bing' ? 'bing' : engine) + '.com/favicon.ico';
            document.getElementById('engineOptions').style.display = 'none';
        }
        
        function doSearch() {
            const query = document.getElementById('search-input').value.trim();
            if (query) {
                window.open(engines[currentEngine] + encodeURIComponent(query), '_blank');
                document.getElementById('suggestionBox').style.display = 'none';
            }
        }
        
        document.getElementById('search-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') { e.preventDefault(); doSearch(); }
        });
        
        // 搜索建议
        let selectedSuggestionIndex = -1;
        let currentSuggestions = [];
        
        document.getElementById('search-input').addEventListener('input', function() {
            const query = this.value.trim();
            if (!query) { document.getElementById('suggestionBox').style.display = 'none'; return; }
            const oldScript = document.querySelector('script[src*="suggestion.baidu.com"]');
            if (oldScript) oldScript.remove();
            const script = document.createElement('script');
            script.src = 'https://suggestion.baidu.com/su?wd=' + encodeURIComponent(query) + '&cb=handleBaiduSuggestions';
            document.body.appendChild(script);
        });
        
        window.handleBaiduSuggestions = function(data) {
            const box = document.getElementById('suggestionBox');
            if (!data.s || data.s.length === 0) { box.style.display = 'none'; return; }
            currentSuggestions = data.s;
            selectedSuggestionIndex = -1;
            box.innerHTML = data.s.map((s, i) => 
                '<div class="suggestion-item" data-index="' + i + '">' + escapeHtml(s) + '</div>'
            ).join('');
            box.querySelectorAll('.suggestion-item').forEach(item => {
                item.addEventListener('click', function() {
                    document.getElementById('search-input').value = currentSuggestions[this.dataset.index];
                    doSearch();
                });
            });
            box.style.display = 'block';
            const oldScript = document.querySelector('script[src*="suggestion.baidu.com"]');
            if (oldScript) oldScript.remove();
        };
        
        document.getElementById('search-input').addEventListener('keydown', function(e) {
            const box = document.getElementById('suggestionBox');
            if (box.style.display !== 'block') return;
            const items = box.querySelectorAll('.suggestion-item');
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                selectedSuggestionIndex = (selectedSuggestionIndex + 1) % items.length;
                items.forEach((item, i) => item.classList.toggle('active', i === selectedSuggestionIndex));
                if (items[selectedSuggestionIndex]) this.value = currentSuggestions[selectedSuggestionIndex];
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                selectedSuggestionIndex = selectedSuggestionIndex <= 0 ? items.length - 1 : selectedSuggestionIndex - 1;
                items.forEach((item, i) => item.classList.toggle('active', i === selectedSuggestionIndex));
                if (items[selectedSuggestionIndex]) this.value = currentSuggestions[selectedSuggestionIndex];
            } else if (e.key === 'Escape') {
                box.style.display = 'none';
            }
        });
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            restoreAuth();
            renderLinks();
        });
    </script>
</body>
</html>
