// 美化模态框组件
const Modal = {
  init() {
    document.addEventListener('click', (e) => {
      // 检查点击的元素或其父元素是否包含modal-close类
      const closeButton = e.target.closest('.modal-close');
      
      if (closeButton) {
        // 获取对应的模态框
        const modal = closeButton.closest('.modal');
        if (modal) {
          // 如果是删除确认模态框，单独关闭
          if (modal.id === 'deleteCategoryModal' || modal.id === 'deleteLinkModal') {
            this.hide(modal.id);
          } else {
            // 其他模态框关闭所有
            this.closeAll();
          }
        }
      }
      // 移除了点击背景关闭模态框的功能
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        // 检查是否有用户须知模态框打开，如果有则不响应ESC
        const welcomeModal = document.getElementById('welcomeNoticeModal');
        if (welcomeModal && welcomeModal.style.display === 'flex') {
          return; // 用户须知模态框打开时，ESC键无效
        }
        
        // ESC键只关闭非删除确认模态框
        const deleteModals = document.querySelectorAll('#deleteCategoryModal, #deleteLinkModal');
        const hasDeleteModalOpen = Array.from(deleteModals).some(modal => 
          modal.style.display === 'flex'
        );
        
        if (!hasDeleteModalOpen) {
          this.closeAll();
        }
      }
    });
    
    // 初始化表单事件
    this.initFormEvents();
  },
  
  showAddLinkModal() {
    const modal = document.getElementById('addLinkModal');
    if (modal) {
      // 显示模态框
      modal.style.display = 'flex';
      
      // 重置表单
      const form = modal.querySelector('form');
      if (form) {
        form.reset();
      }
      
      // 加载分类选项
      this.updateCategoryOptions();
      
      // 聚焦到第一个输入框并添加动画延迟
      setTimeout(() => {
        const urlInput = modal.querySelector('#linkUrl');
        if (urlInput) {
          urlInput.focus();
        }
      }, 150);
      
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
    }
  },
  
  showAddCategoryModal() {
    const modal = document.getElementById('addCategoryModal');
    if (modal) {
      // 显示模态框
      modal.style.display = 'flex';
      
      // 重置表单
      const form = modal.querySelector('form');
      if (form) {
        form.reset();
        // 重置默认选中的颜色
        const defaultColor = modal.querySelector('input[name="categoryColor"][value="#4285f4"]');
        if (defaultColor) {
          defaultColor.checked = true;
        }
      }
      
      // 聚焦到第一个输入框并添加动画延迟
      setTimeout(() => {
        const nameInput = modal.querySelector('#categoryName');
        if (nameInput) {
          nameInput.focus();
        }
      }, 150);
      
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
    }
  },
  
  showSettingsModal() {
    const modal = document.getElementById('settingsModal');
    if (modal) {
      modal.style.display = 'flex';
      
      // 加载当前设置值
      this.loadCurrentSettings();
      
      // 聚焦处理
      setTimeout(() => {
        const firstTab = modal.querySelector('.settings-tab.active');
        if (firstTab) {
          firstTab.focus();
        }
      }, 150);
      
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
    }
  },
  
  showManageCategoryModal() {
    const modal = document.getElementById('manageCategoryModal');
    if (modal) {
      // 显示模态框
      modal.style.display = 'flex';
      
      // 加载分类列表
      this.loadCategoriesForManagement();
      
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
      
      console.log('管理分类模态框已显示');
    }
  },
  
  showEditLinkModal(linkData) {
    const modal = document.getElementById('editLinkModal');
    if (modal) {
      // 显示模态框
      modal.style.display = 'flex';
      
      // 填充表单数据
      this.populateEditLinkForm(linkData);
      
      // 加载分类选项
      this.updateEditCategoryOptions();
      
      // 聚焦到第一个输入框并添加动画延迟
      setTimeout(() => {
        const titleInput = modal.querySelector('#editLinkTitle');
        if (titleInput) {
          titleInput.focus();
        }
      }, 150);
      
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
      
      // 存储当前编辑的链接ID
      modal.setAttribute('data-link-id', linkData.id);
    }
  },

  // 显示首次使用用户须知模态框
  showWelcomeNoticeModal() {
    const modal = document.getElementById('welcomeNoticeModal');
    if (modal) {
      modal.style.display = 'flex';
      
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
      
      // 特殊处理：这个模态框不能通过ESC或点击背景关闭
      modal.classList.add('modal-no-close');
      
      console.log('用户须知模态框已显示');
    }
  },

  // 关闭用户须知模态框（仅在用户确认后）
  closeWelcomeNoticeModal() {
    const modal = document.getElementById('welcomeNoticeModal');
    if (modal && modal.style.display === 'flex') {
      // 添加关闭动画
      modal.style.opacity = '0';
      modal.querySelector('.modal-content').style.transform = 'scale(0.9) translateY(20px)';
      
      setTimeout(() => {
        modal.style.display = 'none';
        modal.style.opacity = '';
        modal.classList.remove('modal-no-close');
        if (modal.querySelector('.modal-content')) {
          modal.querySelector('.modal-content').style.transform = '';
        }
        
        // 恢复背景滚动
        document.body.style.overflow = '';
      }, 200);
      
      console.log('用户须知模态框已关闭');
    }
  },
  
  // 加载当前设置值
  async loadCurrentSettings() {
    try {
      const settings = await StorageManager.getSettings();
      
      // 设置默认视图
      const defaultViewSelect = document.getElementById('defaultView');
      if (defaultViewSelect && settings.defaultView) {
        defaultViewSelect.value = settings.defaultView;
      }
      
      // 设置搜索引擎
      const searchEngineSelect = document.getElementById('searchEngine');
      if (searchEngineSelect && settings.searchEngine) {
        searchEngineSelect.value = settings.searchEngine;
      }
      
      // 设置主题
      const themeSelect = document.getElementById('themeSelect');
      if (themeSelect && settings.theme) {
        themeSelect.value = settings.theme;
      }
      
      // 设置背景类型
      const backgroundTypeSelect = document.getElementById('backgroundType');
      if (backgroundTypeSelect && settings.backgroundType) {
        backgroundTypeSelect.value = settings.backgroundType;
      }
      
      // 加载个人信息
      const nicknameInput = document.getElementById('nickname');
      if (nicknameInput && settings.nickname) {
        nicknameInput.value = settings.nickname;
      }
      
      const birthDateInput = document.getElementById('birthDate');
      if (birthDateInput && settings.birthDate) {
        birthDateInput.value = settings.birthDate;
      }
      
      const genderSelect = document.getElementById('gender');
      if (genderSelect && settings.gender) {
        genderSelect.value = settings.gender;
      }
      
      const identitySelect = document.getElementById('identity');
      if (identitySelect && settings.identity) {
        identitySelect.value = settings.identity;
      }
      
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  },
  
  closeAll() {
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
      // 跳过用户须知模态框，它不能被意外关闭
      if (modal.id === 'welcomeNoticeModal') {
        return;
      }
      
      if (modal.style.display === 'flex') {
        // 添加关闭动画
        modal.style.opacity = '0';
        modal.querySelector('.modal-content').style.transform = 'scale(0.9) translateY(20px)';
        
        setTimeout(() => {
          modal.style.display = 'none';
          modal.style.opacity = '';
          if (modal.querySelector('.modal-content')) {
            modal.querySelector('.modal-content').style.transform = '';
          }
        }, 200);
      }
    });
    
    // 检查用户须知模态框是否仍然打开，如果是则不恢复背景滚动
    const welcomeModal = document.getElementById('welcomeNoticeModal');
    if (!welcomeModal || welcomeModal.style.display !== 'flex') {
      // 恢复背景滚动
      document.body.style.overflow = '';
    }
  },
  
  // 平滑显示模态框的方法
  show(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
      modal.style.display = 'flex';
      
      // 强制重绘以确保动画生效
      modal.offsetHeight;
      
      modal.style.opacity = '1';
      modal.style.visibility = 'visible';
      
      const content = modal.querySelector('.modal-content');
      if (content) {
        content.style.transform = 'scale(1) translateY(0)';
        content.style.opacity = '1';
      }
      
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
    }
  },
  
  // 平滑隐藏模态框的方法
  hide(modalId) {
    const modal = document.getElementById(modalId);
    if (modal && modal.style.display === 'flex') {
      // 添加关闭动画
      modal.style.opacity = '0';
      
      const content = modal.querySelector('.modal-content');
      if (content) {
        content.style.transform = 'scale(0.9) translateY(20px)';
      }
      
      setTimeout(() => {
        modal.style.display = 'none';
        modal.style.opacity = '';
        modal.style.visibility = '';
        if (content) {
          content.style.transform = '';
        }
      }, 200);
      
      // 检查是否还有其他模态框打开
      setTimeout(() => {
        const openModals = document.querySelectorAll('.modal[style*="flex"]');
        if (openModals.length === 0) {
          // 恢复背景滚动
          document.body.style.overflow = '';
        }
      }, 200);
      
      console.log(`模态框 ${modalId} 已关闭`);
    }
  },
  
  // 表单验证和用户体验增强
  enhanceForm(formId) {
    const form = document.getElementById(formId);
    if (!form) return;
    
    const inputs = form.querySelectorAll('input, select, textarea');
    
    inputs.forEach(input => {
      // 添加浮动标签效果
      input.addEventListener('focus', () => {
        input.parentElement.classList.add('focused');
      });
      
      input.addEventListener('blur', () => {
        if (!input.value) {
          input.parentElement.classList.remove('focused');
        }
      });
      
      // 实时验证
      input.addEventListener('input', () => {
        this.validateField(input);
      });
    });
  },
  
  // 字段验证
  validateField(field) {
    const value = field.value.trim();
    let isValid = true;
    let message = '';
    
    // 移除之前的错误状态
    field.classList.remove('error');
    const existingError = field.parentElement.querySelector('.error-message');
    if (existingError) {
      existingError.remove();
    }
    
    // URL验证
    if (field.type === 'url' && value) {
      const urlPattern = /^https?:\/\/.+/;
      if (!urlPattern.test(value)) {
        isValid = false;
        message = '请输入有效的URL地址';
      }
    }
    
    // 必填字段验证
    if (field.required && !value) {
      isValid = false;
      message = '此字段为必填项';
    }
    
    // 分类名称验证
    if (field.id === 'categoryName') {
      if (value.length > 20) {
        isValid = false;
        message = '分类名称不能超过20个字符';
      } else if (value && !/^[\u4e00-\u9fa5a-zA-Z0-9\s]+$/.test(value)) {
        isValid = false;
        message = '分类名称只能包含中文、英文、数字和空格';
      }
    }
    
    // 显示错误信息
    if (!isValid) {
      field.classList.add('error');
      const errorDiv = document.createElement('div');
      errorDiv.className = 'error-message';
      errorDiv.textContent = message;
      field.parentElement.appendChild(errorDiv);
    }
    
    return isValid;
  },
  
  // 初始化表单事件
  initFormEvents() {
    // 添加链接表单事件
    const addLinkForm = document.getElementById('addLinkForm');
    if (addLinkForm) {
      addLinkForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        await this.handleAddLink(addLinkForm);
      });
    }
    
    // 编辑链接表单事件
    const editLinkForm = document.getElementById('editLinkForm');
    if (editLinkForm) {
      editLinkForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        await this.handleEditLink(editLinkForm);
      });
    }
    
    // 添加分类表单事件
    const addCategoryForm = document.getElementById('addCategoryForm');
    if (addCategoryForm) {
      addCategoryForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        await this.handleAddCategory(addCategoryForm);
      });
    }
    
    // 绑定Logo颜色选择器事件
    this.bindLogoColorEvents();
    
    // 绑定添加链接模态框特定事件
    this.bindAddLinkModalEvents();
    
    // 取消按钮事件
    document.addEventListener('click', (e) => {
      if (e.target.id === 'cancelAddLink' || e.target.id === 'cancelAddCategory' || e.target.id === 'closeManageCategory' || e.target.id === 'cancelEditLink') {
        this.closeAll();
      }
      
      // 从书签导入按钮事件
      if (e.target.id === 'importFromBookmarksBtn') {
        this.showImportBookmarksModal();
      }
      
      // 修复分类数据按钮事件
      if (e.target.id === 'fixCategoryDataBtn') {
        this.fixImportedLinksCategories();
      }
      
      // 书签导入模态框相关按钮事件
      if (e.target.id === 'loadBookmarksBtn') {
        this.loadBookmarks();
      }
      
      if (e.target.id === 'importSelectedBtn') {
        this.importSelectedBookmarks();
      }
      
      if (e.target.id === 'cancelImportBookmarks') {
        this.closeImportBookmarksModal();
      }
      
      // 用户须知确认按钮事件
      if (e.target.id === 'confirmWelcomeNotice') {
        this.handleWelcomeNoticeConfirm();
      }
      
      // 保存个人信息按钮事件
      if (e.target.id === 'savePersonalInfo') {
        this.handleSavePersonalInfo();
      }
    });
  },
  
  // 处理添加链接
  async handleAddLink(form) {
    const formData = new FormData(form);
    const linkData = {
      url: form.querySelector('#linkUrl').value.trim(),
      title: form.querySelector('#linkTitle').value.trim(),
      logo: form.querySelector('#linkLogo').value.trim(),
      logoColor: form.querySelector('#linkLogoColorPicker').value,
      category: form.querySelector('#linkCategory').value,
      note: form.querySelector('#linkNote').value.trim(),
      isQuickAccess: form.querySelector('#isQuickAccess')?.checked || false
    };
    
    // 验证数据
    if (!linkData.url || !linkData.title) {
      this.showNotification('请填写必填项！', 'error');
      return;
    }
    
    try {
      const newLink = await StorageManager.addLink(linkData);
      this.showNotification('链接添加成功！', 'success');
      this.closeAll();
      
      // 触发自定义事件，通知页面更新
      document.dispatchEvent(new CustomEvent('linkAdded', { detail: newLink }));
    } catch (error) {
      // 检查是否是重复链接错误
      if (error.name === 'DuplicateUrlError') {
        this.showNotification(`链接已存在：${error.existingLink.title}`, 'warning');
        return;
      }
      
      console.error('添加链接失败:', error);
      this.showNotification('添加链接失败，请重试！', 'error');
    }
  },
  
  // 处理编辑链接
  async handleEditLink(form) {
    const modal = document.getElementById('editLinkModal');
    const linkId = modal.getAttribute('data-link-id');
    
    if (!linkId) {
      this.showNotification('无法获取链接ID！', 'error');
      return;
    }
    
    const linkData = {
      url: form.querySelector('#editLinkUrl').value.trim(),
      title: form.querySelector('#editLinkTitle').value.trim(),
      logo: form.querySelector('#editLinkLogo').value.trim(),
      logoColor: form.querySelector('#editLinkLogoColorPicker').value,
      categoryId: form.querySelector('#editLinkCategory').value,
      note: form.querySelector('#editLinkNote').value.trim(),
      isQuickAccess: form.querySelector('#editIsQuickAccess')?.checked || false
    };
    
    // 验证数据
    if (!linkData.url || !linkData.title) {
      this.showNotification('请填写必填项！', 'error');
      return;
    }
    
    try {
      // 显示加载状态
      const modal = document.getElementById('editLinkModal');
      const submitButton = modal.querySelector('button[type="submit"]');
      let originalText = '保存';
      
      if (submitButton) {
        originalText = submitButton.textContent;
        submitButton.textContent = '保存中...';
        submitButton.disabled = true;
      }
      
      // 执行更新操作
      const updatedLink = await StorageManager.updateLink(linkId, linkData);
      
      this.showNotification('链接更新成功！', 'success');
      this.closeAll();
      
      // 触发自定义事件，通知页面更新
      document.dispatchEvent(new CustomEvent('linkUpdated', { 
        detail: { linkId, updatedLink } 
      }));
      
    } catch (error) {
      console.error('更新链接失败:', error);
      this.showNotification('更新链接失败，请重试！', 'error');
    } finally {
      // 恢复按钮状态
      const modal = document.getElementById('editLinkModal');
      const submitButton = modal.querySelector('button[type="submit"]');
      if (submitButton) {
        submitButton.textContent = '保存';
        submitButton.disabled = false;
      }
    }
  },
  
  // 处理添加分类
  async handleAddCategory(form) {
    const categoryData = {
      name: form.querySelector('#categoryName').value.trim(),
      icon: form.querySelector('#categoryIcon').value,
      color: form.querySelector('input[name="categoryColor"]:checked').value,
      description: form.querySelector('#categoryDescription').value.trim()
    };
    
    // 验证数据
    if (!categoryData.name) {
      this.showNotification('请输入分类名称！', 'error');
      return;
    }
    
    try {
      // 检查分类名称是否已存在
      const existingCategories = await StorageManager.getCategories();
      const nameExists = existingCategories.some(cat => 
        cat.name.toLowerCase() === categoryData.name.toLowerCase()
      );
      
      if (nameExists) {
        this.showNotification('分类名称已存在，请选择其他名称！', 'error');
        return;
      }
      
      const newCategory = await StorageManager.addCategory(categoryData);
      this.showNotification('分类添加成功！', 'success');
      this.closeAll();
      
      // 触发自定义事件，通知页面更新
      document.dispatchEvent(new CustomEvent('categoryAdded', { detail: newCategory }));
      
      // 局部刷新分类栏
      this.refreshCategoriesNav();
      
      // 更新添加链接表单中的分类选项
      this.updateCategoryOptions();
    } catch (error) {
      console.error('添加分类失败:', error);
      this.showNotification('添加分类失败，请重试！', 'error');
    }
  },
  
  // 刷新分类导航栏
  async refreshCategoriesNav() {
    try {
      const categoriesContainer = document.getElementById('categoriesContainer');
      if (!categoriesContainer) return;
      
      // 获取最新的分类数据
      const categories = await StorageManager.getCategoriesWithCounts();
      
      // 清空现有分类
      categoriesContainer.innerHTML = '';
      
      // 添加"所有"标签
      const allTab = document.createElement('div');
      allTab.className = 'category-tab active';
      allTab.setAttribute('data-category-id', '');
      allTab.innerHTML = `
        <span class="category-name">所有</span>
        <span class="category-indicator" style="background-color: #6b7280"></span>
      `;
      categoriesContainer.appendChild(allTab);
      
      // 添加分类标签
      categories.forEach(category => {
        const tab = CategoryTab.create({
          id: category.id,
          name: category.name,
          color: category.color,
          icon: category.icon,
          linkCount: category.linkCount,
          isActive: false
        });
        categoriesContainer.appendChild(tab);
      });
      
      // 添加分类点击事件
      this.bindCategoryEvents();
      
      console.log('分类导航栏已刷新', categories);
    } catch (error) {
      console.error('刷新分类导航栏失败:', error);
    }
  },
  
  // 更新分类选项
  async updateCategoryOptions() {
    try {
      const categories = await StorageManager.getCategories();
      const selects = document.querySelectorAll('#linkCategory');
      
      selects.forEach(select => {
        // 保留默认选项
        select.innerHTML = '<option value="">选择分类</option>';
        
        // 添加新的分类选项
        categories.forEach(category => {
          const option = document.createElement('option');
          option.value = category.id;
          // 检查图标，防止未设置图标显示为未知
          const icon = category.icon && category.icon.trim() ? category.icon : '📁';
          option.textContent = `${icon} ${category.name}`;
          select.appendChild(option);
        });
      });
      
      console.log('分类选项已更新');
    } catch (error) {
      console.error('更新分类选项失败:', error);
    }
  },
  
  // 更新编辑模态框中的分类选项
  async updateEditCategoryOptions() {
    try {
      const categories = await StorageManager.getCategories();
      const select = document.querySelector('#editLinkCategory');
      
      if (select) {
        // 保留默认选项
        select.innerHTML = '<option value="">选择分类</option>';
        
        // 添加新的分类选项
        categories.forEach(category => {
          const option = document.createElement('option');
          option.value = category.id;
          // 检查图标，防止未设置图标显示为未知
          const icon = category.icon && category.icon.trim() ? category.icon : '📁';
          option.textContent = `${icon} ${category.name}`;
          select.appendChild(option);
        });
      }
      
      console.log('编辑模态框分类选项已更新');
    } catch (error) {
      console.error('更新编辑模态框分类选项失败:', error);
    }
  },
  
  // 填充编辑链接表单数据
  populateEditLinkForm(linkData) {
    const modal = document.getElementById('editLinkModal');
    if (!modal) return;
    
    // 填充表单字段
    const urlInput = modal.querySelector('#editLinkUrl');
    const titleInput = modal.querySelector('#editLinkTitle');
    const logoInput = modal.querySelector('#editLinkLogo');
    const logoColorPicker = modal.querySelector('#editLinkLogoColorPicker');
    const categorySelect = modal.querySelector('#editLinkCategory');
    const noteTextarea = modal.querySelector('#editLinkNote');
    const quickAccessCheckbox = modal.querySelector('#editIsQuickAccess');
    
    if (urlInput) urlInput.value = linkData.url || '';
    if (titleInput) titleInput.value = linkData.title || '';
    if (logoInput) logoInput.value = linkData.logo || '';
    if (noteTextarea) noteTextarea.value = linkData.note || '';
    if (quickAccessCheckbox) quickAccessCheckbox.checked = linkData.isQuickAccess || false;
    
    // 设置Logo颜色
    let logoColor = linkData.logoColor || '';
    if (!logoColor && linkData.categoryId) {
      // 如果没有自定义颜色，则使用分类颜色作为默认值
      this.getDefaultCategoryColor(linkData.categoryId).then(color => {
        if (logoColorPicker) {
          logoColorPicker.value = color;
          this.updateColorPreview(logoColorPicker);
        }
      });
    } else if (logoColorPicker) {
      logoColorPicker.value = logoColor || '#4285f4';
      this.updateColorPreview(logoColorPicker);
    }
    
    // 设置分类选项（需要在加载分类选项后设置）
    setTimeout(() => {
      if (categorySelect && linkData.categoryId) {
        categorySelect.value = linkData.categoryId;
      }
    }, 100);
  },
  
  // 获取分类的默认颜色
  async getDefaultCategoryColor(categoryId) {
    try {
      const categories = await StorageManager.getCategories();
      const category = categories.find(cat => cat.id === categoryId);
      return category ? category.color : '#4285f4';
    } catch (error) {
      console.error('获取分类颜色失败:', error);
      return '#4285f4';
    }
  },
  
  // 更新颜色预览
  updateColorPreview(colorInput) {
    const preview = colorInput.nextElementSibling;
    if (preview && preview.classList.contains('color-preview')) {
      preview.style.backgroundColor = colorInput.value;
    }
  },
  
  // 绑定Logo颜色选择器事件
  bindLogoColorEvents() {
    // 监听颜色选择器变化
    document.addEventListener('change', (e) => {
      if (e.target.id === 'editLinkLogoColorPicker') {
        this.updateColorPreview(e.target);
        this.updateQuickColorSelection(e.target.value);
      }
    });
    
    // 监听快捷颜色按钮点击
    document.addEventListener('click', (e) => {
      if (e.target.classList.contains('quick-color-btn')) {
        const color = e.target.getAttribute('data-color');
        const colorPicker = document.getElementById('editLinkLogoColorPicker');
        if (colorPicker) {
          colorPicker.value = color;
          this.updateColorPreview(colorPicker);
          this.updateQuickColorSelection(color);
        }
      }
    });
    
    // 监听分类选择变化，更新默认颜色
    document.addEventListener('change', async (e) => {
      if (e.target.id === 'editLinkCategory') {
        const categoryId = e.target.value;
        if (categoryId) {
          const defaultColor = await this.getDefaultCategoryColor(categoryId);
          const colorPicker = document.getElementById('editLinkLogoColorPicker');
          if (colorPicker && !colorPicker.value) {
            colorPicker.value = defaultColor;
            this.updateColorPreview(colorPicker);
            this.updateQuickColorSelection(defaultColor);
          }
        }
      }
    });
  },
  
  // 更新快捷颜色选择状态
  updateQuickColorSelection(selectedColor) {
    const quickColorBtns = document.querySelectorAll('.quick-color-btn');
    quickColorBtns.forEach(btn => {
      const btnColor = btn.getAttribute('data-color');
      if (btnColor.toLowerCase() === selectedColor.toLowerCase()) {
        btn.classList.add('active');
      } else {
        btn.classList.remove('active');
      }
    });
  },
  
  // 绑定分类点击事件
  bindCategoryEvents() {
    const categoryTabs = document.querySelectorAll('.category-tab');
    categoryTabs.forEach(tab => {
      tab.addEventListener('click', (e) => {
        // 移除所有active类
        categoryTabs.forEach(t => t.classList.remove('active'));
        // 添加到当前点击的标签
        tab.classList.add('active');
        
        // 获取分类ID并触发筛选事件
        const categoryId = tab.getAttribute('data-category-id');
        document.dispatchEvent(new CustomEvent('categoryFilter', { 
          detail: { categoryId } 
        }));
      });
    });
  },
  
  // 绑定添加链接模态框特定事件
  bindAddLinkModalEvents() {
    // 监听分类选择变化，更新默认颜色
    document.addEventListener('change', async (e) => {
      if (e.target.id === 'linkCategory') {
        const categoryId = e.target.value;
        if (categoryId) {
          const defaultColor = await this.getDefaultCategoryColor(categoryId);
          const colorPicker = document.getElementById('linkLogoColorPicker');
          if (colorPicker && !colorPicker.value) {
            colorPicker.value = defaultColor;
            this.updateColorPreview(colorPicker);
            this.updateQuickColorSelection(defaultColor);
          }
        }
      }
    });
    
    // 监听添加链接模态框打开事件，设置默认颜色
    document.addEventListener('modalOpened', (e) => {
      if (e.detail.modalId === 'addLinkModal') {
        // 设置默认颜色为蓝色
        const colorPicker = document.getElementById('linkLogoColorPicker');
        if (colorPicker) {
          colorPicker.value = '#4285f4';
          this.updateColorPreview(colorPicker);
          this.updateQuickColorSelection('#4285f4');
        }
      }
    });
  },
  
  // 显示删除链接确认模态框
  showDeleteLinkModal(linkId, linkTitle) {
    if (!linkId || !linkTitle) {
      this.showNotification('无法获取链接信息！', 'error');
      return;
    }
    
    const modal = document.getElementById('deleteLinkModal');
    if (!modal) {
      this.showNotification('删除确认对话框未找到！', 'error');
      return;
    }
    
    // 填充链接信息
    const linkTitleSpan = modal.querySelector('#deleteLinkTitle');
    if (linkTitleSpan) {
      linkTitleSpan.textContent = linkTitle;
    }
    
    // 绑定确认删除事件
    const confirmButton = modal.querySelector('#confirmDeleteLink');
    const cancelButton = modal.querySelector('#cancelDeleteLink');
    
    if (confirmButton) {
      // 移除之前的事件监听器
      const newConfirmButton = confirmButton.cloneNode(true);
      confirmButton.parentNode.replaceChild(newConfirmButton, confirmButton);
      
      // 添加新的事件监听器
      newConfirmButton.addEventListener('click', async () => {
        await this.handleDeleteLink(linkId, linkTitle);
      });
    }
    
    if (cancelButton) {
      // 移除之前的事件监听器
      const newCancelButton = cancelButton.cloneNode(true);
      cancelButton.parentNode.replaceChild(newCancelButton, cancelButton);
      
      // 添加新的事件监听器
      newCancelButton.addEventListener('click', () => {
        this.closeAll();
      });
    }
    
    // 显示模态框
    this.show('deleteLinkModal');
  },
  
  // 处理删除链接
  async handleDeleteLink(linkId, linkTitle) {
    try {
      // 显示加载状态
      const confirmButton = document.querySelector('#confirmDeleteLink');
      const originalText = confirmButton.textContent;
      confirmButton.textContent = '删除中...';
      confirmButton.disabled = true;
      
      // 执行删除操作
      await StorageManager.deleteLink(linkId);
      
      // 显示成功消息
      this.showNotification(`链接 "${linkTitle}" 删除成功！`, 'success');
      
      // 关闭模态框
      this.closeAll();
      
      // 触发自定义事件，通知页面更新
      document.dispatchEvent(new CustomEvent('linkDeleted', { 
        detail: { linkId, linkTitle } 
      }));
      
    } catch (error) {
      console.error('删除链接失败:', error);
      this.showNotification('删除链接失败，请重试！', 'error');
    } finally {
      // 恢复按钮状态
      const confirmButton = document.querySelector('#confirmDeleteLink');
      if (confirmButton) {
        confirmButton.textContent = '确认删除';
        confirmButton.disabled = false;
      }
    }
  },
  
  // 显示删除分类确认模态框
  showDeleteCategoryModal(deleteButton) {
    const categoryId = deleteButton.getAttribute('data-category-id');
    const categoryName = deleteButton.getAttribute('data-category-name');
    const linkCount = parseInt(deleteButton.getAttribute('data-link-count')) || 0;
    
    console.log('尝试显示删除分类模态框:', { categoryId, categoryName, linkCount });
    
    if (!categoryId) {
      this.showNotification('无法获取分类信息！', 'error');
      return;
    }
    
    const modal = document.getElementById('deleteCategoryModal');
    if (!modal) {
      this.showNotification('删除确认对话框未找到！', 'error');
      return;
    }
    
    // 填充分类信息
    const categoryNameSpan = modal.querySelector('#deleteCategoryName');
    const linkCountSpan = modal.querySelector('#deleteLinkCount');
    const warningNote = modal.querySelector('.warning-note');
    
    if (categoryNameSpan) {
      categoryNameSpan.textContent = categoryName;
    }
    
    if (linkCountSpan) {
      linkCountSpan.textContent = linkCount;
    }
    
    if (warningNote) {
      if (linkCount > 0) {
        warningNote.innerHTML = `<strong>此操作不可逆转！</strong>删除后无法恢复数据，将同时删除 ${linkCount} 个链接。`;
      } else {
        warningNote.innerHTML = '<strong>此操作不可逆转！</strong>删除后无法恢复数据。';
      }
    }
    
    // 绑定确认删除事件
    const confirmButton = modal.querySelector('#confirmDeleteCategory');
    const cancelButton = modal.querySelector('#cancelDeleteCategory');
    
    if (confirmButton) {
      // 移除之前的事件监听器
      const newConfirmButton = confirmButton.cloneNode(true);
      confirmButton.parentNode.replaceChild(newConfirmButton, confirmButton);
      
      // 添加新的事件监听器
      newConfirmButton.addEventListener('click', async () => {
        await this.handleDeleteCategory(categoryId, categoryName);
      });
    }
    
    if (cancelButton) {
      // 移除之前的事件监听器
      const newCancelButton = cancelButton.cloneNode(true);
      cancelButton.parentNode.replaceChild(newCancelButton, cancelButton);
      
      // 添加新的事件监听器
      newCancelButton.addEventListener('click', () => {
        this.hide('deleteCategoryModal');
      });
    }
    
    // 显示模态框（使用直接显示方式）
    modal.style.display = 'flex';
    modal.style.opacity = '1';
    modal.style.visibility = 'visible';
    modal.style.zIndex = '1100'; // 确保在管理模态框之上
    
    // 确保模态框内容可见
    const content = modal.querySelector('.modal-content');
    if (content) {
      content.style.transform = 'scale(1) translateY(0)';
      content.style.opacity = '1';
    }
    
    // 防止背景滚动
    document.body.style.overflow = 'hidden';
    
    console.log('删除分类模态框已显示', {
      display: modal.style.display,
      opacity: modal.style.opacity,
      visibility: modal.style.visibility,
      zIndex: modal.style.zIndex,
      contentTransform: content ? content.style.transform : 'no content'
    });
  },
  
  // 处理删除分类
  async handleDeleteCategory(categoryId, categoryName) {
    try {
      // 显示加载状态
      const confirmButton = document.querySelector('#confirmDeleteCategory');
      const originalText = confirmButton.textContent;
      confirmButton.textContent = '删除中...';
      confirmButton.disabled = true;
      
      // 执行删除操作
      const result = await StorageManager.deleteCategory(categoryId);
      
      // 显示成功消息
      const message = result && result.deletedLinksCount > 0 
        ? `分类 "${categoryName}" 及其下 ${result.deletedLinksCount} 个链接删除成功！`
        : `分类 "${categoryName}" 删除成功！`;
      this.showNotification(message, 'success');
      
      // 关闭删除确认模态框
      this.hide('deleteCategoryModal');
      
      // 刷新管理分类模态框（如果还在显示状态）
      const manageModal = document.getElementById('manageCategoryModal');
      if (manageModal && manageModal.style.display === 'flex') {
        await this.loadCategoriesForManagement();
      }
      
      // 刷新界面
      await this.refreshCategoriesNav();
      await this.updateCategoryOptions();
      
      // 触发链接重新加载事件（如果当前显示的是被删除的分类）
      const activeCategory = document.querySelector('.category-tab.active');
      if (activeCategory && activeCategory.getAttribute('data-category-id') === categoryId) {
        // 切换到"所有"分类
        const allTab = document.querySelector('.category-tab[data-category-id=""]');
        if (allTab) {
          allTab.click();
        }
      }
      
      // 触发自定义事件
      document.dispatchEvent(new CustomEvent('categoryDeleted', { 
        detail: { categoryId, categoryName, deletedLinksCount: result?.deletedLinksCount || 0 } 
      }));
      
    } catch (error) {
      console.error('删除分类失败:', error);
      this.showNotification('删除分类失败，请重试！', 'error');
    } finally {
      // 恢复按钮状态
      const confirmButton = document.querySelector('#confirmDeleteCategory');
      if (confirmButton) {
        confirmButton.textContent = '确认删除';
        confirmButton.disabled = false;
      }
    }
  },
  
  // 显示通知
  showNotification(message, type = 'info') {
    // 移除已存在的通知
    const existingNotification = document.querySelector('.notification');
    if (existingNotification) {
      existingNotification.remove();
    }
    
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
      if (notification.parentElement) {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
          notification.remove();
        }, 300);
      }
    }, 3000);
  },
  
  // 加载分类管理列表
  async loadCategoriesForManagement() {
    try {
      const categories = await StorageManager.getCategoriesWithCounts();
      const container = document.getElementById('manageCategoryList');
      const countInfo = document.getElementById('totalCategoryCount');
      
      if (!container) return;
      
      container.innerHTML = '';
      
      if (categories.length === 0) {
        container.innerHTML = `
          <div class="empty-categories">
            <div class="empty-icon">📁</div>
            <h4>暂无分类</h4>
            <p>您还没有创建任何分类，点击“添加分类”按钮开始创建。</p>
          </div>
        `;
        if (countInfo) countInfo.textContent = '0';
        return;
      }
      
      categories.forEach(category => {
        const item = this.createCategoryManageItem(category);
        container.appendChild(item);
      });
      
      if (countInfo) {
        countInfo.textContent = categories.length;
      }
      
      // 在所有分类项添加完成后，绑定事件
      this.bindCategoryManageEvents();
      
      console.log('分类管理列表加载完成', categories.length, '个分类');
      
    } catch (error) {
      console.error('加载分类列表失败:', error);
      this.showNotification('加载分类列表失败', 'error');
    }
  },
  
  // 创建分类管理项
  createCategoryManageItem(category) {
    const item = document.createElement('div');
    item.className = 'manage-category-item';
    item.setAttribute('data-category-id', category.id);
    
    const linkCountText = category.linkCount > 0 ? `${category.linkCount} 个链接` : '无链接';
    
    item.innerHTML = `
      <div class="manage-category-info">
        <div class="manage-category-icon">${category.icon || '📁'}</div>
        <div class="manage-category-details">
          <h4>${category.name}</h4>
          <div class="manage-category-meta">
            <div class="manage-category-color" style="background-color: ${category.color}"></div>
            <span class="manage-category-count">${linkCountText}</span>
            ${category.description ? `<span>· ${category.description}</span>` : ''}
          </div>
        </div>
      </div>
      <div class="manage-category-actions">
        <button class="btn-edit-category" 
                data-category-id="${category.id}"
                data-category-name="${category.name}"
                data-category-icon="${category.icon || '📁'}"
                data-category-color="${category.color || '#4285f4'}"
                data-category-description="${category.description || ''}"
                title="编辑分类">
          <svg class="icon" viewBox="0 0 24 24">
            <path d="M20.71,7.04C21.1,6.65 21.1,6 20.71,5.63L18.37,3.29C18,2.9 17.35,2.9 16.96,3.29L15.12,5.12L18.87,8.87M3,17.25V21H6.75L17.81,9.93L14.06,6.18L3,17.25Z" />
          </svg>
          编辑
        </button>
        <button class="btn-delete-category" 
                data-category-id="${category.id}"
                data-category-name="${category.name}"
                data-link-count="${category.linkCount || 0}"
                title="删除分类">
          <svg class="icon" viewBox="0 0 24 24">
            <path d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"/>
          </svg>
          删除
        </button>
      </div>
    `;
    
    return item;
  },
  
  // 绑定分类管理项的事件
  bindCategoryManageEvents() {
    const container = document.getElementById('manageCategoryList');
    if (!container) return;
    
    // 移除之前的事件监听器（防止重复绑定）
    const existingHandler = container._categoryEventHandler;
    if (existingHandler) {
      container.removeEventListener('click', existingHandler);
    }
    
    // 创建新的事件处理器
    const handler = (e) => {
      // 处理删除按钮点击
      const deleteBtn = e.target.closest('.btn-delete-category');
      if (deleteBtn) {
        e.preventDefault();
        e.stopPropagation();
        console.log('删除按钮被点击', {
          categoryId: deleteBtn.getAttribute('data-category-id'),
          categoryName: deleteBtn.getAttribute('data-category-name'),
          linkCount: deleteBtn.getAttribute('data-link-count')
        });
        this.showDeleteCategoryModal(deleteBtn);
        return;
      }
      
      // 处理编辑按钮点击
      const editBtn = e.target.closest('.btn-edit-category');
      if (editBtn) {
        e.preventDefault();
        e.stopPropagation();
        console.log('编辑按钮被点击', {
          categoryId: editBtn.getAttribute('data-category-id'),
          categoryName: editBtn.getAttribute('data-category-name'),
          categoryIcon: editBtn.getAttribute('data-category-icon'),
          categoryColor: editBtn.getAttribute('data-category-color'),
          categoryDescription: editBtn.getAttribute('data-category-description')
        });
        this.showEditCategoryModal(editBtn);
        return;
      }
    };
    
    // 绑定新的事件处理器
    container.addEventListener('click', handler);
    container._categoryEventHandler = handler;
    
    // 初始化拖拽功能
    this.initDragAndDrop(container);
    
    console.log('分类管理事件绑定完成');
  },

  // 初始化拖拽功能
  initDragAndDrop(container) {
    const items = container.querySelectorAll('.manage-category-item');
    
    items.forEach(item => {
      // 设置拖拽属性
      item.setAttribute('draggable', true);
      
      // 拖拽开始事件
      item.addEventListener('dragstart', (e) => {
        // 检查点击的是否是按钮，如果是则不启动拖拽
        if (e.target.classList.contains('btn-edit-category') || e.target.classList.contains('btn-delete-category')) {
          e.preventDefault();
          return;
        }
        
        e.dataTransfer.setData('text/plain', item.getAttribute('data-category-id'));
        item.classList.add('dragging');
        setTimeout(() => item.style.opacity = '0.7', 0);
      });
      
      // 拖拽结束事件
      item.addEventListener('dragend', () => {
        item.classList.remove('dragging');
        item.style.opacity = '';
        
        // 重新初始化拖拽功能，因为DOM可能已更改
        setTimeout(() => this.initDragAndDrop(container), 0);
      });
      
      // 拖拽进入事件
      item.addEventListener('dragover', (e) => {
        e.preventDefault();
        const afterElement = this.getDragAfterElement(container, e.clientY);
        const currentDragged = document.querySelector('.dragging');
        
        if (afterElement == null) {
          container.appendChild(currentDragged);
        } else {
          container.insertBefore(currentDragged, afterElement);
        }
      });
    });
    
    // 容器的拖放事件
    container.addEventListener('drop', (e) => {
      e.preventDefault();
      
      // 保存新的分类顺序
      this.saveCategoryOrder(container);
    });
  },
  
  // 获取拖拽位置的元素
  getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.manage-category-item:not(.dragging)')];
    
    return draggableElements.reduce((closest, child) => {
      const box = child.getBoundingClientRect();
      const offset = y - box.top - box.height / 2;
      
      if (offset < 0 && offset > closest.offset) {
        return { offset: offset, element: child };
      } else {
        return closest;
      }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
  },
  
  // 保存分类顺序
  async saveCategoryOrder(container) {
    const items = container.querySelectorAll('.manage-category-item');
    const categoryIds = [];
    
    items.forEach(item => {
      const categoryId = item.getAttribute('data-category-id');
      if (categoryId) {
        categoryIds.push(categoryId);
      }
    });
    
    try {
      // 保存新的顺序到存储中
      await StorageManager.updateCategoryOrder(categoryIds);
      console.log('分类顺序已保存', categoryIds);
      
      // 通知UI更新
      document.dispatchEvent(new CustomEvent('categoriesReordered', { detail: { order: categoryIds } }));
      
      this.showNotification('分类顺序已保存', 'success');
    } catch (error) {
      console.error('保存分类顺序失败:', error);
      this.showNotification('保存分类顺序失败', 'error');
    }
  },
  
  // 显示编辑分类模态框
  showEditCategoryModal(editBtn) {
    const categoryId = editBtn.getAttribute('data-category-id');
    const categoryName = editBtn.getAttribute('data-category-name');
    const categoryIcon = editBtn.getAttribute('data-category-icon');
    const categoryColor = editBtn.getAttribute('data-category-color');
    const categoryDescription = editBtn.getAttribute('data-category-description');
    
    // 创建编辑分类的模态框
    this.createEditCategoryModal();
    
    // 显示模态框并填充数据
    const modal = document.getElementById('editCategoryModal');
    if (modal) {
      document.getElementById('editCategoryId').value = categoryId;
      document.getElementById('editCategoryName').value = categoryName;
      document.getElementById('editCategoryIcon').value = categoryIcon;
      
      // 设置颜色选择
      const colorRadio = modal.querySelector(`input[name="editCategoryColor"][value="${categoryColor}"]`);
      if (colorRadio) {
        colorRadio.checked = true;
      }
      
      document.getElementById('editCategoryDescription').value = categoryDescription || '';
      
      modal.style.display = 'flex';
      modal.style.opacity = '1';
      modal.style.visibility = 'visible';
      
      const content = modal.querySelector('.modal-content');
      if (content) {
        content.style.transform = 'scale(1) translateY(0)';
        content.style.opacity = '1';
      }
      
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
    }
  },
  
  // 创建编辑分类模态框
  createEditCategoryModal() {
    // 检查是否已经创建过模态框
    if (document.getElementById('editCategoryModal')) {
      return;
    }
    
    const modalHtml = `
      <div id="editCategoryModal" class="modal" style="display: none; z-index: 1200;">
        <div class="modal-content">
          <div class="modal-header">
            <h3>编辑分类</h3>
            <button class="modal-close">
              <svg class="icon" viewBox="0 0 24 24">
                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
              </svg>
            </button>
          </div>
          
          <div class="modal-body">
            <form id="editCategoryForm">
              <input type="hidden" id="editCategoryId">
              
              <div class="form-group">
                <label for="editCategoryName">分类名称 *</label>
                <input type="text" id="editCategoryName" required placeholder="如：工作、学习、娱乐" maxlength="20">
                <small>最多20个字符，用于标识分类</small>
              </div>
              
              <div class="form-group">
                <label for="editCategoryIcon">分类图标</label>
                <select id="editCategoryIcon">
                  <option value="📁">📁 文件夹</option>
                  <option value="💼">💼 工作</option>
                  <option value="📚">📚 学习</option>
                  <option value="🎮">🎮 娱乐</option>
                  <option value="🛒">🛒 购物</option>
                  <option value="🏥">🏥 健康</option>
                  <option value="💰">💰 金融</option>
                  <option value="🍔">🍔 美食</option>
                  <option value="✈️">✈️ 旅行</option>
                  <option value="🎵">🎵 音乐</option>
                  <option value="📸">📸 摄影</option>
                  <option value="⚽">⚽ 运动</option>
                  <option value="🔧">🔧 工具</option>
                  <option value="📰">📰 新闻</option>
                  <option value="🎨">🎨 设计</option>
                </select>
                <small>选择一个代表性图标</small>
              </div>
              
              <div class="form-group">
                <label for="editCategoryColor">分类颜色</label>
                <div class="color-picker">
                  <input type="radio" name="editCategoryColor" value="#4285f4" id="editColor1" checked>
                  <label for="editColor1" class="color-option" style="background: #4285f4;"></label>
                  
                  <input type="radio" name="editCategoryColor" value="#34a853" id="editColor2">
                  <label for="editColor2" class="color-option" style="background: #34a853;"></label>
                  
                  <input type="radio" name="editCategoryColor" value="#ea4335" id="editColor3">
                  <label for="editColor3" class="color-option" style="background: #ea4335;"></label>
                  
                  <input type="radio" name="editCategoryColor" value="#fbbc04" id="editColor4">
                  <label for="editColor4" class="color-option" style="background: #fbbc04;"></label>
                  
                  <input type="radio" name="editCategoryColor" value="#9c27b0" id="editColor5">
                  <label for="editColor5" class="color-option" style="background: #9c27b0;"></label>
                  
                  <input type="radio" name="editCategoryColor" value="#ff5722" id="editColor6">
                  <label for="editColor6" class="color-option" style="background: #ff5722;"></label>
                  
                  <input type="radio" name="editCategoryColor" value="#607d8b" id="editColor7">
                  <label for="editColor7" class="color-option" style="background: #607d8b;"></label>
                  
                  <input type="radio" name="editCategoryColor" value="#795548" id="editColor8">
                  <label for="editColor8" class="color-option" style="background: #795548;"></label>
                </div>
                <small>选择分类的主题颜色</small>
              </div>
              
              <div class="form-group">
                <label for="editCategoryDescription">分类描述</label>
                <textarea id="editCategoryDescription" placeholder="可选的分类描述" maxlength="100"></textarea>
                <small>最多100个字符，描述分类用途</small>
              </div>
            </form>
          </div>
          
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" id="cancelEditCategory">取消</button>
            <button type="submit" form="editCategoryForm" class="btn btn-primary">保存</button>
          </div>
        </div>
      </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // 绑定编辑分类表单事件
    this.bindEditCategoryEvents();
  },
  
  // 绑定编辑分类表单事件
  bindEditCategoryEvents() {
    const editForm = document.getElementById('editCategoryForm');
    if (!editForm) return;
    
    editForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      await this.handleEditCategory();
    });
    
    // 绑定取消按钮事件
    const cancelBtn = document.getElementById('cancelEditCategory');
    if (cancelBtn) {
      cancelBtn.addEventListener('click', () => {
        const modal = document.getElementById('editCategoryModal');
        if (modal) {
          modal.style.display = 'none';
          // 恢复背景滚动
          document.body.style.overflow = '';
        }
      });
    }
    
    // 绑定关闭按钮事件
    const closeButtons = document.querySelectorAll('#editCategoryModal .modal-close');
    closeButtons.forEach(button => {
      button.addEventListener('click', () => {
        const modal = document.getElementById('editCategoryModal');
        if (modal) {
          modal.style.display = 'none';
          // 恢复背景滚动
          document.body.style.overflow = '';
        }
      });
    });
  },
  
  // 处理编辑分类
  async handleEditCategory() {
    const categoryId = document.getElementById('editCategoryId').value;
    const categoryName = document.getElementById('editCategoryName').value.trim();
    const categoryIcon = document.getElementById('editCategoryIcon').value;
    const categoryColor = document.querySelector('input[name="editCategoryColor"]:checked').value;
    const categoryDescription = document.getElementById('editCategoryDescription').value.trim();
    
    if (!categoryName) {
      this.showNotification('请输入分类名称！', 'error');
      return;
    }
    
    try {
      // 更新分类信息
      const updatedCategory = await StorageManager.updateCategory(categoryId, {
        name: categoryName,
        icon: categoryIcon,
        color: categoryColor,
        description: categoryDescription
      });
      
      this.showNotification('分类信息已更新！', 'success');
      
      // 关闭模态框
      const modal = document.getElementById('editCategoryModal');
      if (modal) {
        modal.style.display = 'none';
        // 恢复背景滚动
        document.body.style.overflow = '';
      }
      
      // 刷新分类管理列表
      await this.loadCategoriesForManagement();
      
      // 刷新分类导航栏
      await this.refreshCategoriesNav();
      
      // 更新分类选项
      await this.updateCategoryOptions();
      
      // 触发自定义事件
      document.dispatchEvent(new CustomEvent('categoryUpdated', { 
        detail: { updatedCategory } 
      }));
      
    } catch (error) {
      console.error('更新分类失败:', error);
      this.showNotification('更新分类失败，请重试！', 'error');
    }
  },

  // 显示书签导入模态框
  showImportBookmarksModal() {
    const modal = document.getElementById('importBookmarksModal');
    if (modal) {
      // 隐藏管理分类模态框
      this.hide('manageCategoryModal');
      
      // 显示书签导入模态框
      modal.style.display = 'flex';
      
      // 重置状态
      this.resetImportState();
      
      // 防止背景滚动
      document.body.style.overflow = 'hidden';
      
      console.log('书签导入模态框已显示');
    }
  },

  // 关闭书签导入模态框
  closeImportBookmarksModal() {
    const modal = document.getElementById('importBookmarksModal');
    if (modal) {
      modal.style.display = 'none';
      
      // 显示管理分类模态框
      this.showManageCategoryModal();
      
      console.log('书签导入模态框已关闭');
    }
  },

  // 重置导入状态
  resetImportState() {
    // 重置选项
    const createCategoriesCheckbox = document.getElementById('createCategoriesFromFolders');
    const importStructureCheckbox = document.getElementById('importFolderStructure');
    if (createCategoriesCheckbox) createCategoriesCheckbox.checked = true;
    if (importStructureCheckbox) importStructureCheckbox.checked = true;
    
    // 清空书签树
    const bookmarkTree = document.getElementById('bookmarkTree');
    if (bookmarkTree) {
      bookmarkTree.innerHTML = `
        <div class="tree-placeholder">
          <div class="placeholder-icon">
            <svg class="icon" viewBox="0 0 24 24">
              <path d="M17,3H7A2,2 0 0,0 5,5V21L12,18L19,21V5A2,2 0 0,0 17,3M17,18L12,15.82L7,18V5H17V18Z"/>
            </svg>
          </div>
          <h4>点击"加载书签"开始</h4>
          <p>加载您的Chrome书签，选择要导入的文件夹和链接</p>
        </div>
      `;
    }
    
    // 隐藏进度条和统计
    const importProgress = document.getElementById('importProgress');
    const importSummary = document.getElementById('importSummary');
    if (importProgress) importProgress.style.display = 'none';
    if (importSummary) importSummary.style.display = 'none';
    
    // 禁用导入按钮
    const importBtn = document.getElementById('importSelectedBtn');
    if (importBtn) importBtn.disabled = true;
    
    // 清空选中数据
    this.selectedBookmarks = {
      folders: [],
      links: [],
      categories: []
    };
  },

  // 加载书签
  async loadBookmarks() {
    await BookmarkImporter.loadBookmarks();
  },

  // 导入选中的书签
  async importSelectedBookmarks() {
    try {
      const importBtn = document.getElementById('importSelectedBtn');
      const progressDiv = document.getElementById('importProgress');
      const progressFill = document.getElementById('progressFill');
      const progressText = document.getElementById('progressText');
      
      if (importBtn) {
        importBtn.disabled = true;
        importBtn.textContent = '导入中...';
      }
      
      if (progressDiv) {
        progressDiv.style.display = 'block';
      }
      
      const createCategories = document.getElementById('createCategoriesFromFolders')?.checked;
      
      // 调试信息：显示选中的书签信息
      BookmarkImporter.debugSelectedBookmarks();
      
      // 获取完整的书签树数据，为建立父子关系做准备
      const bookmarkTree = await chrome.bookmarks.getTree();
      const folderMap = new Map(); // 文件夹ID到文件夹信息的映射
      const categoryMap = new Map(); // 文件夹ID到分类ID的映射
      
      // 递归构建文件夹映射
      this.buildFolderMap(bookmarkTree, folderMap);
      
      let currentProgress = 0;
      const totalSteps = BookmarkImporter.selectedBookmarks.folders.length + BookmarkImporter.selectedBookmarks.links.length;
      
      // 第一步：为选中的文件夹创建分类
      if (createCategories) {
        for (const folderId of BookmarkImporter.selectedBookmarks.folders) {
          try {
            const folderInfo = folderMap.get(folderId);
            if (folderInfo) {
              const categoryName = folderInfo.title || '未命名分类';
              
              // 检查是否已存在该分类
              const existingCategories = await StorageManager.getCategories();
              const existingCategory = existingCategories.find(cat => 
                cat.name.toLowerCase() === categoryName.toLowerCase()
              );
              
              let categoryId;
              if (existingCategory) {
                categoryId = existingCategory.id;
                console.log(`使用现有分类: ${categoryName} (ID: ${categoryId})`);
              } else {
                // 创建新分类
                const newCategory = await StorageManager.addCategory({
                  name: categoryName,
                  icon: '📁',
                  color: BookmarkImporter.getRandomColor(),
                  description: `从书签导入: ${categoryName}`
                });
                categoryId = newCategory.id;
                console.log(`创建新分类: ${categoryName} (ID: ${categoryId})`);
              }
              
              categoryMap.set(folderId, categoryId);
              console.log(`建立映射: 文件夹ID ${folderId} -> 分类ID ${categoryId}`);
            }
            
            currentProgress++;
            if (progressFill && progressText) {
              const percent = Math.round((currentProgress / totalSteps) * 100);
              progressFill.style.width = `${percent}%`;
              progressText.textContent = `正在创建分类... ${percent}%`;
            }
            
            await new Promise(resolve => setTimeout(resolve, 50));
          } catch (error) {
            console.error('创建分类失败:', folderId, error);
          }
        }
      }
      
      // 第二步：导入链接，直接关联到最近的父文件夹对应的分类
      for (const link of BookmarkImporter.selectedBookmarks.links) {
        try {
          let categoryId = null;
          let categoryName = '未分类';
          
          if (createCategories) {
            // 使用链接的直接父文件夹ID（最近的父级）
            const directParentId = link.parentFolderId;
            
            if (directParentId && categoryMap.has(directParentId)) {
              // 如果直接父文件夹已被选中且创建了分类
              categoryId = categoryMap.get(directParentId);
              const folderInfo = folderMap.get(directParentId);
              categoryName = folderInfo ? folderInfo.title : '未命名分类';
            } else if (directParentId) {
              // 如果直接父文件夹没有被选中，但用户希望创建分类
              // 需要为这个未选中的父文件夹创建分类
              const folderInfo = folderMap.get(directParentId);
              if (folderInfo) {
                const parentCategoryName = folderInfo.title || '未命名分类';
                
                // 检查是否已存在
                const existingCategories = await StorageManager.getCategories();
                const existingCategory = existingCategories.find(cat => 
                  cat.name.toLowerCase() === parentCategoryName.toLowerCase()
                );
                
                if (existingCategory) {
                  categoryId = existingCategory.id;
                } else {
                  // 创建新分类
                  const newCategory = await StorageManager.addCategory({
                    name: parentCategoryName,
                    icon: '📁',
                    color: BookmarkImporter.getRandomColor(),
                    description: `从书签导入: ${parentCategoryName} (自动创建)`
                  });
                  categoryId = newCategory.id;
                }
                
                categoryMap.set(directParentId, categoryId);
                categoryName = parentCategoryName;
                console.log(`自动为未选中的父文件夹创建分类: ${parentCategoryName} (ID: ${categoryId})`);
              }
            }
          }
          
          console.log(`导入链接: ${link.title} -> 分类: ${categoryName} (ID: ${categoryId || '无'})`);
          
          // 添加链接
          try {
            await StorageManager.addLink({
              url: link.url,
              title: link.title || '未命名链接',
              logo: BookmarkImporter.generateLogo(link.title || link.url),
              category: categoryId || '',
              categoryId: categoryId || '',
              note: '从书签导入',
              isQuickAccess: false
            });
          } catch (addError) {
            // 如果是重复链接，跳过并记录
            if (addError.name === 'DuplicateUrlError') {
              console.log(`跳过重复链接: ${link.title} - 已存在 "${addError.existingLink.title}"`);
            } else {
              // 其他错误也记录但不中断导入
              console.error('导入链接失败:', link, addError);
            }
          }
          
          currentProgress++;
          if (progressFill && progressText) {
            const percent = Math.round((currentProgress / totalSteps) * 100);
            progressFill.style.width = `${percent}%`;
            progressText.textContent = `正在导入链接... ${percent}%`;
          }
          
          await new Promise(resolve => setTimeout(resolve, 50));
        } catch (error) {
          console.error('导入链接失败:', link, error);
        }
      }
      
      // 完成导入
      if (progressFill && progressText) {
        progressFill.style.width = '100%';
        progressText.textContent = '导入完成！';
      }
      
      this.showNotification(`成功导入 ${BookmarkImporter.selectedBookmarks.links.length} 个链接和 ${BookmarkImporter.selectedBookmarks.folders.length} 个分类！`, 'success');
      
      // 刷新界面
      await this.refreshCategoriesNav();
      await this.updateCategoryOptions();
      
      // 触发事件
      document.dispatchEvent(new CustomEvent('bookmarksImported', {
        detail: {
          linksCount: BookmarkImporter.selectedBookmarks.links.length,
          categoriesCount: BookmarkImporter.selectedBookmarks.folders.length
        }
      }));
      
      // 延迟关闭
      setTimeout(() => {
        this.closeImportBookmarksModal();
      }, 2000);
      
    } catch (error) {
      console.error('导入书签失败:', error);
      this.showNotification('导入书签失败，请重试！', 'error');
    } finally {
      // 恢复按钮状态
      const importBtn = document.getElementById('importSelectedBtn');
      if (importBtn) {
        importBtn.disabled = false;
        importBtn.innerHTML = `
          <svg class="icon" viewBox="0 0 24 24">
            <path d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z"/>
          </svg>
          导入选中项
        `;
      }
    }
  },

  // 修复已导入链接的分类关联（解决category和categoryId不一致的问题）
  async fixImportedLinksCategories() {
    try {
      console.log('开始修复已导入链接的分类关联...');
      
      const links = await StorageManager.getLinks();
      let fixedCount = 0;
      
      for (const link of links) {
        // 检查是否存在category字段但categoryId为空的情况
        if (link.category && !link.categoryId) {
          console.log(`修复链接: ${link.title} - 设置categoryId为 ${link.category}`);
          
          // 更新链接，设置categoryId
          await StorageManager.updateLink(link.id, {
            categoryId: link.category
          });
          
          fixedCount++;
        }
        // 检查是否存在categoryId字段但category为空的情况
        else if (link.categoryId && !link.category) {
          console.log(`修复链接: ${link.title} - 设置category为 ${link.categoryId}`);
          
          // 更新链接，设置category
          await StorageManager.updateLink(link.id, {
            category: link.categoryId
          });
          
          fixedCount++;
        }
      }
      
      if (fixedCount > 0) {
        console.log(`已修复 ${fixedCount} 个链接的分类关联`);
        this.showNotification(`已修复 ${fixedCount} 个链接的分类关联`, 'success');
      } else {
        console.log('没有发现需要修复的链接');
      }
      
    } catch (error) {
      console.error('修复链接分类关联失败:', error);
    }
  },

  // 递归构建文件夹映射（ID -> 文件夹信息）
  buildFolderMap(nodes, folderMap, parentId = null) {
    if (!nodes || !Array.isArray(nodes)) return;
    
    nodes.forEach(node => {
      if (node.children) {
        // 这是一个文件夹
        folderMap.set(node.id, {
          id: node.id,
          title: node.title,
          parentId: parentId,
          url: node.url // 通常文件夹没有URL
        });
        
        // 递归处理子节点
        this.buildFolderMap(node.children, folderMap, node.id);
      } else if (node.url) {
        // 这是一个链接，也记录在映射中以便查找父文件夹
        folderMap.set(node.id, {
          id: node.id,
          title: node.title,
          parentId: parentId,
          url: node.url
        });
      }
    });
  },

  // 处理用户须知确认
  async handleWelcomeNoticeConfirm() {
    try {
      // 关闭模态框
      this.closeWelcomeNoticeModal();
      
      // 保存用户已查看须知的标记
      await StorageManager.updateSettings({
        hasSeenWelcomeNotice: true,
        welcomeNoticeSeenAt: new Date().toISOString()
      });
      
      console.log('用户已确认查看须知');
      
      // 可以触发一个自定义事件，通知其他组件
      document.dispatchEvent(new CustomEvent('welcomeNoticeConfirmed'));
      
    } catch (error) {
      console.error('保存用户须知状态失败:', error);
    }
  },
  
  // 处理保存个人信息
  async handleSavePersonalInfo() {
    try {
      const nicknameInput = document.getElementById('nickname');
      const birthDateInput = document.getElementById('birthDate');
      const genderSelect = document.getElementById('gender');
      const identitySelect = document.getElementById('identity');
      
      const nickname = nicknameInput ? nicknameInput.value.trim() : '';
      const birthDate = birthDateInput ? birthDateInput.value : '';
      const gender = genderSelect ? genderSelect.value : '';
      const identity = identitySelect ? identitySelect.value : '';
      
      // 验证昵称长度
      if (nickname && nickname.length > 20) {
        this.showNotification('昵称不能超过20个字符！', 'error');
        return;
      }
      
      // 准备要保存的设置对象
      const personalInfo = {};
      if (nickname !== undefined) {
        personalInfo.nickname = nickname;
      }
      if (birthDate !== undefined) {
        personalInfo.birthDate = birthDate;
      }
      if (gender !== undefined) {
        personalInfo.gender = gender;
      }
      if (identity !== undefined) {
        personalInfo.identity = identity;
      }
      
      // 保存到存储
      await StorageManager.updateSettings(personalInfo);
      
      this.showNotification('个人信息保存成功！', 'success');
      
      // 保存成功后刷新页面以更新生命统计数据
      setTimeout(() => {
        location.reload();
      }, 500); // 延迟500毫秒，让用户能看到成功提示
      
    } catch (error) {
      console.error('保存个人信息失败:', error);
      this.showNotification('保存个人信息失败，请重试！', 'error');
    }
  },
  
  // 显示个人信息模态框
  async showPersonalInfoModal() {
    // 创建个人信息模态框HTML
    const modalId = 'personalInfoModal';
    
    // 检查模态框是否已存在
    let modal = document.getElementById(modalId);
    if (!modal) {
      const modalHtml = `
        <div id="${modalId}" class="modal" style="display: none; z-index: 1200;">
          <div class="modal-content">
            <div class="modal-header">
              <h3>我的信息</h3>
              <button class="modal-close">
                <svg class="icon" viewBox="0 0 24 24">
                  <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                </svg>
              </button>
            </div>
            
            <div class="modal-body">
              <div class="personal-settings" id="personalSettings">
                <div class="setting-item">
                  <label for="nickname">昵称</label>
                  <input type="text" id="nickname" placeholder="请输入您的昵称" maxlength="20">
                  <small>设置您的个人昵称，用于个性化显示</small>
                </div>
                
                <div class="setting-item">
                  <label for="birthDate">出生日期</label>
                  <input type="date" id="birthDate">
                  <small>选择您的出生日期，用于个人信息管理</small>
                </div>
                
                <div class="setting-item">
                  <label for="gender">性别</label>
                  <select id="gender">
                    <option value="">请选择性别</option>
                    <option value="男">男</option>
                    <option value="女">女</option>
                  </select>
                  <small>选择您的性别</small>
                </div>
                
                <div class="setting-item">
                  <label for="identity">身份</label>
                  <select id="identity">
                    <option value="">请选择身份</option>
                    <option value="工人">工人</option>
                    <option value="干部">干部</option>
                    <option value="男职工">男职工</option>
                  </select>
                  <small>选择您的身份</small>
                </div>
                
                <div class="setting-item">
                  <button class="btn btn-primary" id="savePersonalInfo">保存个人信息</button>
                  <button class="btn btn-danger" id="deletePersonalInfo" style="margin-top: 10px;">删除个人信息</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      `;
      
      document.body.insertAdjacentHTML('beforeend', modalHtml);
      modal = document.getElementById(modalId);
    }
    
    // 绑定保存按钮事件
    const saveButton = document.getElementById('savePersonalInfo');
    if (saveButton && !saveButton.hasAttribute('data-bound')) {
      saveButton.addEventListener('click', () => this.handleSavePersonalInfo());
      saveButton.setAttribute('data-bound', 'true');
    }
    
    // 绑定删除按钮事件
    const deleteButton = document.getElementById('deletePersonalInfo');
    if (deleteButton && !deleteButton.hasAttribute('data-bound')) {
      deleteButton.addEventListener('click', () => this.handleDeletePersonalInfo());
      deleteButton.setAttribute('data-bound', 'true');
    }
    
    // 绑定关闭按钮事件
    const closeButtons = modal.querySelectorAll('.modal-close, .modal-footer .btn-secondary');
    closeButtons.forEach(button => {
      if (!button.hasAttribute('data-bound')) {
        button.addEventListener('click', () => {
          this.hide(modalId);
          // 关闭模态框后刷新页面以更新生命统计数据
          setTimeout(() => {
            location.reload();
          }, 300); // 延迟300毫秒，等待模态框关闭动画完成
        });
        button.setAttribute('data-bound', 'true');
      }
    });
    
    // 显示模态框
    modal.style.display = 'flex';
    
    // 加载当前设置值
    await this.loadCurrentSettings();
    
    // 防止背景滚动
    document.body.style.overflow = 'hidden';
  },
  
  // 处理删除个人信息
  async handleDeletePersonalInfo() {
    if (!confirm('确定要删除所有个人信息吗？此操作不可撤销。')) {
      return;
    }
    
    try {
      // 准备要清除的个人信息字段
      const personalInfoFields = {
        nickname: '',
        birthDate: '',
        gender: '',
        identity: ''
      };
      
      // 清除个人信息到存储
      await StorageManager.updateSettings(personalInfoFields);
      
      // 清空表单字段
      const nicknameInput = document.getElementById('nickname');
      const birthDateInput = document.getElementById('birthDate');
      const genderSelect = document.getElementById('gender');
      const identitySelect = document.getElementById('identity');
      
      if (nicknameInput) nicknameInput.value = '';
      if (birthDateInput) birthDateInput.value = '';
      if (genderSelect) genderSelect.value = '';
      if (identitySelect) identitySelect.value = '';
      
      this.showNotification('个人信息删除成功！', 'success');
      
      // 删除成功后刷新页面以更新生命统计数据
      setTimeout(() => {
        location.reload();
      }, 500); // 延迟500毫秒，让用户能看到成功提示
      
    } catch (error) {
      console.error('删除个人信息失败:', error);
      this.showNotification('删除个人信息失败，请重试！', 'error');
    }
  }
  
};