// A1Tabs 新标签页主脚本
// 处理新标签页的所有交互和数据展示

document.addEventListener('DOMContentLoaded', async function() {
  console.log('A1Tabs 新标签页加载完成');
  
  // 初始化迁移检查
  await initializeMigrationCheck();
  
  // 初始化应用
  await initializeNewTab();
  
  // 绑定事件监听器
  bindEventListeners();
  
  // 加载数据
  await loadAllData();
  
  // 启动时钟
  startClock();
  
  // 设置主题
  await applyTheme();
});

// 迁移检查和提示
async function initializeMigrationCheck() {
  try {
    // 检查chrome.storage是否存在且可用
    if (!chrome || !chrome.storage || !chrome.storage.local) {
      console.warn('Chrome存储API不可用，跳过迁移检查');
      return;
    }
    
    // 检查是否已标记为迁移
    const migrationStatus = await chrome.storage.local.get(['indexeddb_migrated']);
    
    if (!migrationStatus.indexeddb_migrated) {
      // 创建迁移提示实例
      if (typeof MigrationPrompt !== 'undefined') {
        const migrationPrompt = new MigrationPrompt();
        
        // 延迟显示以确保页面完全加载
        setTimeout(() => {
          migrationPrompt.checkAndShowMigrationPrompt();
        }, 1000);
      } else {
        console.warn('MigrationPrompt 组件未加载');
      }
    }
  } catch (error) {
    console.error('迁移检查失败:', error);
  }
}

// 全局状态管理
const NewTabState = {
  categories: [],
  links: [],
  settings: {
    theme: 'light',
    defaultView: 'grid',
    searchEngine: 'bing',
    wallpaper: '2.webp'
  },
  currentCategory: '',
  searchQuery: '',
  viewMode: 'grid',
  isLoading: false
};

// 初始化新标签页
async function initializeNewTab() {
  // 检查是否首次使用
  const hasData = await checkExistingData();
  if (!hasData) {
    await createWelcomeData();
  }
  
  // 初始化组件
  Modal.init();
  
  // 检查是否需要显示用户须知
  await checkAndShowWelcomeNotice();
  
  // 设置焦点到搜索框
  document.getElementById('mainSearch').focus();
  
  // 更新搜索框提示信息
  updateSearchPlaceholder();
}

// 检查是否有现有数据
async function checkExistingData() {
  const data = await StorageManager.getAllData();
  return data.links && data.links.length > 0;
}

// 检查并显示用户须知（首次使用）
async function checkAndShowWelcomeNotice() {
  try {
    // 获取用户设置
    const settings = await StorageManager.getSettings();
    
    // 检查用户是否已经看过须知
    if (!settings.hasSeenWelcomeNotice) {
      console.log('首次使用，显示用户须知');
      
      // 延迟显示以确保页面完全加载
      setTimeout(() => {
        Modal.showWelcomeNoticeModal();
      }, 1500); // 稍微延迟一些，让用户先看到页面加载完成
    } else {
      console.log('用户已查看过须知，跳过显示');
    }
  } catch (error) {
    console.error('检查用户须知状态失败:', error);
  }
}

// 创建欢迎数据
async function createWelcomeData() {
  try {
    // 首先创建默认分类
    const defaultCategories = [
      {
        name: '工具',
        icon: '🔧',
        color: '#4285f4',
        description: '实用工具链接'
      },
      {
        name: '工作',
        icon: '💼',
        color: '#34a853',
        description: '工作相关链接'
      }
    ];
    
    const categoryMap = new Map();
    
    // 创建分类并保存ID映射
    for (const categoryData of defaultCategories) {
      try {
        const newCategory = await StorageManager.addCategory(categoryData);
        categoryMap.set(categoryData.name, newCategory.id);
        console.log('创建默认分类:', categoryData.name, newCategory.id);
      } catch (error) {
        console.warn('创建分类失败，可能已存在:', categoryData.name, error);
        // 如果创建失败，可能是分类已存在，尝试从现有分类中查找
        const existingCategories = await StorageManager.getCategories();
        const existingCategory = existingCategories.find(cat => cat.name === categoryData.name);
        if (existingCategory) {
          categoryMap.set(categoryData.name, existingCategory.id);
        }
      }
    }
    
    // 创建欢迎链接
    const welcomeLinks = [
      {
        title: '海豚星空投屏',
        url: 'https://dolphinstar.cn/',
        logo: 'Dps',
        categoryId: categoryMap.get('工具') || '',
        note: '欢迎使用A1Tabs',
        isQuickAccess: true
      },
      {
        title: 'GitHub',
        url: 'https://github.com',
        logo: 'Gh',
        categoryId: categoryMap.get('工作') || '',
        note: '全球最大的代码托管平台',
        isQuickAccess: true
      }
    ];
    
    // 使用IndexedDB的addLink方法逐个添加
    for (const linkData of welcomeLinks) {
      try {
        await StorageManager.addLink(linkData);
        console.log('成功添加欢迎链接:', linkData.title);
      } catch (error) {
        if (error.name === 'DuplicateUrlError') {
          console.log('跳过重复的欢迎链接:', linkData.title);
        } else {
          console.error('添加欢迎链接失败:', linkData.title, error);
        }
      }
    }
    
    console.log('欢迎数据创建完成');
    
  } catch (error) {
    console.error('创建欢迎数据失败:', error);
  }
}

