// 书签导入工具类
const BookmarkImporter = {
  selectedBookmarks: {
    folders: [],
    links: [],
    categories: []
  },

  // 加载书签
  async loadBookmarks() {
    try {
      const loadBtn = document.getElementById('loadBookmarksBtn');
      if (loadBtn) {
        loadBtn.disabled = true;
        loadBtn.textContent = '加载中...';
      }
      
      // 获取书签树
      const bookmarkTree = await chrome.bookmarks.getTree();
      console.log('书签数据:', bookmarkTree);
      
      // 渲染书签树
      this.renderBookmarkTree(bookmarkTree);
      
    } catch (error) {
      console.error('加载书签失败:', error);
      Modal.showNotification('加载书签失败，请检查权限设置', 'error');
    } finally {
      const loadBtn = document.getElementById('loadBookmarksBtn');
      if (loadBtn) {
        loadBtn.disabled = false;
        loadBtn.innerHTML = `
          <svg class="icon" viewBox="0 0 24 24">
            <path d="M12,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z"/>
          </svg>
          加载书签
        `;
      }
    }
  },

  // 渲染书签树
  renderBookmarkTree(bookmarkTree) {
    const container = document.getElementById('bookmarkTree');
    if (!container || !bookmarkTree || bookmarkTree.length === 0) return;
    
    container.innerHTML = '';
    
    // 初始化选中数据
    this.selectedBookmarks = {
      folders: [],
      links: [],
      categories: []
    };
    
    // 创建完整的书签映射，用于查找父子关系
    this.bookmarkMap = new Map();
    this.buildBookmarkMap(bookmarkTree);
    
    // 递归渲染书签节点
    bookmarkTree.forEach(rootNode => {
      if (rootNode.children) {
        rootNode.children.forEach(node => {
          this.renderBookmarkNode(node, container, 0, rootNode.id);
        });
      }
    });
    
    // 绑定事件
    this.bindBookmarkEvents();
  },

  // 构建书签映射关系
  buildBookmarkMap(bookmarkTree, parentId = null) {
    bookmarkTree.forEach(node => {
      // 保存节点及其父ID
      this.bookmarkMap.set(node.id, {
        ...node,
        parentId: parentId
      });
      
      // 递归处理子节点
      if (node.children && node.children.length > 0) {
        this.buildBookmarkMap(node.children, node.id);
      }
    });
  },

  // 渲染书签节点
  renderBookmarkNode(node, container, level, parentId = null) {
    if (!node) return;
    
    const nodeElement = document.createElement('div');
    nodeElement.className = `bookmark-tree-node level-${level}`;
    nodeElement.setAttribute('data-bookmark-id', node.id);
    nodeElement.setAttribute('data-level', level);
    
    if (node.children) {
      // 文件夹节点
      nodeElement.innerHTML = `
        <div class="bookmark-node bookmark-folder" data-folder-id="${node.id}">
          <label class="checkbox-group">
            <input type="checkbox" class="folder-checkbox" data-folder-id="${node.id}">
            <span class="checkmark"></span>
            <svg class="icon" viewBox="0 0 24 24">
              <path d="M10,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V8C22,6.89 21.1,6 20,6H12L10,4Z"/>
            </svg>
            <span class="bookmark-title">${node.title || '未命名文件夹'}</span>
            <span class="bookmark-count">(${this.countBookmarks(node)} 个链接)</span>
          </label>
        </div>
      `;
      
      container.appendChild(nodeElement);
      
      // 递归渲染子节点
      if (node.children && node.children.length > 0) {
        node.children.forEach(childNode => {
          this.renderBookmarkNode(childNode, container, level + 1, node.id);
        });
      }
    } else if (node.url) {
      // 链接节点，记录直接父文件夹ID
      nodeElement.innerHTML = `
        <div class="bookmark-node bookmark-link" data-link-id="${node.id}" data-parent-folder-id="${parentId || ''}">
          <label class="checkbox-group">
            <input type="checkbox" class="link-checkbox" 
                   data-link-id="${node.id}" 
                   data-url="${node.url}" 
                   data-title="${node.title || ''}" 
                   data-parent-folder-id="${parentId || ''}">
            <span class="checkmark"></span>
            <svg class="icon" viewBox="0 0 24 24">
              <path d="M16.36,14C16.44,13.34 16.5,12.68 16.5,12C16.5,11.32 16.44,10.66 16.36,10H19.74C19.9,10.64 20,11.31 20,12C20,12.69 19.9,13.36 19.74,14M14.59,19.56C15.19,18.45 15.65,17.25 15.97,16H18.92C17.96,17.65 16.43,18.93 14.59,19.56M14.34,14H9.66C9.56,13.34 9.5,12.68 9.5,12C9.5,11.32 9.56,10.65 9.66,10H14.34C14.43,10.65 14.5,11.32 14.5,12C14.5,12.68 14.43,13.34 14.34,14M12,19.96C11.17,18.76 10.5,17.43 10.09,16H13.91C13.5,17.43 12.83,18.76 12,19.96M8,8H5.08C6.03,6.34 7.57,5.06 9.4,4.44C8.8,5.55 8.35,6.75 8,8M5.08,16H8C8.35,17.25 8.8,18.45 9.4,19.56C7.57,18.93 6.03,17.65 5.08,16M4.26,14C4.1,13.36 4,12.69 4,12C4,11.31 4.1,10.64 4.26,10H7.64C7.56,10.66 7.5,11.32 7.5,12C7.5,12.68 7.56,13.34 7.64,14M12,4.03C12.83,5.23 13.5,6.57 13.91,8H10.09C10.5,6.57 11.17,5.23 12,4.03M18.92,8H15.97C15.65,6.75 15.19,5.55 14.59,4.44C16.43,5.07 17.96,6.34 18.92,8M12,2C6.47,2 2,6.5 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z"/>
            </svg>
            <div style="flex: 1; min-width: 0;">
              <div class="bookmark-title">${node.title || '无标题'}</div>
              <div class="bookmark-url">${node.url}</div>
            </div>
          </label>
        </div>
      `;
      
      container.appendChild(nodeElement);
    }
  },

  // 统计文件夹中的书签数量
  countBookmarks(node) {
    if (!node.children) return 0;
    
    let count = 0;
    node.children.forEach(child => {
      if (child.url) {
        count++;
      } else if (child.children) {
        count += this.countBookmarks(child);
      }
    });
    return count;
  },

  // 绑定书签事件
  bindBookmarkEvents() {
    const container = document.getElementById('bookmarkTree');
    if (!container) return;
    
    // 文件夹复选框事件
    container.addEventListener('change', (e) => {
      if (e.target.classList.contains('folder-checkbox')) {
        this.handleFolderCheckboxChange(e.target);
      } else if (e.target.classList.contains('link-checkbox')) {
        this.handleLinkCheckboxChange(e.target);
      }
      
      // 更新统计信息
      this.updateImportSummary();
    });
  },

  // 处理文件夹复选框变化
  handleFolderCheckboxChange(checkbox) {
    const folderId = checkbox.getAttribute('data-folder-id');
    const isChecked = checkbox.checked;
    
    // 更新子级复选框
    const container = document.getElementById('bookmarkTree');
    const folderNode = container.querySelector(`[data-folder-id="${folderId}"]`);
    
    if (folderNode) {
      // 找到该文件夹后的所有子节点
      let currentElement = folderNode.parentElement;
      const currentLevel = parseInt(currentElement.getAttribute('data-level'));
      
      let nextElement = currentElement.nextElementSibling;
      while (nextElement && parseInt(nextElement.getAttribute('data-level')) > currentLevel) {
        const childCheckbox = nextElement.querySelector('input[type="checkbox"]');
        if (childCheckbox) {
          childCheckbox.checked = isChecked;
          
          if (childCheckbox.classList.contains('link-checkbox')) {
            // 处理链接选择，使用直接父文件夹ID
            const linkId = childCheckbox.getAttribute('data-link-id');
            const url = childCheckbox.getAttribute('data-url');
            const title = childCheckbox.getAttribute('data-title');
            const directParentId = childCheckbox.getAttribute('data-parent-folder-id');
            
            if (isChecked) {
              const existingIndex = this.selectedBookmarks.links.findIndex(link => link.id === linkId);
              if (existingIndex === -1) {
                this.selectedBookmarks.links.push({
                  id: linkId,
                  url: url,
                  title: title,
                  parentFolderId: directParentId || null // 使用直接父文件夹ID，确保最近的父级
                });
              }
            } else {
              const index = this.selectedBookmarks.links.findIndex(link => link.id === linkId);
              if (index > -1) {
                this.selectedBookmarks.links.splice(index, 1);
              }
            }
          } else if (childCheckbox.classList.contains('folder-checkbox')) {
            const childFolderId = childCheckbox.getAttribute('data-folder-id');
            if (isChecked && !this.selectedBookmarks.folders.includes(childFolderId)) {
              this.selectedBookmarks.folders.push(childFolderId);
            } else if (!isChecked) {
              const index = this.selectedBookmarks.folders.indexOf(childFolderId);
              if (index > -1) {
                this.selectedBookmarks.folders.splice(index, 1);
              }
            }
          }
        }
        nextElement = nextElement.nextElementSibling;
      }
    }
    
    // 更新选中文件夹列表
    if (isChecked) {
      if (!this.selectedBookmarks.folders.includes(folderId)) {
        this.selectedBookmarks.folders.push(folderId);
      }
    } else {
      const index = this.selectedBookmarks.folders.indexOf(folderId);
      if (index > -1) {
        this.selectedBookmarks.folders.splice(index, 1);
      }
    }
  },

  // 处理链接复选框变化
  handleLinkCheckboxChange(checkbox) {
    const linkId = checkbox.getAttribute('data-link-id');
    const url = checkbox.getAttribute('data-url');
    const title = checkbox.getAttribute('data-title');
    const parentFolderId = checkbox.getAttribute('data-parent-folder-id'); // 直接从数据属性获取最近的父文件夹ID
    const isChecked = checkbox.checked;
    
    if (isChecked) {
      // 添加到选中列表
      const existingIndex = this.selectedBookmarks.links.findIndex(link => link.id === linkId);
      if (existingIndex === -1) {
        this.selectedBookmarks.links.push({
          id: linkId,
          url: url,
          title: title,
          parentFolderId: parentFolderId || null // 确保使用最近的父文件夹ID
        });
      }
    } else {
      // 从选中列表中移除
      const index = this.selectedBookmarks.links.findIndex(link => link.id === linkId);
      if (index > -1) {
        this.selectedBookmarks.links.splice(index, 1);
      }
    }
  },

  // 更新导入统计
  updateImportSummary() {
    const summaryDiv = document.getElementById('importSummary');
    const selectedFoldersCount = document.getElementById('selectedFoldersCount');
    const selectedLinksCount = document.getElementById('selectedLinksCount');
    const newCategoriesCount = document.getElementById('newCategoriesCount');
    const importBtn = document.getElementById('importSelectedBtn');
    
    if (!summaryDiv) return;
    
    const hasSelections = this.selectedBookmarks.links.length > 0 || this.selectedBookmarks.folders.length > 0;
    
    if (hasSelections) {
      summaryDiv.style.display = 'block';
      
      if (selectedFoldersCount) {
        selectedFoldersCount.textContent = this.selectedBookmarks.folders.length;
      }
      
      if (selectedLinksCount) {
        selectedLinksCount.textContent = this.selectedBookmarks.links.length;
      }
      
      // 计算新建分类数量
      const createCategories = document.getElementById('createCategoriesFromFolders')?.checked;
      if (createCategories && newCategoriesCount) {
        newCategoriesCount.textContent = this.selectedBookmarks.folders.length;
      } else if (newCategoriesCount) {
        newCategoriesCount.textContent = '0';
      }
      
      // 统计有父文件夹的链接数量（用于调试）
      const linksWithParent = this.selectedBookmarks.links.filter(link => link.parentFolderId).length;
      console.log(`选中的链接中，${linksWithParent} 个有父文件夹信息，${this.selectedBookmarks.links.length - linksWithParent} 个没有`);
      console.log('选中的链接详情:', this.selectedBookmarks.links.map(link => ({
        title: link.title,
        parentFolderId: link.parentFolderId
      })));
      
      // 启用导入按钮
      if (importBtn) {
        importBtn.disabled = false;
      }
    } else {
      summaryDiv.style.display = 'none';
      
      // 禁用导入按钮
      if (importBtn) {
        importBtn.disabled = true;
      }
    }
  },

  // 生成随机颜色
  getRandomColor() {
    const colors = [
      '#4285f4', '#ea4335', '#34a853', '#fbbc04', '#ff6d01',
      '#9c27b0', '#673ab7', '#3f51b5', '#2196f3', '#00bcd4',
      '#009688', '#4caf50', '#8bc34a', '#cddc39', '#ffeb3b',
      '#ffc107', '#ff9800', '#ff5722', '#795548', '#607d8b'
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  },

  // 生成Logo标识
  generateLogo(title) {
    if (!title) return '🔗';
    
    // 提取中文字符
    const chineseMatch = title.match(/[\u4e00-\u9fff]/);
    if (chineseMatch) {
      return chineseMatch[0];
    }
    
    // 提取英文字符
    const englishMatch = title.match(/[a-zA-Z]/);
    if (englishMatch) {
      return englishMatch[0].toUpperCase();
    }
    
    return '🔗';
  },

  // 查找链接的父文件夹ID
  findParentFolderId(linkElement) {
    let parentFolderId = null;
    let currentElement = linkElement.previousElementSibling;
    const currentLevel = parseInt(linkElement.getAttribute('data-level'));
    
    // 向上查找父级文件夹
    while (currentElement) {
      const elementLevel = parseInt(currentElement.getAttribute('data-level'));
      if (elementLevel < currentLevel) {
        const folderCheckbox = currentElement.querySelector('.folder-checkbox');
        if (folderCheckbox) {
          parentFolderId = folderCheckbox.getAttribute('data-folder-id');
          break;
        }
      }
      currentElement = currentElement.previousElementSibling;
    }
    
    return parentFolderId;
  },

  // 递归查找最近的被选中的父文件夹
  findSelectedParentFolder(linkElement) {
    let currentElement = linkElement.previousElementSibling;
    const currentLevel = parseInt(linkElement.getAttribute('data-level'));
    
    // 向上查找被选中的父级文件夹
    while (currentElement) {
      const elementLevel = parseInt(currentElement.getAttribute('data-level'));
      if (elementLevel < currentLevel) {
        const folderCheckbox = currentElement.querySelector('.folder-checkbox');
        if (folderCheckbox && folderCheckbox.checked) {
          return folderCheckbox.getAttribute('data-folder-id');
        }
      }
      currentElement = currentElement.previousElementSibling;
    }
    
    return null;
  },

  // 调试方法：打印选中的链接和其父文件夹信息
  debugSelectedBookmarks() {
    console.log('选中的文件夹:', this.selectedBookmarks.folders);
    console.log('选中的链接:');
    this.selectedBookmarks.links.forEach(link => {
      console.log(`  - ${link.title} (${link.url}) -> 父文件夹: ${link.parentFolderId || '无'}`);
    });
  }
};