// A1Tabs 后台服务工作线程
// A1Tabs 后台服务工作线程
// 处理插件生命周期、右键菜单、快捷键等
// 现在使用 IndexedDB 作为主要存储方案

// ====================
// Background IndexedDB 管理器 (内嵌版本)
// ====================
class BackgroundIndexedDBManager {
  constructor() {
    this.dbName = 'A1TabsDB';
    this.dbVersion = 2;
    this.db = null;
  }

  // 初始化数据库
  async init() {
    if (this.db) return this.db;

    return new Promise((resolve, reject) => {
      console.log('Background: 尝试打开IndexedDB，版本:', this.dbVersion);
      console.log('Background: 数据库名称:', this.dbName);
      const request = indexedDB.open(this.dbName, this.dbVersion);

      request.onerror = () => {
        console.error('Background IndexedDB打开失败:', request.error);
        console.error('Background: 请求版本:', this.dbVersion);
        console.error('Background: 数据库名称:', this.dbName);
        reject(request.error);
      };

      request.onsuccess = () => {
        this.db = request.result;
        console.log('Background IndexedDB初始化成功');
        resolve(this.db);
      };

      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        console.log('Background IndexedDB数据库升级，版本:', event.oldVersion, '->', event.newVersion);

        // 创建categories存储
        if (!db.objectStoreNames.contains('categories')) {
          const categoriesStore = db.createObjectStore('categories', { keyPath: 'id' });
          categoriesStore.createIndex('name', 'name', { unique: false });
          categoriesStore.createIndex('createdAt', 'createdAt', { unique: false });
        }

        // 创建links存储
        if (!db.objectStoreNames.contains('links')) {
          const linksStore = db.createObjectStore('links', { keyPath: 'id' });
          linksStore.createIndex('categoryId', 'categoryId', { unique: false });
          linksStore.createIndex('category', 'category', { unique: false });
          linksStore.createIndex('title', 'title', { unique: false });
          linksStore.createIndex('url', 'url', { unique: false });
          linksStore.createIndex('isQuickAccess', 'isQuickAccess', { unique: false });
          linksStore.createIndex('visitCount', 'visitCount', { unique: false });
          linksStore.createIndex('createdAt', 'createdAt', { unique: false });
          linksStore.createIndex('lastVisited', 'lastVisited', { unique: false });
        }

        // 创建settings存储
        if (!db.objectStoreNames.contains('settings')) {
          const settingsStore = db.createObjectStore('settings', { keyPath: 'key' });
        }

        // 创建metadata存储
        if (!db.objectStoreNames.contains('metadata')) {
          const metadataStore = db.createObjectStore('metadata', { keyPath: 'key' });
        }

        // 创建todos存储
        if (!db.objectStoreNames.contains('todos')) {
          const todosStore = db.createObjectStore('todos', { keyPath: 'id' });
          todosStore.createIndex('createdAt', 'createdAt', { unique: false });
          todosStore.createIndex('completed', 'completed', { unique: false });
        }
      };
    });
  }

  // 获取单个对象存储
  async getStore(storeName, mode = 'readonly') {
    await this.init();
    const transaction = this.db.transaction([storeName], mode);
    return transaction.objectStore(storeName);
  }

  // 生成唯一ID
  generateUniqueId(prefix = 'link') {
    const timestamp = Date.now().toString(36);
    const randomStr = Math.random().toString(36).substr(2, 9);
    const extraRandom = Math.floor(Math.random() * 1000).toString(36);
    return `${prefix}_${timestamp}_${randomStr}_${extraRandom}`;
  }

  // 生成Logo
  generateLogo(title) {
    if (!title || !title.trim()) return '?';
    
    const cleanTitle = title.trim();
    
    // 检查是否包含中文字符
    const chineseMatch = cleanTitle.match(/[一-龥]/);
    if (chineseMatch) return chineseMatch[0];
    
    // 处理英文单词
    const words = cleanTitle.split(/\s+/).filter(word => word.length > 0);
    if (words.length >= 2) {
      return (words[0][0] + words[1][0]).toUpperCase();
    } else if (words.length === 1) {
      const word = words[0];
      if (word.length >= 2) {
        return word.substring(0, 1).toUpperCase() + word.substring(1, 2).toLowerCase();
      } else {
        return word.charAt(0).toUpperCase();
      }
    }
    
    return '?';
  }

  // === 链接管理 ===

  // 获取所有链接
  async getLinks() {
    const store = await this.getStore('links');
    
    return new Promise((resolve, reject) => {
      const request = store.getAll();
      
      request.onsuccess = () => {
        resolve(request.result || []);
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 添加链接
  async addLink(link) {
    // 首先检查URL是否已存在
    const existingLinks = await this.getLinks();
    const duplicateLink = existingLinks.find(existingLink => 
      existingLink.url === link.url
    );
    
    if (duplicateLink) {
      // 如果链接已存在，抛出一个特殊的错误
      const error = new Error(`链接 "${duplicateLink.title}" 已存在`);
      error.name = 'DuplicateUrlError';
      error.existingLink = duplicateLink;
      throw error;
    }
    
    // 生成唯一ID，避免冲突
    let linkId = link.id;
    if (!linkId) {
      linkId = this.generateUniqueId();
    }
    
    // 检查ID是否已存在，如果存在则生成新ID
    while (existingLinks.some(existingLink => existingLink.id === linkId)) {
      linkId = this.generateUniqueId();
    }
    
    const newLink = {
      id: linkId,
      url: link.url,
      title: link.title,
      logo: link.logo || this.generateLogo(link.title),
      category: link.category || '',
      categoryId: link.categoryId || '',
      note: link.note || '',
      isQuickAccess: link.isQuickAccess || false,
      visitCount: 0,
      createdAt: link.createdAt || link.createTime || new Date().toISOString(),
      lastVisited: null
    };

    const store = await this.getStore('links', 'readwrite');
    
    return new Promise((resolve, reject) => {
      const request = store.add(newLink);
      
      request.onsuccess = () => {
        console.log('Background IndexedDB: 成功添加链接', newLink.title);
        resolve(newLink);
      };
      
      request.onerror = () => {
        console.error('Background IndexedDB: 添加链接失败', request.error);
        reject(request.error);
      };
    });
  }

  // 更新链接
  async updateLink(linkId, updates) {
    const store = await this.getStore('links', 'readwrite');
    
    return new Promise((resolve, reject) => {
      const getRequest = store.get(linkId);
      
      getRequest.onsuccess = () => {
        const link = getRequest.result;
        if (!link) {
          reject(new Error('链接不存在'));
          return;
        }
        
        const updatedLink = { ...link, ...updates };
        const putRequest = store.put(updatedLink);
        
        putRequest.onsuccess = () => {
          resolve(updatedLink);
        };
        
        putRequest.onerror = () => {
          reject(putRequest.error);
        };
      };
      
      getRequest.onerror = () => {
        reject(getRequest.error);
      };
    });
  }

  // 删除链接
  async deleteLink(linkId) {
    const store = await this.getStore('links', 'readwrite');
    
    return new Promise((resolve, reject) => {
      const request = store.delete(linkId);
      
      request.onsuccess = () => {
        console.log('Background IndexedDB: 成功删除链接', linkId);
        resolve();
      };
      
      request.onerror = () => {
        console.error('Background IndexedDB: 删除链接失败', request.error);
        reject(request.error);
      };
    });
  }

  // === 分类管理 ===

  // 获取所有分类
  async getCategories() {
    const store = await this.getStore('categories');
    
    return new Promise((resolve, reject) => {
      const request = store.getAll();
      
      request.onsuccess = () => {
        resolve(request.result || []);
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // === 待办事项管理 ===

  // 获取待办事项
  async getTodos() {
    // 检查数据库是否包含todos存储
    if (!this.db.objectStoreNames.contains('todos')) {
      return [];
    }
    
    const store = await this.getStore('todos');
    
    return new Promise((resolve, reject) => {
      const request = store.getAll();
      
      request.onsuccess = () => {
        resolve(request.result || []);
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 保存待办事项
  async saveTodos(todos) {
    // 检查数据库是否包含todos存储
    if (!this.db.objectStoreNames.contains('todos')) {
      console.warn('todos存储不存在，跳过保存');
      return;
    }
    
    const transaction = this.db.transaction(['todos'], 'readwrite');
    
    return new Promise((resolve, reject) => {
      const todosStore = transaction.objectStore('todos');
      
      // 清空现有待办事项
      todosStore.clear();
      
      transaction.oncomplete = () => {
        resolve();
      };
      
      transaction.onerror = () => {
        reject(transaction.error);
      };
      
      // 添加新的待办事项
      if (Array.isArray(todos)) {
        todos.forEach(todo => {
          todosStore.add(todo);
        });
      }
    });
  }

  // === 设置管理 ===

  // 获取设置
  async getSettings() {
    const store = await this.getStore('settings');
    
    return new Promise((resolve, reject) => {
      const request = store.get('userSettings');
      
      request.onsuccess = () => {
        const result = request.result;
        resolve(result ? result.value : {
          theme: 'light',
          defaultView: 'grid',
          searchEngine: 'bing',
          backgroundType: 'default',
          autoCapture: true,
          showVisitCount: true
        });
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 保存设置
  async saveSettings(settings) {
    const store = await this.getStore('settings', 'readwrite');
    
    return new Promise((resolve, reject) => {
      const request = store.put({
        key: 'userSettings',
        value: settings,
        updatedAt: new Date().toISOString()
      });
      
      request.onsuccess = () => {
        resolve();
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // === 数据同步和迁移 ===

  // 检查是否需要从 Chrome Storage 迁移
  async checkMigrationNeeded() {
    try {
      const links = await this.getLinks();
      const categories = await this.getCategories();
      
      // 如果IndexedDB中已有数据，则不需要迁移
      if (links.length > 0 || categories.length > 0) {
        return false;
      }
      
      // 检查Chrome Storage中是否有数据
      const chromeData = await chrome.storage.sync.get(['links', 'categories']);
      return (chromeData.links && chromeData.links.length > 0) || 
             (chromeData.categories && chromeData.categories.length > 0);
    } catch (error) {
      console.error('检查迁移状态失败:', error);
      return false;
    }
  }

  // 从 Chrome Storage 迁移数据
  async migrateFromChromeStorage() {
    try {
      console.log('开始从 Chrome Storage 迁移数据到 IndexedDB...');
      
      const chromeData = await chrome.storage.sync.get(['links', 'categories', 'settings']);
      
      // 迁移分类
      if (chromeData.categories && chromeData.categories.length > 0) {
        const categoriesStore = await this.getStore('categories', 'readwrite');
        
        for (const category of chromeData.categories) {
          try {
            await new Promise((resolve, reject) => {
              const request = categoriesStore.add(category);
              request.onsuccess = () => resolve();
              request.onerror = () => reject(request.error);
            });
            console.log('迁移分类:', category.name);
          } catch (error) {
            console.warn('迁移分类失败:', category.name, error);
          }
        }
      }
      
      // 迁移链接
      if (chromeData.links && chromeData.links.length > 0) {
        const linksStore = await this.getStore('links', 'readwrite');
        
        for (const link of chromeData.links) {
          try {
            // 确保链接对象有必要的字段
            const migratedLink = {
              ...link,
              createdAt: link.createTime || link.createdAt || new Date().toISOString(),
              lastVisited: link.lastVisited || null
            };
            
            await new Promise((resolve, reject) => {
              const request = linksStore.add(migratedLink);
              request.onsuccess = () => resolve();
              request.onerror = () => reject(request.error);
            });
            console.log('迁移链接:', link.title);
          } catch (error) {
            console.warn('迁移链接失败:', link.title, error);
          }
        }
      }
      
      // 迁移设置
      if (chromeData.settings) {
        await this.saveSettings(chromeData.settings);
        console.log('迁移设置完成');
      }
      
      // 标记迁移完成
      await chrome.storage.local.set({ indexeddb_migrated: true });
      console.log('数据迁移完成');
      
      return true;
    } catch (error) {
      console.error('数据迁移失败:', error);
      return false;
    }
  }
}

// ====================
// 结束 IndexedDB 管理器
// ====================

// 创建 IndexedDB 管理器实例，添加安全检查
let dbManager = null;
let indexedDBAvailable = true;

console.log('🔧 正在创建 IndexedDB 管理器...');
console.log('🔍 检查 BackgroundIndexedDBManager 类定义:', {
  type: typeof BackgroundIndexedDBManager,
  isFunction: typeof BackgroundIndexedDBManager === 'function',
  isUndefined: typeof BackgroundIndexedDBManager === 'undefined'
});

try {
  // 确保 BackgroundIndexedDBManager 类已定义
  if (typeof BackgroundIndexedDBManager === 'function') {
    dbManager = new BackgroundIndexedDBManager();
    console.log('✅ BackgroundIndexedDBManager 实例创建成功，版本:', dbManager.dbVersion);
  } else {
    console.error('❌ BackgroundIndexedDBManager 类未定义，类型:', typeof BackgroundIndexedDBManager);
    console.error('🔍 全局对象检查:', {
      hasWindow: typeof window !== 'undefined',
      hasSelf: typeof self !== 'undefined',
      hasGlobal: typeof global !== 'undefined'
    });
    indexedDBAvailable = false;
  }
} catch (error) {
  console.error('❌ 创建 IndexedDB 管理器失败:', error);
  console.error('🔍 错误详情:', {
    name: error.name,
    message: error.message,
    stack: error.stack
  });
  indexedDBAvailable = false;
}

// 设置全局标志
self.indexedDBAvailable = indexedDBAvailable;
self.dbManager = dbManager;

// 检查链接是否已存在
async function checkLinkExists(url) {
  try {
    // 先检查 IndexedDB
    if (dbManager && typeof dbManager.getLinkByUrl === 'function') {
      try {
        await dbManager.init(); // 确保初始化
        const indexedDBLink = await dbManager.getLinkByUrl(url);
        if (indexedDBLink) {
          return indexedDBLink;
        }
      } catch (error) {
        console.warn('Background: 检查 IndexedDB 中的链接失败:', error);
      }
    }
    
    // 再检查 Chrome Storage
    try {
      const result = await chrome.storage.sync.get(['links']);
      const links = result.links || [];
      const existingLink = links.find(link => link.url === url);
      if (existingLink) {
        return existingLink;
      }
    } catch (error) {
      console.warn('Background: 检查 Chrome Storage 中的链接失败:', error);
    }
    
    // 如果都没有找到，返回 null
    return null;
  } catch (error) {
    console.error('Background: 检查链接存在性失败:', error);
    return null;
  }
}

// 工具函数
function generateId(prefix = '') {
  const timestamp = Date.now().toString(36);
  const randomStr = Math.random().toString(36).substr(2, 9);
  return `${prefix}${timestamp}_${randomStr}`;
}

function generateLogoFromTitle(title) {
  if (!title || !title.trim()) return '?';
  
  const cleanTitle = title.trim();
  
  // 检查是否包含中文字符
  const chineseMatch = cleanTitle.match(/[一-龥]/);
  if (chineseMatch) return chineseMatch[0];
  
  // 处理英文单词
  const words = cleanTitle.split(/\s+/).filter(word => word.length > 0);
  if (words.length >= 2) {
    return (words[0][0] + words[1][0]).toUpperCase();
  } else if (words.length === 1) {
    const word = words[0];
    if (word.length >= 2) {
      return word.substring(0, 1).toUpperCase() + word.substring(1, 2).toLowerCase();
    } else {
      return word.charAt(0).toUpperCase();
    }
  }
  
  return '?';
}

// 插件安装时初始化
chrome.runtime.onInstalled.addListener(async (details) => {
  console.log('A1Tabs 插件已安装');
  
  try {
    // 检查 IndexedDB 是否可用
    if (dbManager && typeof dbManager.init === 'function') {
      // 初始化 IndexedDB
      await dbManager.init();
      console.log('✅ IndexedDB 初始化成功');
      
      // 检查是否需要从 Chrome Storage 迁移数据
      const needsMigration = await dbManager.checkMigrationNeeded();
      if (needsMigration) {
        console.log('检测到 Chrome Storage 中有数据，开始迁移...');
        await dbManager.migrateFromChromeStorage();
      }
      
      // 初始化默认数据
      await initializeDefaultData();
      
      // 确保 IndexedDB 完全初始化后再执行同步
      setTimeout(async () => {
        try {
          await syncChromeStorageToIndexedDB();
        } catch (syncError) {
          console.warn('Background: 数据同步失败:', syncError.message);
        }
      }, 1000);
    } else {
      console.warn('⚠️ IndexedDB 不可用，使用 Chrome Storage 作为后备');
      await initializeDefaultDataWithChromeStorage();
    }
    
    // 创建右键菜单
    createContextMenus();
    
    if (details.reason === 'install') {
      // 首次安装时打开新标签页
      chrome.tabs.create({
        url: chrome.runtime.getURL('newtab.html')
      });
    }
  } catch (error) {
    console.error('❌ A1Tabs 初始化失败:', error);
    // 即使初始化失败，也要创建右键菜单
    createContextMenus();
  }
});

// 初始化默认数据 - 现在使用 IndexedDB
async function initializeDefaultData() {
  try {
    if (!dbManager) {
      console.warn('⚠️ dbManager 不可用，跳过 IndexedDB 初始化');
      return;
    }
    
    // 检查 IndexedDB 中是否已有数据
    const [categories, links, settings] = await Promise.all([
      dbManager.getCategories(),
      dbManager.getLinks(),
      dbManager.getSettings()
    ]);
    
    // 如果没有分类，创建默认分类
    if (categories.length === 0) {
      const defaultCategories = [
        {
          id: 'cat_work',
          name: '工作',
          icon: '💼',
          color: '#4285f4',
          createdAt: new Date().toISOString(),
          linkCount: 0
        },
        {
          id: 'cat_study',
          name: '学习',
          icon: '📚',
          color: '#34a853',
          createdAt: new Date().toISOString(),
          linkCount: 0
        },
        {
          id: 'cat_entertainment',
          name: '娱乐',
          icon: '🎉',
          color: '#ea4335',
          createdAt: new Date().toISOString(),
          linkCount: 0
        },
        {
          id: 'cat_tools',
          name: '工具',
          icon: '🔧',
          color: '#fbbc04',
          createdAt: new Date().toISOString(),
          linkCount: 0
        }
      ];
      
      // 使用 IndexedDB 添加默认分类
      for (const category of defaultCategories) {
        try {
          const store = await dbManager.getStore('categories', 'readwrite');
          await new Promise((resolve, reject) => {
            const request = store.add(category);
            request.onsuccess = () => resolve();
            request.onerror = () => reject(request.error);
          });
          console.log('创建默认分类:', category.name);
        } catch (error) {
          console.warn('创建默认分类失败:', category.name, error);
        }
      }
    }
    
    // 检查设置，如果没有则创建默认设置
    if (!settings || Object.keys(settings).length === 0) {
      const defaultSettings = {
        theme: 'light',
        defaultView: 'grid',
        searchEngine: 'bing',
        backgroundType: 'default',
        shortcuts: {
          openPanel: 'Ctrl+Shift+T'
        },
        autoCapture: true,
        showVisitCount: true
      };
      
      await dbManager.saveSettings(defaultSettings);
      console.log('创建默认设置完成');
    }
    
    console.log('✅ IndexedDB 默认数据初始化完成');
  } catch (error) {
    console.error('❌ 初始化默认数据失败:', error);
  }
}

// Chrome Storage 降级方案
async function initializeDefaultDataWithChromeStorage() {
  try {
    console.log('使用 Chrome Storage 初始化默认数据...');
    
    const result = await chrome.storage.sync.get(['categories', 'links', 'settings']);
    
    // 如果没有数据，创建默认分类和设置
    if (!result.categories) {
      const defaultCategories = [
        {
          id: 'cat_work',
          name: '工作',
          icon: '💼',
          color: '#4285f4',
          createdAt: new Date().toISOString(),
          linkCount: 0
        },
        {
          id: 'cat_study',
          name: '学习',
          icon: '📚',
          color: '#34a853',
          createdAt: new Date().toISOString(),
          linkCount: 0
        },
        {
          id: 'cat_entertainment',
          name: '娱乐',
          icon: '🎉',
          color: '#ea4335',
          createdAt: new Date().toISOString(),
          linkCount: 0
        },
        {
          id: 'cat_tools',
          name: '工具',
          icon: '🔧',
          color: '#fbbc04',
          createdAt: new Date().toISOString(),
          linkCount: 0
        }
      ];
      
      await chrome.storage.sync.set({ categories: defaultCategories });
    }
    
    if (!result.links) {
      await chrome.storage.sync.set({ links: [] });
    }
    
    if (!result.settings) {
      const defaultSettings = {
        theme: 'light',
        defaultView: 'grid',
        searchEngine: 'bing',
        backgroundType: 'default',
        shortcuts: {
          openPanel: 'Ctrl+Shift+T'
        },
        autoCapture: true,
        showVisitCount: true
      };
      
      await chrome.storage.sync.set({ settings: defaultSettings });
    }
    
    console.log('✅ Chrome Storage 默认数据初始化完成');
  } catch (error) {
    console.error('❌ Chrome Storage 初始化失败:', error);
  }
}

// 创建右键菜单
function createContextMenus() {
  chrome.contextMenus.removeAll(() => {
    chrome.contextMenus.create({
      id: 'addToA1Tabs',
      title: '添加到 A1Tabs',
      contexts: ['page', 'link']
    });
    
    chrome.contextMenus.create({
      id: 'addLinkToA1Tabs',
      title: '将此链接添加到 A1Tabs',
      contexts: ['link']
    });
  });
}

// 处理右键菜单点击
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'addToA1Tabs') {
    addCurrentPageToLinks(tab).catch(error => {
      console.error('右键菜单添加页面失败:', error);
    });
  } else if (info.menuItemId === 'addLinkToA1Tabs') {
    addLinkToLinks(info.linkUrl, info.selectionText || '').catch(error => {
      console.error('右键菜单添加链接失败:', error);
    });
  }
});

// 添加当前页面到链接列表 - 使用 IndexedDB 或 Chrome Storage
async function addCurrentPageToLinks(tab, pageInfo = null) {
  try {
    // 使用pageInfo或tab信息
    const info = pageInfo || {
      title: tab.title,
      url: tab.url
    };
    
    // 检查URL是否已存在
    const existingLink = await checkLinkExists(info.url);
    if (existingLink) {
      await showErrorNotification(`链接已存在: ${existingLink.title}`);
      throw new Error(`链接已存在: ${existingLink.title}`);
    }
    
    const newLink = {
      id: generateId(),
      title: info.title,
      url: info.url,
      logo: generateLogoFromTitle(info.title),
      categoryId: '',
      createdAt: new Date().toISOString(),
      visitCount: 0,
      note: info.description || ''
    };
    
    let addedLink;
    
    // 先尝试使用 IndexedDB
    if (dbManager && typeof dbManager.addLink === 'function') {
      try {
        await dbManager.init(); // 确保初始化
        addedLink = await dbManager.addLink(newLink);
        console.log('Background: 成功添加链接到 IndexedDB:', addedLink.title);
      } catch (error) {
        // 如果是重复链接错误，直接抛出
        if (error.name === 'DuplicateUrlError') {
          await showErrorNotification(`链接已存在: ${error.existingLink.title}`);
          throw error;
        }
        console.warn('Background: IndexedDB 添加失败，降级到 Chrome Storage:', error);
        addedLink = await addLinkWithChromeStorage(newLink);
      }
    } else {
      // 降级到 Chrome Storage
      console.log('Background: 使用 Chrome Storage 添加链接');
      addedLink = await addLinkWithChromeStorage(newLink);
    }
    
    // 显示通知
    await showSuccessNotification('已添加链接: ' + info.title);
    
    return addedLink;
  } catch (error) {
    console.error('Background: 添加链接失败:', error);
    if (!error.message.includes('链接已存在')) {
      await showErrorNotification('添加链接失败');
    }
    throw error;
  }
}

// Chrome Storage 降级方案 - 添加链接
async function addLinkWithChromeStorage(newLink) {
  const result = await chrome.storage.sync.get(['links']);
  const links = result.links || [];
  links.push(newLink);
  await chrome.storage.sync.set({ links });
  console.log('Background: 成功添加链接到 Chrome Storage:', newLink.title);
  return newLink;
}

// 添加链接到链接列表 - 使用 IndexedDB 或 Chrome Storage
async function addLinkToLinks(url, title) {
  try {
    // 检查URL是否已存在
    const existingLink = await checkLinkExists(url);
    if (existingLink) {
      await showErrorNotification(`链接已存在: ${existingLink.title}`);
      throw new Error(`链接已存在: ${existingLink.title}`);
    }
    
    const newLink = {
      id: generateId(),
      title: title || '新链接',
      url: url,
      logo: generateLogoFromTitle(title),
      categoryId: '',
      createdAt: new Date().toISOString(),
      visitCount: 0,
      note: ''
    };
    
    let addedLink;
    
    // 先尝试使用 IndexedDB
    if (dbManager && typeof dbManager.addLink === 'function') {
      try {
        await dbManager.init(); // 确保初始化
        addedLink = await dbManager.addLink(newLink);
        console.log('Background: 成功添加链接到 IndexedDB:', addedLink.title);
      } catch (error) {
        // 如果是重复链接错误，直接抛出
        if (error.name === 'DuplicateUrlError') {
          await showErrorNotification(`链接已存在: ${error.existingLink.title}`);
          throw error;
        }
        console.warn('Background: IndexedDB 添加失败，降级到 Chrome Storage:', error);
        addedLink = await addLinkWithChromeStorage(newLink);
      }
    } else {
      // 降级到 Chrome Storage
      addedLink = await addLinkWithChromeStorage(newLink);
    }
    
    // 显示通知
    await showSuccessNotification('已添加链接: ' + (title || '新链接'));
    
    return addedLink;
  } catch (error) {
    console.error('Background: 添加链接失败:', error);
    if (!error.message.includes('链接已存在')) {
      await showErrorNotification('添加链接失败');
    }
    throw error;
  }
}

// 处理标签页更新（用于访问统计）
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete' && tab.url) {
    await updateVisitCount(tab.url);
  }
});

// 更新访问计数 - 使用 IndexedDB
async function updateVisitCount(url) {
  try {
    // 检查dbManager是否可用
    if (!dbManager || typeof dbManager.init !== 'function') {
      console.warn('Background: dbManager未初始化，跳过访问计数更新');
      return;
    }
    
    // 确保dbManager已初始化
    await dbManager.init();
    
    const links = await dbManager.getLinks();
    const targetLink = links.find(link => link.url === url);
    
    if (targetLink) {
      const updatedLink = await dbManager.updateLink(targetLink.id, {
        visitCount: (targetLink.visitCount || 0) + 1,
        lastVisited: new Date().toISOString()
      });
      
      console.log('Background: 更新访问计数:', updatedLink.title, updatedLink.visitCount);
    }
  } catch (error) {
    // 只记录警告，不影响主要功能
    console.warn('Background: 更新访问计数失败:', error.message);
  }
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  switch (message.action) {
    case 'ping':
      // 调试ping响应
      sendResponse({
        success: true,
        indexedDBAvailable: indexedDBAvailable && !!dbManager,
        dbManagerStatus: dbManager ? '已创建' : '未创建',
        timestamp: new Date().toISOString(),
        backgroundReady: true
      });
      break;
      
    case 'getCurrentTab':
      getCurrentTab().then(sendResponse);
      return true;
      
    case 'addCurrentPage':
      // 处理来自content script的添加当前页面请求
      handleAddCurrentPageMessage(message, sender).then(sendResponse);
      return true;
      
    case 'openLink':
      chrome.tabs.create({ url: message.url });
      sendResponse({ success: true });
      break;
      
    case 'deleteLink':
      // 处理删除链接请求
      handleDeleteLinkMessage(message).then(sendResponse);
      return true;
      
    case 'updateLink':
      // 处理更新链接请求
      handleUpdateLinkMessage(message).then(sendResponse);
      return true;
      
    case 'exportData':
      exportData().then(sendResponse);
      return true;
      
    case 'importData':
      importData(message.data).then(sendResponse);
      return true;
      
    case 'getLinks':
      // 获取所有链接
      dbManager.getLinks().then(sendResponse).catch(error => 
        sendResponse({ error: error.message })
      );
      return true;
      
    case 'getCategories':
      // 获取所有分类
      dbManager.getCategories().then(sendResponse).catch(error => 
        sendResponse({ error: error.message })
      );
      return true;
      
    default:
      sendResponse({ error: 'Unknown action' });
  }
});

// 处理来自content script的添加当前页面请求
async function handleAddCurrentPageMessage(message, sender) {
  try {
    // 获取当前标签页信息
    const tab = sender.tab;
    if (!tab) {
      return { error: '无法获取标签页信息' };
    }
    
    // 使用pageInfo或者tab信息
    const pageInfo = message.pageInfo || {
      title: tab.title,
      url: tab.url
    };
    
    // 添加当前页面到链接列表
    await addCurrentPageToLinks(tab, pageInfo);
    
    return { success: true, message: '已成功添加到 A1Tabs' };
  } catch (error) {
    console.error('处理添加当前页面请求失败:', error);
    return { error: error.message };
  }
}

// 处理删除链接请求
async function handleDeleteLinkMessage(message) {
  try {
    const { linkId } = message;
    if (!linkId) {
      return { error: '缺少链接ID' };
    }
    
    // 使用 IndexedDB 删除链接
    await dbManager.deleteLink(linkId);
    console.log('Background: 成功删除链接:', linkId);
    
    return { success: true, message: '链接已删除' };
  } catch (error) {
    console.error('Background: 删除链接失败:', error);
    return { error: error.message };
  }
}

// 处理更新链接请求
async function handleUpdateLinkMessage(message) {
  try {
    const { linkId, updates } = message;
    if (!linkId || !updates) {
      return { error: '缺少必要参数' };
    }
    
    // 使用 IndexedDB 更新链接
    const updatedLink = await dbManager.updateLink(linkId, updates);
    console.log('Background: 成功更新链接:', updatedLink.title);
    
    return { success: true, data: updatedLink };
  } catch (error) {
    console.error('Background: 更新链接失败:', error);
    return { error: error.message };
  }
}

// 获取当前标签页信息
async function getCurrentTab() {
  const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
  return tabs[0];
}

// 显示成功通知
async function showSuccessNotification(message) {
  try {
    chrome.notifications.create({
      type: 'basic',
      iconUrl: chrome.runtime.getURL('assets/icons/icon48.png'),
      title: 'A1Tabs',
      message: message
    });
  } catch (error) {
    console.warn('Background: 显示通知失败:', error);
  }
}

// 显示错误通知
async function showErrorNotification(message) {
  try {
    chrome.notifications.create({
      type: 'basic',
      iconUrl: chrome.runtime.getURL('assets/icons/icon48.png'),
      title: 'A1Tabs - 错误',
      message: message
    });
  } catch (error) {
    console.warn('Background: 显示错误通知失败:', error);
  }
}

// 导出数据 - 使用 IndexedDB
async function exportData() {
  try {
    const [categories, links, settings, todos] = await Promise.all([
      dbManager.getCategories(),
      dbManager.getLinks(),
      dbManager.getSettings(),
      dbManager.getTodos()
    ]);
    
    return {
      exportTime: new Date().toISOString(),
      version: '1.0.0',
      data: {
        categories,
        links,
        settings,
        todos
      }
    };
  } catch (error) {
    console.error('Background: 导出数据失败:', error);
    return { error: error.message };
  }
}

// 导入数据 - 使用 IndexedDB
async function importData(importedData) {
  try {
    if (!importedData.data) {
      return { error: 'Invalid data format' };
    }
      
    const { categories, links, settings, todos } = importedData.data;
      
    // 使用事务批量导入数据
    const transaction = dbManager.db.transaction(['categories', 'links', 'settings', 'todos'], 'readwrite');
      
    return new Promise((resolve, reject) => {
      transaction.oncomplete = () => {
        console.log('Background: 数据导入完成');
        resolve({ success: true });
      };
        
      transaction.onerror = () => {
        console.error('Background: 数据导入失败:', transaction.error);
        reject(transaction.error);
      };
        
      const categoriesStore = transaction.objectStore('categories');
      const linksStore = transaction.objectStore('links');
      const settingsStore = transaction.objectStore('settings');
      const todosStore = transaction.objectStore('todos');
        
      // 清空现有数据
      categoriesStore.clear();
      linksStore.clear();
      settingsStore.clear();
      todosStore.clear();
        
      // 导入分类
      if (categories && Array.isArray(categories)) {
        categories.forEach(category => {
          categoriesStore.add(category);
        });
      }
        
      // 导入链接
      if (links && Array.isArray(links)) {
        links.forEach(link => {
          linksStore.add(link);
        });
      }
        
      // 导入设置
      if (settings) {
        settingsStore.put({
          key: 'userSettings',
          value: settings,
          updatedAt: new Date().toISOString()
        });
      }
        
      // 导入待办事项
      if (todos && Array.isArray(todos)) {
        todos.forEach(todo => {
          todosStore.add(todo);
        });
      }
    });
  } catch (error) {
    console.error('Background: 导入数据失败:', error);
    return { error: error.message };
  }
}

// 同步 Chrome Storage 到 IndexedDB 并清理 Chrome Storage
async function syncChromeStorageToIndexedDB() {
  try {
    // 等待 IndexedDB 完全初始化
    if (!dbManager || typeof dbManager.init !== 'function') {
      console.warn('Background: dbManager 未准备好，延迟同步');
      // 延迟一段时间后重试
      setTimeout(() => syncChromeStorageToIndexedDB(), 1000);
      return;
    }
    
    try {
      await dbManager.init();
    } catch (initError) {
      console.warn('Background: IndexedDB 初始化失败，延迟同步:', initError.message);
      setTimeout(() => syncChromeStorageToIndexedDB(), 2000);
      return;
    }
    
    // 从 Chrome Storage 获取数据
    const result = await chrome.storage.sync.get(['links', 'categories', 'settings']);
    
    let hasDataToSync = false;
    
    // 同步链接数据
    if (result.links && result.links.length > 0) {
      console.log(`Background: 发现 ${result.links.length} 个链接需要同步到 IndexedDB`);
      
      for (const link of result.links) {
        try {
          // 检查链接是否已存在于 IndexedDB 中
          const existingLink = await dbManager.getLinkByUrl(link.url);
          if (!existingLink) {
            // 如果不存在，则添加到 IndexedDB
            await dbManager.addLink({
              ...link,
              createdAt: link.createdAt || link.createTime || new Date().toISOString(),
              lastVisited: link.lastVisited || null
            });
            console.log('Background: 已同步链接到 IndexedDB:', link.title);
            hasDataToSync = true;
          } else {
            console.log('Background: 链接已存在于 IndexedDB，跳过:', link.title);
          }
        } catch (error) {
          if (error.name !== 'DuplicateUrlError') {
            console.error('Background: 同步链接失败:', link.title, error);
          }
        }
      }
      
      // 如果同步成功，清理 Chrome Storage 中的链接数据
      if (hasDataToSync) {
        await chrome.storage.sync.set({ links: [] });
        console.log('Background: 已清理 Chrome Storage 中的链接数据');
      }
    }
    
    // 同步分类数据
    if (result.categories && result.categories.length > 0) {
      console.log(`Background: 发现 ${result.categories.length} 个分类需要同步到 IndexedDB`);
      
      for (const category of result.categories) {
        try {
          // 检查分类是否已存在于 IndexedDB 中
          const existingCategory = await dbManager.getCategoryById(category.id);
          if (!existingCategory) {
            // 如果不存在，则添加到 IndexedDB
            await dbManager.addCategory(category);
            console.log('Background: 已同步分类到 IndexedDB:', category.name);
            hasDataToSync = true;
          } else {
            console.log('Background: 分类已存在于 IndexedDB，跳过:', category.name);
          }
        } catch (error) {
          console.error('Background: 同步分类失败:', category.name, error);
        }
      }
      
      // 如果同步成功，清理 Chrome Storage 中的分类数据
      if (hasDataToSync) {
        await chrome.storage.sync.set({ categories: [] });
        console.log('Background: 已清理 Chrome Storage 中的分类数据');
      }
    }
    
    // 同步设置数据
    if (result.settings) {
      console.log('Background: 发现设置数据需要同步到 IndexedDB');
      
      try {
        // 保存设置到 IndexedDB
        await dbManager.saveSettings(result.settings);
        console.log('Background: 已同步设置到 IndexedDB');
        hasDataToSync = true;
        
        // 清理 Chrome Storage 中的设置数据
        await chrome.storage.sync.remove('settings');
        console.log('Background: 已清理 Chrome Storage 中的设置数据');
      } catch (error) {
        console.error('Background: 同步设置失败:', error);
      }
    }
    
    if (hasDataToSync) {
      console.log('Background: 数据同步完成');
    } else {
      console.log('Background: 没有需要同步的数据');
    }
    
  } catch (error) {
    console.error('Background: 同步 Chrome Storage 到 IndexedDB 失败:', error);
  }
}

// 导出同步函数供外部使用
self.syncChromeStorageToIndexedDB = syncChromeStorageToIndexedDB;