// 绑定事件监听器
function bindEventListeners() {
  // 主搜索框
  const mainSearch = document.getElementById('mainSearch');
  mainSearch.addEventListener('input', handleMainSearch);
  mainSearch.addEventListener('keydown', handleSearchKeydown);
  
  // 搜索按钮
  document.getElementById('searchBtn').addEventListener('click', handleWebSearch);
  
  // 头部按钮
  document.getElementById('addLinkBtn').addEventListener('click', () => Modal.showAddLinkModal());
  document.getElementById('settingsBtn').addEventListener('click', () => Modal.showSettingsModal());
  document.getElementById('themeToggle').addEventListener('click', toggleTheme);
  
  // Logo容器点击事件
  const logoContainer = document.getElementById('logoContainer');
  if (logoContainer) {
    logoContainer.addEventListener('click', () => {
      window.open('https://dolphinstar.cn/', '_blank');
    });
  }

  // 移动端导航切换（抽屉）
  const navToggle = document.getElementById('navToggleBtn');
  if (navToggle) {
    navToggle.addEventListener('click', () => toggleSidebar());
  }

  const drawerBackdrop = document.getElementById('drawerBackdrop');
  if (drawerBackdrop) {
    drawerBackdrop.addEventListener('click', () => closeSidebar());
  }

  // 悬浮按钮点击打开侧边栏
  const sidebarFloat = document.getElementById('sidebarFloatBtn');
  if (sidebarFloat) {
    sidebarFloat.addEventListener('click', () => toggleSidebar(true));
  }

  // 窗口尺寸变化时更新悬浮按钮显示和lifeStatsContainer显示（移动端行为）
  window.addEventListener('resize', () => {
    updateSidebarFloatVisibility();
    
    // 根据屏幕宽度控制lifeStatsContainer显示
    const lifeStatsContainer = document.getElementById('lifeStatsContainer');
    if (lifeStatsContainer) {
      if (window.matchMedia('(max-width: 768px)').matches) {
        // 在小于等于768px时，如果侧边栏关闭则显示lifeStatsContainer
        const sidebar = document.querySelector('.sidebar');
        if (sidebar && !sidebar.classList.contains('open')) {
          lifeStatsContainer.style.display = 'block';
        }
      }
    }
  });
  // 初始状态
  updateSidebarFloatVisibility();
  
  // 初始化时也根据屏幕宽度控制lifeStatsContainer显示
  setTimeout(() => {
    const lifeStatsContainer = document.getElementById('lifeStatsContainer');
    if (lifeStatsContainer) {
      if (window.matchMedia('(max-width: 768px)').matches) {
        // 在小于等于768px时，如果侧边栏关闭则显示lifeStatsContainer
        const sidebar = document.querySelector('.sidebar');
        if (sidebar && !sidebar.classList.contains('open')) {
          lifeStatsContainer.style.display = 'block';
        }
      }
    }
  }, 100);
  
  // 分类相关
  document.getElementById('addCategoryBtn').addEventListener('click', () => Modal.showAddCategoryModal());
  document.getElementById('manageCategoryBtn').addEventListener('click', () => Modal.showManageCategoryModal());
  
  // 空状态按钮
  document.getElementById('emptyStateAddBtn').addEventListener('click', () => Modal.showAddLinkModal());
  
  // 取消按钮
  document.getElementById('cancelAddCategory').addEventListener('click', () => Modal.closeAll());
  
  // 视图控制
  document.getElementById('gridViewBtn').addEventListener('click', () => setViewMode('grid'));
  document.getElementById('listViewBtn').addEventListener('click', () => setViewMode('list'));
  document.getElementById('sortSelect').addEventListener('change', handleSortChange);
  
  // 表单提交
  document.getElementById('addLinkForm').addEventListener('submit', handleAddLink);
  
  // 设置相关
  bindSettingsEvents();
  
  // 移除了模态框点击背景关闭功能
  
  // 键盘快捷键
  document.addEventListener('keydown', handleKeyboardShortcuts);
  
  // 监听链接删除事件
  document.addEventListener('linkDeleted', handleLinkDeleted);
  
  // 监听链接更新事件
  document.addEventListener('linkUpdated', handleLinkUpdated);
  
  // 监听书签导入事件
  document.addEventListener('bookmarksImported', handleBookmarksImported);
  
  // 监听用户须知确认事件
  document.addEventListener('welcomeNoticeConfirmed', handleWelcomeNoticeConfirmed);
}

// 处理主搜索
function handleMainSearch() {
  const query = document.getElementById('mainSearch').value.trim();
  NewTabState.searchQuery = query;
  
  // 延迟搜索以提高性能
  clearTimeout(window.searchTimeout);
  window.searchTimeout = setTimeout(() => {
    filterAndRenderLinks();
  }, 300);
}

// 处理搜索框键盘事件
function handleSearchKeydown(event) {
  if (event.key === 'Enter') {
    const query = event.target.value.trim();
    if (query) {
      // 如果是URL，直接添加为链接
      if (isValidURL(query)) {
        addQuickLink(query);
      } else {
        // 否则进行网络搜索
        handleWebSearch();
      }
    }
  }
}

// 更新搜索框提示信息
function updateSearchPlaceholder() {
  const searchEngine = NewTabState.settings.searchEngine || 'bing';
  const searchEngineNames = {
    google: 'Google',
    bing: 'Bing',
    baidu: '百度',
    duckduckgo: 'DuckDuckGo',
    yahoo: 'Yahoo',
    sogou: '搜狗',
    so360: '360搜索',
    yandex: 'Yandex'
  };
  
  const engineName = searchEngineNames[searchEngine] || 'Bing';
  const placeholder = `搜索链接、添加新链接或使用 ${engineName} 搜索网络...`;
  
  document.getElementById('mainSearch').placeholder = placeholder;
}

// 处理网络搜索
function handleWebSearch() {
  const query = document.getElementById('mainSearch').value.trim();
  if (!query) return;
  
  const searchEngines = {
    google: `https://www.google.com/search?q=${encodeURIComponent(query)}`,
    bing: `https://www.bing.com/search?q=${encodeURIComponent(query)}`,
    baidu: `https://www.baidu.com/s?wd=${encodeURIComponent(query)}`,
    duckduckgo: `https://duckduckgo.com/?q=${encodeURIComponent(query)}`,
    yahoo: `https://search.yahoo.com/search?p=${encodeURIComponent(query)}`,
    sogou: `https://www.sogou.com/web?query=${encodeURIComponent(query)}`,
    so360: `https://www.so.com/s?q=${encodeURIComponent(query)}`,
    yandex: `https://yandex.com/search/?text=${encodeURIComponent(query)}`
  };
  
  const searchEngine = NewTabState.settings.searchEngine || 'bing';
  const searchUrl = searchEngines[searchEngine];
  
  // 在新标签页打开搜索结果
  window.open(searchUrl, '_blank');
}

// 快速添加链接
async function addQuickLink(url) {
  try {
    // 尝试获取页面标题
    const title = await fetchPageTitle(url) || extractDomain(url);
    
    const newLink = {
      id: generateId(),
      title: title,
      url: url,
      logo: generateLogoFromTitle(title),
      categoryId: '',
      createTime: new Date().toISOString(),
      visitCount: 0,
      isQuickAccess: false
    };
    
    // 使用IndexedDB的addLink方法
    await StorageManager.addLink(newLink);
    
    // 更新本地状态
    NewTabState.links.push(newLink);
    
    // 清空搜索框
    document.getElementById('mainSearch').value = '';
    NewTabState.searchQuery = '';
    
    // 重新渲染
    renderLinks();
    
    showNotification('链接添加成功！', 'success');
    
  } catch (error) {
    // 检查是否是重复链接错误
    if (error.name === 'DuplicateUrlError') {
      showNotification(`链接已存在：${error.existingLink.title}`, 'warning');
      return;
    }
    
    console.error('添加链接失败:', error);
    showNotification('添加链接失败', 'error');
  }
}

// 获取页面标题（简化版）
async function fetchPageTitle(url) {
  try {
    // 由于跨域限制，这里只是返回域名
    return extractDomain(url);
  } catch (error) {
    return null;
  }
}

// 切换主题
async function toggleTheme() {
  const currentTheme = NewTabState.settings.theme;
  const newTheme = currentTheme === 'light' ? 'dark' : 'light';
  
  NewTabState.settings.theme = newTheme;
  await StorageManager.updateSettings({ theme: newTheme });
  
  applyTheme();
}

// 应用主题
async function applyTheme() {
  const settings = await StorageManager.getSettings();
  const theme = settings.theme || 'light';
  
  document.body.setAttribute('data-theme', theme);
  
  // 更新主题切换按钮图标
  const themeBtn = document.getElementById('themeToggle');
  const icon = themeBtn.querySelector('.icon path');
  if (theme === 'dark') {
    icon.setAttribute('d', 'M12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9M12,2L14.39,5.42C13.65,5.15 12.84,5 12,5C11.16,5 10.35,5.15 9.61,5.42L12,2M3.34,7L7.5,6.65C6.9,7.16 6.36,7.78 5.94,8.5C5.52,9.22 5.25,10 5.11,10.79L3.34,7M3.36,17L5.12,13.21C5.26,14 5.53,14.78 5.95,15.5C6.37,16.22 6.91,16.84 7.51,17.35L3.36,17M20.65,7L18.88,10.79C18.74,10 18.47,9.22 18.05,8.5C17.63,7.78 17.1,7.15 16.5,6.65L20.65,7M20.64,17L16.49,17.35C17.09,16.84 17.62,16.22 18.04,15.5C18.46,14.78 18.73,14 18.87,13.21L20.64,17Z');
  } else {
    icon.setAttribute('d', 'M12,18C11.11,18 10.26,17.8 9.5,17.45C11.56,16.5 13,14.42 13,12C13,9.58 11.56,7.5 9.5,6.55C10.26,6.2 11.11,6 12,6A6,6 0 0,1 18,12A6,6 0 0,1 12,18M20,8.69V4H15.31L12,0.69L8.69,4H4V8.69L0.69,12L4,15.31V20H8.69L12,23.31L15.31,20H20V15.31L23.31,12L20,8.69Z');
  }
  
  // 应用背景设置
  await applyBackgroundSettings();
}

// 应用背景设置
async function applyBackgroundSettings() {
  const settings = await StorageManager.getSettings();
  const wallpaper = settings.wallpaper || '2.webp';
  
  // 应用壁纸设置
  if (wallpaper && wallpaper !== 'default') {
    setBackgroundImage(wallpaper);
  } else {
    // 对于默认壁纸，移除壁纸背景
    removeWallpaperBackground();
  }
}

// 设置视图模式
function setViewMode(mode) {
  NewTabState.viewMode = mode;
  
  // 更新按钮状态
  document.querySelectorAll('.view-btn').forEach(btn => btn.classList.remove('active'));
  document.getElementById(mode + 'ViewBtn').classList.add('active');
  
  // 更新容器类名
  const linksGrid = document.getElementById('linksGrid');
  linksGrid.className = mode === 'list' ? 'links-list' : 'links-grid';
  
  // 保存设置
  StorageManager.updateSettings({ defaultView: mode });
}

// 壁纸功能相关函数
function setBackgroundImage(wallpaper) {
  // 如果壁纸设置为默认，则移除壁纸背景
  if (!wallpaper || wallpaper === 'default') {
    removeWallpaperBackground();
    return;
  }
  
  // 创建或获取壁纸背景元素
  let wallpaperBg = document.getElementById('wallpaperBackground');
  if (!wallpaperBg) {
    wallpaperBg = document.createElement('div');
    wallpaperBg.id = 'wallpaperBackground';
    wallpaperBg.className = 'wallpaper-background';
    document.body.appendChild(wallpaperBg);
  }
  
  // 设置壁纸路径
  const wallpaperPath = `/src/imgs/wallpaper/${wallpaper}`;
  wallpaperBg.style.backgroundImage = `url('${wallpaperPath}')`;
  
  // 预加载壁纸以确保快速显示
  const img = new Image();
  img.onload = () => {
    wallpaperBg.style.backgroundImage = `url('${wallpaperPath}')`;
  };
  img.onerror = () => {
    console.warn(`壁纸加载失败: ${wallpaperPath}`);
    // 如果加载失败，尝试移除壁纸背景
    removeWallpaperBackground();
  };
  img.src = wallpaperPath;
  
  // 添加激活类以显示壁纸
  setTimeout(() => {
    wallpaperBg.classList.add('active');
  }, 10);
}

function removeWallpaperBackground() {
  const wallpaperBg = document.getElementById('wallpaperBackground');
  if (wallpaperBg) {
    wallpaperBg.classList.remove('active');
    // 延迟移除元素以允许过渡效果完成
    setTimeout(() => {
      if (wallpaperBg.parentNode) {
        wallpaperBg.parentNode.removeChild(wallpaperBg);
      }
    }, 500);
  }
}



// 处理排序变化
function handleSortChange() {
  const sortBy = document.getElementById('sortSelect').value;
  NewTabState.sortBy = sortBy;
  
  // 保存排序选项到设置
  StorageManager.updateSettings({ sortBy: sortBy });
  
  renderLinks();
}

// 绑定设置事件
function bindSettingsEvents() {
  // 设置标签切换
  document.querySelectorAll('.settings-tab').forEach(tab => {
    tab.addEventListener('click', (e) => {
      const tabName = e.target.dataset.tab;
      switchSettingsTab(tabName);
    });
  });
  
  // 设置项变化
  document.getElementById('defaultView').addEventListener('change', (e) => {
    setViewMode(e.target.value);
  });
  
  document.getElementById('themeSelect').addEventListener('change', async (e) => {
    NewTabState.settings.theme = e.target.value;
    await StorageManager.updateSettings({ theme: e.target.value });
    applyTheme();
  });
  
  document.getElementById('searchEngine').addEventListener('change', async (e) => {
    NewTabState.settings.searchEngine = e.target.value;
    await StorageManager.updateSettings({ searchEngine: e.target.value });
    updateSearchPlaceholder(); // 更新搜索框提示信息
  });
  
  // 壁纸选择
  document.querySelectorAll('input[name="wallpaper"]').forEach(radio => {
    radio.addEventListener('change', async (e) => {
      if (e.target.checked) {
        const wallpaper = e.target.value;
        NewTabState.settings.wallpaper = wallpaper;
        await StorageManager.updateSettings({ wallpaper: wallpaper });
        // 延迟一点应用壁纸，确保DOM更新完成
        setTimeout(() => {
          setBackgroundImage(wallpaper);
        }, 50);
      }
    });
  });
  
  // 数据操作
  document.getElementById('exportData').addEventListener('click', exportData);
  document.getElementById('importData').addEventListener('click', () => {
    document.getElementById('importFile').click();
  });
  document.getElementById('importFile').addEventListener('change', importData);
  document.getElementById('clearAllData').addEventListener('click', clearAllData);
}

// 切换设置标签
function switchSettingsTab(tabName) {
  // 更新标签状态
  document.querySelectorAll('.settings-tab').forEach(tab => {
    tab.classList.toggle('active', tab.dataset.tab === tabName);
  });
  
  // 更新面板显示
  document.querySelectorAll('.settings-panel').forEach(panel => {
    panel.classList.toggle('active', panel.id === tabName + 'Settings');
  });
}

// 加载所有数据
async function loadAllData() {
  try {
    NewTabState.isLoading = true;
    showLoadingState();
    
    const [categories, links, settings] = await Promise.all([
      StorageManager.getCategories(),
      StorageManager.getLinks(),
      StorageManager.getSettings()
    ]);
    
    NewTabState.categories = categories;
    NewTabState.links = links;
    NewTabState.settings = { ...NewTabState.settings, ...settings };
    
    // 设置视图模式
    setViewMode(settings.defaultView || 'grid');
    
    // 设置排序选项（如果存在）
    if (settings.sortBy) {
      NewTabState.sortBy = settings.sortBy;
      // 更新排序下拉框的值
      const sortSelect = document.getElementById('sortSelect');
      if (sortSelect) {
        sortSelect.value = settings.sortBy;
      }
    }
    
    // 更新搜索框提示信息
    updateSearchPlaceholder();
    
    // 渲染界面
    renderCategories();
    renderQuickAccess();
    renderLinks();
    
    // 应用背景设置
    applyBackgroundSettings();
    
    NewTabState.isLoading = false;
    hideLoadingState();
    
  } catch (error) {
    console.error('加载数据失败:', error);
    showErrorState('加载数据失败，请刷新页面重试');
  }
}

// 渲染分类
function renderCategories() {
  const container = document.getElementById('categoriesContainer');
  container.innerHTML = '';
  
  // 全部分类
  const allTab = CategoryTab.create({
    id: '',
    name: '全部',
    color: '#666',
    isActive: NewTabState.currentCategory === ''
  });
  allTab.addEventListener('click', () => setActiveCategory(''));
  container.appendChild(allTab);
  
  // 其他分类
  NewTabState.categories.forEach(category => {
    const tab = CategoryTab.create({
      ...category,
      isActive: NewTabState.currentCategory === category.id
    });
    tab.addEventListener('click', () => setActiveCategory(category.id));
    container.appendChild(tab);
  });
  
  // 为分类容器添加鼠标滚轮支持
  addWheelScrollSupport(container);
}

// 渲染常用链接
function renderQuickAccess() {
  const container = document.getElementById('quickLinksGrid');
  const quickLinks = NewTabState.links
    .filter(link => link.isQuickAccess)
    .slice(0, 12); // 最多显示12个，支持横向滚动
  
  container.innerHTML = '';
  
  if (quickLinks.length === 0) {
    document.getElementById('quickAccess').style.display = 'none';
    return;
  }
  
  document.getElementById('quickAccess').style.display = 'block';
  
  quickLinks.forEach(link => {
    const card = createQuickLinkCard(link);
    container.appendChild(card);
  });
  
  // 添加鼠标滚轮支持
  addWheelScrollSupport(container);
}

// 创建快速链接卡片
function createQuickLinkCard(linkData) {
  const card = document.createElement('div');
  card.className = 'quick-link-card';
  card.innerHTML = `
    <div class="quick-link-logo" style="background-color: ${getCategoryColor(linkData.categoryId)}">
      ${linkData.logo || '?'}
    </div>
    <div class="quick-link-title">${TextUtils.truncate(linkData.title, 20)}</div>
  `;
  
  card.addEventListener('click', () => {
    openLink(linkData.url, linkData.id);
  });
  
  return card;
}

// 添加鼠标滚轮支持函数
function addWheelScrollSupport(container) {
  // 移除之前的事件监听器（避免重复绑定）
  container.removeEventListener('wheel', handleWheelScroll);
  
  // 添加新的事件监听器
  container.addEventListener('wheel', handleWheelScroll, { passive: false });
}

// 处理鼠标滚轮事件
function handleWheelScroll(event) {
  // 阻止默认的垂直滚动
  event.preventDefault();
  
  // 将垂直滚动转换为水平滚动
  const scrollAmount = event.deltaY;
  event.currentTarget.scrollLeft += scrollAmount;
}

// 获取分类颜色
function getCategoryColor(categoryId) {
  const category = NewTabState.categories.find(cat => cat.id === categoryId);
  return category ? category.color : '#4285f4';
}

// 渲染链接
function renderLinks() {
  const container = document.getElementById('linksGrid');
  const emptyState = document.getElementById('emptyState');
  
  let filteredLinks = filterLinks();
  filteredLinks = sortLinks(filteredLinks);
  
  container.innerHTML = '';
  
  if (filteredLinks.length === 0) {
    emptyState.style.display = 'flex';
    container.style.display = 'none';
    updateSectionTitle(0);
  } else {
    emptyState.style.display = 'none';
    container.style.display = NewTabState.viewMode === 'list' ? 'block' : 'grid';
    updateSectionTitle(filteredLinks.length);
    
    filteredLinks.forEach(link => {
      const category = NewTabState.categories.find(cat => cat.id === link.categoryId);
      const card = LinkCard.create({
        ...link,
        // 修复时间字段名不匹配问题：将createdAt映射为createTime
        createTime: link.createdAt || link.createTime,
        categoryName: category ? category.name : '未分类',
        categoryColor: category ? category.color : '#ccc'
      });
      container.appendChild(card);
    });
  }
}

// 过滤链接
function filterLinks() {
  let links = [...NewTabState.links];
  
  // 按分类过滤
  if (NewTabState.currentCategory) {
    links = links.filter(link => link.categoryId === NewTabState.currentCategory);
  }
  
  // 按搜索词过滤
  if (NewTabState.searchQuery) {
    const query = NewTabState.searchQuery.toLowerCase();
    links = links.filter(link => 
      link.title.toLowerCase().includes(query) ||
      link.url.toLowerCase().includes(query) ||
      (link.note && link.note.toLowerCase().includes(query))
    );
  }
  
  return links;
}

// 排序链接
function sortLinks(links) {
  const sortBy = NewTabState.sortBy || 'recent';
  
  switch (sortBy) {
    case 'visit':
      return links.sort((a, b) => (b.visitCount || 0) - (a.visitCount || 0));
    case 'alpha':
      return links.sort((a, b) => a.title.localeCompare(b.title));
    case 'category':
      return links.sort((a, b) => {
        const catA = NewTabState.categories.find(cat => cat.id === a.categoryId);
        const catB = NewTabState.categories.find(cat => cat.id === b.categoryId);
        const nameA = catA ? catA.name : '未分类';
        const nameB = catB ? catB.name : '未分类';
        return nameA.localeCompare(nameB);
      });
    default: // recent
      return links.sort((a, b) => {
        // 修复时间字段名不匹配问题：兼容两种字段名
        const timeA = new Date(a.createdAt || a.createTime);
        const timeB = new Date(b.createdAt || b.createTime);
        return timeB - timeA;
      });
  }
}

// 更新分区标题
function updateSectionTitle(count) {
  const title = document.getElementById('sectionTitle');
  const categoryName = NewTabState.currentCategory ? 
    NewTabState.categories.find(cat => cat.id === NewTabState.currentCategory)?.name : '所有链接';
  
  title.textContent = `${categoryName || '所有链接'} (${count})`;
}

// 设置活动分类
function setActiveCategory(categoryId) {
  NewTabState.currentCategory = categoryId;
  renderCategories();
  renderLinks();
  
  // 滚动到链接区域顶部
  scrollToLinksSection();
}

// 滚动到链接区域顶部
function scrollToLinksSection() {
  // 等待DOM更新完成后再执行滚动
  setTimeout(() => {
    const linksSection = document.querySelector('.links-section');
    if (linksSection) {
      // 获取链接区域相对于视口的位置
      const rect = linksSection.getBoundingClientRect();
      const isVisible = (
        rect.top >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight)
      );
      
      // 只有当链接区域不在视口内时才滚动
      if (!isVisible) {
        linksSection.scrollIntoView({ 
          behavior: 'smooth',
          block: 'start'
        });
      } else {
        // 如果已经在视口中，只需确保它在顶部附近
        linksSection.scrollIntoView({ 
          behavior: 'smooth',
          block: 'nearest'
        });
      }
    }
  }, 100); // 短暂延迟确保DOM已更新
}

// 过滤并渲染链接（搜索时使用）
function filterAndRenderLinks() {
  renderLinks();
}

// 打开链接
async function openLink(url, linkId) {
  try {
    // 在新标签页打开链接
    window.open(url, '_blank');
    
    // 更新访问计数
    if (linkId) {
      await updateVisitCount(linkId);
    }
  } catch (error) {
    console.error('打开链接失败:', error);
  }
}

// 更新访问计数
async function updateVisitCount(linkId) {
  try {
    // 使用IndexedDB的recordVisit方法
    await StorageManager.recordVisit(linkId);
    
    // 更新本地状态
    const linkIndex = NewTabState.links.findIndex(link => link.id === linkId);
    if (linkIndex !== -1) {
      NewTabState.links[linkIndex].visitCount = (NewTabState.links[linkIndex].visitCount || 0) + 1;
      NewTabState.links[linkIndex].lastVisit = new Date().toISOString();
    }
  } catch (error) {
    console.error('更新访问计数失败:', error);
  }
}

// 启动时钟
function startClock() {
  async function updateTimeAsync() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit'
    });
    const dateString = now.toLocaleDateString('zh-CN', {
      month: 'long',
      day: 'numeric',
      weekday: 'long'
    });
    
    // 获取当前日期并格式化为 MM/dd 格式
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const monthDay = `${month}/${day}`;
    
    // 获取星期几
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const weekday = weekdays[now.getDay()];
    
    // 更新时间显示 - 月/日、时间、星期三行显示
    document.getElementById('timeDisplay').innerHTML = `
      <div class="year-month-date">${monthDay}</div>
      <div class="time">${timeString}</div>
      <div class="weekday">${weekday}</div>
    `;
    
    // 获取个人信息并更新生命统计数据
    const settings = await StorageManager.getSettings();
    const birthDate = settings.birthDate;
    const nickname = settings.nickname || '用户';
    
    // 获取或创建生命统计数据容器
    let lifeStatsContainer = document.getElementById('lifeStatsContainer');
    if (!lifeStatsContainer) {
      // 创建生命统计数据容器并插入到timeDisplay之后
      const headerRight = document.querySelector('.header-right');
      lifeStatsContainer = document.createElement('div');
      lifeStatsContainer.id = 'lifeStatsContainer';
      lifeStatsContainer.className = 'life-stats-container';
      // 将生命统计数据容器插入到timeDisplay之后，但在header-actions之前
      const timeDisplay = document.getElementById('timeDisplay');
      const headerActions = document.querySelector('.header-actions');
      if (timeDisplay && headerActions) {
        timeDisplay.parentNode.insertBefore(lifeStatsContainer, headerActions);
      } else {
        // 如果没找到对应元素，添加到headerRight末尾
        headerRight.appendChild(lifeStatsContainer);
      }
    }
    
    if (birthDate) {
      const today = new Date();
      const birth = new Date(birthDate);
      const diffTime = Math.abs(today - birth);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      // 计算剩余天数（假设平均寿命79岁）
      const expectedYears = 79;
      const expectedEndDate = new Date(birth.getFullYear() + expectedYears, birth.getMonth(), birth.getDate());
      const remainingTime = expectedEndDate - today;
      const remainingDays = Math.ceil(remainingTime / (1000 * 60 * 60 * 24));
      
      // 获取个人信息以计算退休年龄
      const settings = await StorageManager.getSettings();
      const gender = settings.gender || '';
      const identity = settings.identity || '';
      
      // 根据性别和身份计算退休日期（基于中国弹性退休政策）
      // 默认男性60岁退休，女性工人50岁、干部55岁退休
      let retirementAge = 60; // 默认男性退休年龄
      
      // 根据性别和身份调整退休年龄
      if (gender === '女') {
        if (identity === '工人') {
          retirementAge = 50;
        } else if (identity === '干部' || identity === '男职工') {
          retirementAge = 55;
        }
      }
      
      const retirementDate = new Date(birth.getFullYear() + retirementAge, birth.getMonth(), birth.getDate());
      const retirementTime = retirementDate - today;
      const daysToRetirement = Math.ceil(retirementTime / (1000 * 60 * 60 * 24));
      
      lifeStatsContainer.innerHTML = `
        <div class="life-stats">
          <div class="life-stats-row single-row">
            <div class="life-stat-item successfully-lived">
              <div class="stat-label">成功存活</div>
              <div class="stat-value">${diffDays}<span class="stat-unit">天</span></div>
              <div class="stat-comment">恭喜恭喜</div>
            </div>
            <div class="life-stat-item expected-remaining">
              ${remainingDays > 0 ? 
                `<div class="stat-label">预计剩余</div><div class="stat-value">${remainingDays}<span class="stat-unit">天</span></div><div class="stat-comment">参考2024年人均寿命</div>` : 
                `<div class="stat-label">成功多活</div><div class="stat-value">${Math.abs(remainingDays)}<span class="stat-unit">天</span></div><div class="stat-comment">参考2024年人均寿命</div>`
              }
            </div>
            <div class="life-stat-item retirement-distance">
              <div class="stat-label">${daysToRetirement >= 0 ? '距离退休' : '成功退休'}</div>
              <div class="stat-value">${Math.abs(daysToRetirement)}<span class="stat-unit">天</span></div>
              <div class="stat-comment">${daysToRetirement >= 0 ? '加油坚持' : '已退休'}</div>
            </div> 
          </div>
        </div>
      `;
    } else {
      // 如果没有生日信息，显示默认值为0的生命统计数据
      lifeStatsContainer.innerHTML = `
        <div class="life-stats">
          <div class="life-stats-row single-row">
            <div class="life-stat-item successfully-lived">
              <div class="stat-label">成功存活</div>
              <div class="stat-value">0<span class="stat-unit">天</span></div>
              <div class="stat-comment">请设置生日</div>
            </div>
            <div class="life-stat-item expected-remaining">
              <div class="stat-label">预计剩余</div>
              <div class="stat-value">0<span class="stat-unit">天</span></div>
              <div class="stat-comment">请设置生日</div>
            </div>
            <div class="life-stat-item retirement-distance">
              <div class="stat-label">距离退休</div>
              <div class="stat-value">0<span class="stat-unit">天</span></div>
              <div class="stat-comment">请设置生日</div>
            </div> 
          </div>
        </div>
      `;
    }
  }
  
  // 首次调用
  updateTimeAsync();
  
  // 每秒更新时间
  setInterval(() => {
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit'
    });
    
    // 只更新时间部分，保持年月日和星期不变
    const timeElement = document.querySelector('#timeDisplay .time');
    if (timeElement) {
      timeElement.textContent = timeString;
    }
  }, 1000);

  // 每分钟更新一次个人信息统计
  // setInterval(updateTimeAsync, 60000); // 注释掉此行以取消定时器

  // 检查是否需要更新日期和星期（每天第一次执行时）
  let lastCheckDate = new Date().getDate();
  setInterval(() => {
    const now = new Date();
    const currentDate = now.getDate();
    
    if (currentDate !== lastCheckDate) {
      // 日期发生了变化，需要更新年月日和星期
      lastCheckDate = currentDate;
      
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const date = String(now.getDate()).padStart(2, '0');
      
      // 获取星期几
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      const weekday = weekdays[now.getDay()];
      
      // 更新月/日和完整日期显示
      const yearMonthDateElement = document.querySelector('#timeDisplay .year-month-date');
      const weekdayElement = document.querySelector('#timeDisplay .weekday');
      
      if (yearMonthDateElement) {
        // 更新月/日格式
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const date = String(now.getDate()).padStart(2, '0');
        yearMonthDateElement.textContent = `${month}/${date}`;
      }
      
      if (weekdayElement) {
        // 更新星期
        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const weekday = weekdays[now.getDay()];
        weekdayElement.textContent = weekday;
      }
    }
  }, 60000); // 每分钟检查一次
}

// 处理添加链接
async function handleAddLink(event) {
  event.preventDefault();
  
  const formData = new FormData(event.target);
  const linkData = {
    // 不在这里生成ID，让IndexedDB处理
    title: formData.get('title') || document.getElementById('linkTitle').value,
    url: formData.get('url') || document.getElementById('linkUrl').value,
    logo: formData.get('logo') || document.getElementById('linkLogo').value,
    categoryId: formData.get('category') || document.getElementById('linkCategory').value,
    note: formData.get('note') || document.getElementById('linkNote').value,
    createTime: new Date().toISOString(),
    visitCount: 0,
    isQuickAccess: document.getElementById('isQuickAccess').checked
  };
  
  if (!linkData.title || !linkData.url) {
    showNotification('请填写标题和链接地址', 'error');
    return;
  }
  
  let addSuccess = false;
  let newLink = null;
  
  try {
    // 使用IndexedDB的addLink方法
    newLink = await StorageManager.addLink(linkData);
    addSuccess = true;
    
    // 更新本地状态
    NewTabState.links.push(newLink);
    
    console.log('链接添加成功:', newLink);
    
  } catch (dbError) {
    // 检查是否是重复链接错误
    if (dbError.name === 'DuplicateUrlError') {
      showNotification(`链接已存在：${dbError.existingLink.title}`, 'warning');
      return;
    }
    
    console.error('数据库操作失败:', dbError);
    showNotification('添加链接失败: ' + (dbError.message || '数据库错误'), 'error');
    return;
  }
  
  // 如果数据添加成功，继续处理UI操作
  if (addSuccess && newLink) {
    try {
      // 先关闭模态框
      Modal.closeAll();
      
      // 延迟重置表单和刷新UI，避免与关闭动画冲突
      setTimeout(() => {
        try {
          // 重置表单
          if (event.target && typeof event.target.reset === 'function') {
            event.target.reset();
          }
          
          // 刷新UI
          renderQuickAccess();
          renderLinks();
          
          showNotification('链接添加成功！', 'success');
          
        } catch (uiError) {
          console.warn('UI操作警告:', uiError);
          // 即使UI操作出错，数据已经添加成功，只显示警告
          showNotification('链接添加成功，但界面刷新可能有延迟', 'success');
          
          // 手动刷新页面以确保显示最新数据
          setTimeout(() => {
            location.reload();
          }, 1000);
        }
      }, 300);
      
    } catch (modalError) {
      console.warn('模态框关闭错误:', modalError);
      // 即使模态框关闭出错，数据已经添加成功
      showNotification('链接添加成功！', 'success');
      
      // 强制关闭模态框并刷新
      setTimeout(() => {
        try {
          const modal = document.getElementById('addLinkModal');
          if (modal) {
            modal.style.display = 'none';
          }
          document.body.style.overflow = '';
          
          renderQuickAccess();
          renderLinks();
        } catch (fallbackError) {
          console.warn('备用UI操作失败:', fallbackError);
          location.reload();
        }
      }, 100);
    }
  }
}

// 键盘快捷键
function handleKeyboardShortcuts(event) {
  // Ctrl/Cmd + K: 聚焦搜索框
  if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
    event.preventDefault();
    document.getElementById('mainSearch').focus();
  }
  
  // Escape: 清空搜索或关闭模态框
  if (event.key === 'Escape') {
    if (document.querySelector('.modal[style*="flex"]')) {
      Modal.closeAll();
    } else {
      document.getElementById('mainSearch').value = '';
      NewTabState.searchQuery = '';
      renderLinks();
    }
  }
}

// 显示状态函数
function showLoadingState() {
  document.getElementById('linksGrid').innerHTML = `
    <div class="loading-state">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
  `;
}

function hideLoadingState() {
  // 由renderLinks处理
}

function showErrorState(message) {
  const errorContainer = document.createElement('div');
  errorContainer.className = 'error-state';
  errorContainer.innerHTML = `
    <div class="error-icon">⚠️</div>
    <p>${message}</p>
    <button class="btn btn-primary" id="reloadPageBtn">重新加载</button>
  `;
  
  document.getElementById('linksGrid').appendChild(errorContainer);
  
  // 使用addEventListener绑定重新加载事件
  const reloadBtn = document.getElementById('reloadPageBtn');
  if (reloadBtn) {
    reloadBtn.addEventListener('click', () => {
      location.reload();
    });
  }
}

function showNotification(message, type = 'info') {
  const notification = document.createElement('div');
  notification.className = `notification notification-${type}`;
  notification.textContent = message;
  document.body.appendChild(notification);
  
  setTimeout(() => {
    if (notification.parentNode) {
      notification.parentNode.removeChild(notification);
    }
  }, 3000);
}

// 处理链接删除事件
async function handleLinkDeleted(event) {
  const { linkId } = event.detail;
  
  try {
    // 从状态中移除链接
    NewTabState.links = NewTabState.links.filter(link => link.id !== linkId);
    
    // 局部刷新相关列表
    renderQuickAccess(); // 刷新快速访问区域
    renderLinks();       // 刷新链接列表
    renderCategories();  // 刷新分类导航（更新链接数量）
    
    console.log(`链接 ${linkId} 已删除，列表已刷新`);
  } catch (error) {
    console.error('处理链接删除事件失败:', error);
  }
}

// 处理链接更新事件
async function handleLinkUpdated(event) {
  const { linkId, updatedLink } = event.detail;
  
  try {
    // 更新状态中的链接
    const linkIndex = NewTabState.links.findIndex(link => link.id === linkId);
    if (linkIndex !== -1) {
      NewTabState.links[linkIndex] = updatedLink;
    }
    
    // 局部刷新相关列表
    renderQuickAccess(); // 刷新快速访问区域
    renderLinks();       // 刷新链接列表
    renderCategories();  // 刷新分类导航（更新链接数量）
    
    console.log(`链接 ${linkId} 已更新，列表已刷新`);
  } catch (error) {
    console.error('处理链接更新事件失败:', error);
  }
}

// 数据导出导入
async function exportData() {
  try {
    const data = await StorageManager.exportData();
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `a1tabs-backup-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    showNotification('数据导出成功', 'success');
  } catch (error) {
    showNotification('导出失败', 'error');
  }
}

async function importData(event) {
  const file = event.target.files[0];
  if (!file) return;
  
  try {
    const text = await file.text();
    const data = JSON.parse(text);
    
    if (confirm('导入数据将覆盖现有数据，确定继续吗？')) {
      await StorageManager.importData(data);
      location.reload();
    }
  } catch (error) {
    showNotification('导入失败，请检查文件格式', 'error');
  }
}

async function clearAllData() {
  if (confirm('确定要清空所有数据吗？此操作无法恢复！')) {
    await StorageManager.clearAllData();
    location.reload();
  }
}

// 处理书签导入事件
async function handleBookmarksImported(event) {
  const { linksCount, categoriesCount } = event.detail;
  
  console.log(`书签导入完成: ${linksCount} 个链接, ${categoriesCount} 个分类`);
  
  // 重新加载数据
  await loadAllData();
  
  // 显示成功消息
  showNotification(`成功导入 ${linksCount} 个链接和 ${categoriesCount} 个分类！`, 'success');
}

// 处理用户须知确认事件
function handleWelcomeNoticeConfirmed() {
  console.log('用户已确认查看用户须知');
  
  // 可以在这里添加一些用户确认后的操作
  // 比如显示欢迎消息或其他提示
  
  showNotification('欢迎使用 A1Tabs！', 'success');
}

// 移动端抽屉控制函数
function toggleSidebar(forceOpen) {
  const sidebar = document.querySelector('.sidebar');
  const backdrop = document.getElementById('drawerBackdrop');
  if (!sidebar) return;

  const shouldOpen = typeof forceOpen === 'boolean' ? forceOpen : !sidebar.classList.contains('open');
  if (shouldOpen) {
    sidebar.classList.add('open');
    if (backdrop) {
      backdrop.classList.add('visible');
      backdrop.setAttribute('aria-hidden', 'false');
    }
    const navToggle = document.getElementById('navToggleBtn');
    if (navToggle) navToggle.setAttribute('aria-expanded', 'true');
    document.body.classList.add('sidebar-open');
    // 隐藏悬浮按钮
    const floatBtn = document.getElementById('sidebarFloatBtn');
    if (floatBtn) floatBtn.style.display = 'none';
    
    // 在移动端模式下无需特别隐藏lifeStatsContainer，由CSS控制各项目显示
    const lifeStatsContainer = document.getElementById('lifeStatsContainer');
    if (lifeStatsContainer && window.matchMedia('(max-width: 768px)').matches) {
      lifeStatsContainer.style.display = 'block';
    }
  } else {
    sidebar.classList.remove('open');
    if (backdrop) {
      backdrop.classList.remove('visible');
      backdrop.setAttribute('aria-hidden', 'true');
    }
    const navToggle = document.getElementById('navToggleBtn');
    if (navToggle) navToggle.setAttribute('aria-expanded', 'false');
    document.body.classList.remove('sidebar-open');
    // 显示悬浮按钮（仅在小屏）
    const floatBtn = document.getElementById('sidebarFloatBtn');
    if (floatBtn && window.matchMedia('(max-width: 768px)').matches) floatBtn.style.display = 'inline-flex';
    
    // 在移动端模式下显示lifeStatsContainer
    const lifeStatsContainer = document.getElementById('lifeStatsContainer');
    if (lifeStatsContainer && window.matchMedia('(max-width: 768px)').matches) {
      lifeStatsContainer.style.display = 'block';
    }
  }
}

function closeSidebar() {
  toggleSidebar(false);
}

// 根据窗口尺寸与侧边栏状态控制悬浮按钮显示
function updateSidebarFloatVisibility() {
  const floatBtn = document.getElementById('sidebarFloatBtn');
  const sidebar = document.querySelector('.sidebar');
  const lifeStatsContainer = document.getElementById('lifeStatsContainer');
  
  if (!floatBtn) return;

  const isMobile = window.matchMedia('(max-width: 768px)').matches;
  const isOpen = sidebar && sidebar.classList.contains('open');

  if (isMobile && !isOpen) {
    floatBtn.style.display = 'inline-flex';
    // 在移动端模式下显示lifeStatsContainer
    if (lifeStatsContainer) {
      lifeStatsContainer.style.display = 'block';
    }
  } else {
    floatBtn.style.display = 'none';
    // 在移动端模式下根据侧边栏状态控制显示
    if (lifeStatsContainer && isMobile) {
      if (isOpen) {
        lifeStatsContainer.style.display = 'none';
      } else {
        lifeStatsContainer.style.display = 'block';
      }
    }
  }
}

// TO-DO 功能相关代码
let todos = [];

// 初始化待办事项
async function initTodoFeature() {
  // 从 IndexedDB 加载待办事项
  try {
    const savedTodos = await StorageManager.getTodos();
    todos = savedTodos || [];
    renderTodoList();
  } catch (error) {
    console.error('加载待办事项失败:', error);
    todos = [];
  }

  // 绑定待办事项相关事件
  bindTodoEvents();
}

// 绑定待办事项相关事件
function bindTodoEvents() {
  // 绑定待办事项输入框事件
  const todoInput = document.getElementById('todoInput');
  if (todoInput) {
    // Ctrl+Enter 添加待办事项
    todoInput.addEventListener('keydown', function(e) {
      if (e.ctrlKey && e.key === 'Enter') {
        e.preventDefault(); // 阻止默认换行动作
        addTodo();
      }
      // Enter键换行（不做任何处理，允许自然换行）
    });
    
    // 自动调整textarea高度
    todoInput.addEventListener('input', function() {
      this.style.height = 'auto';
      this.style.height = (this.scrollHeight) + 'px';
    });
  }

  // 绑定添加按钮点击事件
  const addTodoBtn = document.getElementById('addTodoBtn');
  if (addTodoBtn) {
    addTodoBtn.addEventListener('click', addTodo);
  }
}

// 切换待办事项抽屉
function toggleTodoDrawer() {
  const drawer = document.getElementById('todoDrawer');
  const overlay = document.getElementById('todoOverlay');
  
  if (drawer && overlay) {
    drawer.classList.toggle('open');
    overlay.classList.toggle('show');
    
    // 如果抽屉现在是打开状态，聚焦到输入框
    if (drawer.classList.contains('open')) {
      const input = document.getElementById('todoInput');
      if (input) {
        setTimeout(() => input.focus(), 300);
      }
    }
  }
}

// 添加待办事项
async function addTodo() {
  const input = document.getElementById('todoInput');
  if (!input) return;
  
  const text = input.value.trim();
  if (text === '') return;
  
  const newTodo = {
    id: Date.now(),
    text: text,
    completed: false,
    createdAt: new Date().toISOString()
  };
  
  todos.unshift(newTodo); // 添加到开头
  saveTodos();
  renderTodoList();
  
  // 清空输入框并重置高度
  input.value = '';
  input.style.height = 'auto';
  input.style.height = (input.scrollHeight) + 'px';
}

// 切换待办事项完成状态
async function toggleTodo(id) {
  const todo = todos.find(t => t.id === id);
  if (todo) {
    todo.completed = !todo.completed;
    await saveTodos();
    renderTodoList();
  }
}

// 显示删除待办事项确认模态框
function showDeleteTodoModal(id, text) {
  const modal = document.getElementById('deleteTodoModal');
  const todoTextElement = document.getElementById('deleteTodoText');
  const confirmButton = document.getElementById('confirmDeleteTodo');
  const cancelButton = document.getElementById('cancelDeleteTodo');
  
  if (modal && todoTextElement && confirmButton && cancelButton) {
    // 填入待办事项内容
    todoTextElement.textContent = text;
    
    // 绑定确认删除事件
    const handleConfirm = () => {
      deleteTodoConfirmed(id);
      modal.style.display = 'none';
      document.body.style.overflow = '';
      // 移除事件监听器
      confirmButton.removeEventListener('click', handleConfirm);
      cancelButton.removeEventListener('click', handleCancel);
    };
    
    // 绑定取消事件
    const handleCancel = () => {
      modal.style.display = 'none';
      document.body.style.overflow = '';
      // 移除事件监听器
      confirmButton.removeEventListener('click', handleConfirm);
      cancelButton.removeEventListener('click', handleCancel);
    };
    
    // 移除之前的事件监听器（防止重复绑定）
    const confirmClone = confirmButton.cloneNode(true);
    confirmButton.parentNode.replaceChild(confirmClone, confirmButton);
    const cancelClone = cancelButton.cloneNode(true);
    cancelButton.parentNode.replaceChild(cancelClone, cancelButton);
    
    // 重新获取元素并绑定新事件
    const newConfirmButton = document.getElementById('confirmDeleteTodo');
    const newCancelButton = document.getElementById('cancelDeleteTodo');
    
    newConfirmButton.addEventListener('click', handleConfirm);
    newCancelButton.addEventListener('click', handleCancel);
    
    // 显示模态框
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
  }
}

// 删除待办事项（确认后）
async function deleteTodoConfirmed(id) {
  todos = todos.filter(t => t.id !== id);
  await saveTodos();
  renderTodoList();
}

// 删除待办事项（调用模态框）
function deleteTodo(id) {
  const todo = todos.find(t => t.id === id);
  if (todo) {
    showDeleteTodoModal(id, todo.text);
  }
}

// 保存待办事项到 IndexedDB
async function saveTodos() {
  try {
    await StorageManager.saveTodos(todos);
  } catch (error) {
    console.error('保存待办事项失败:', error);
  }
}

// 渲染待办事项列表
function renderTodoList() {
  const listContainer = document.getElementById('todoList');
  if (!listContainer) return;
  
  listContainer.innerHTML = '';
  
  if (todos.length === 0) {
    listContainer.innerHTML = '<div class="todo-empty">暂无待办事项</div>';
    return;
  }
  
  todos.forEach(todo => {
    const todoItem = document.createElement('div');
    todoItem.className = `todo-item ${todo.completed ? 'completed' : ''}`;
    
    // 创建头部区域（包含复选框和时间在左侧，删除按钮在右侧）
    const todoItemHeader = document.createElement('div');
    todoItemHeader.className = 'todo-item-header';
    
    // 创建左侧复选框和时间区域
    const todoLeftSide = document.createElement('div');
    todoLeftSide.className = 'todo-left-side';
    
    // 创建复选框
    const checkboxDiv = document.createElement('div');
    checkboxDiv.className = 'todo-checkbox';
    checkboxDiv.textContent = todo.completed ? '✓' : '';
    
    // 创建时间
    const timeSmall = document.createElement('small');
    timeSmall.className = 'todo-time';
    timeSmall.textContent = formatTime(todo.createdAt);
    
    todoLeftSide.appendChild(checkboxDiv);
    todoLeftSide.appendChild(timeSmall);
    
    // 创建删除按钮
    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'todo-delete-btn';
    deleteBtn.textContent = '×';
    
    // 将左侧区域和删除按钮放入头部
    todoItemHeader.appendChild(todoLeftSide);
    todoItemHeader.appendChild(deleteBtn);
    
    // 创建内容区域（单独一行）
    const todoItemContent = document.createElement('div');
    todoItemContent.className = 'todo-item-content';
    
    // 创建文本内容
    const textDiv = document.createElement('div');
    textDiv.className = 'todo-text';
    
    const textSpan = document.createElement('span');
    textSpan.className = todo.completed ? 'completed-text' : '';
    textSpan.textContent = todo.text;
    
    textDiv.appendChild(textSpan);
    todoItemContent.appendChild(textDiv);
    
    // 绑定事件
    checkboxDiv.addEventListener('click', () => toggleTodo(todo.id));
    deleteBtn.addEventListener('click', (e) => {
      e.stopPropagation(); // 防止触发父元素的点击事件
      deleteTodo(todo.id);
    });
    
    // 将头部和内容区域添加到项目中
    todoItem.appendChild(todoItemHeader);
    todoItem.appendChild(todoItemContent);
    
    listContainer.appendChild(todoItem);
  });
}

// 格式化时间显示
function formatTime(dateString) {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now - date;
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  
  if (diffDays === 0) {
    return '今天 ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
  } else if (diffDays === 1) {
    return '昨天 ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
  } else {
    return date.toLocaleDateString([], {month: 'short', day: 'numeric'}) + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
  }
}

// 页面加载完成后启动时钟和生命统计数据
window.addEventListener('DOMContentLoaded', () => {
  startClock();
  
  // 绑定个人信息按钮事件
  const personalInfoBtn = document.getElementById('personalInfoBtn');
  if (personalInfoBtn) {
    personalInfoBtn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      Modal.showPersonalInfoModal();
    });
  }
  
  // 初始化待办事项功能
  initTodoFeature();
  
  // 绑定待办事项按钮事件
  const todoBtn = document.getElementById('todoBtn');
  if (todoBtn) {
    todoBtn.addEventListener('click', toggleTodoDrawer);
  }
  
  // 绑定待办事项遮罩层点击事件
  const todoOverlay = document.getElementById('todoOverlay');
  if (todoOverlay) {
    todoOverlay.addEventListener('click', toggleTodoDrawer);
  }
  
  // 绑定待办事项关闭按钮事件
  const closeTodoDrawerBtn = document.getElementById('closeTodoDrawer');
  if (closeTodoDrawerBtn) {
    closeTodoDrawerBtn.addEventListener('click', toggleTodoDrawer);
  }
});