// 存储管理器 - 使用Chrome Storage Local (支持大数据集)
// 与原版相比，将 chrome.storage.sync 替换为 chrome.storage.local
// 优点：支持大数据量(~5MB)，缺点：不跨设备同步

const StorageManager = {
  // 获取分类
  async getCategories() {
    const result = await chrome.storage.local.get(['categories']);
    return result.categories || [];
  },
  
  // 保存分类
  async saveCategories(categories) {
    await chrome.storage.local.set({ categories });
  },
  
  // 添加分类
  async addCategory(category) {
    const categories = await this.getCategories();
    const newCategory = {
      id: Date.now().toString(),
      name: category.name,
      icon: category.icon || '📁',
      color: category.color || '#4285f4',
      description: category.description || '',
      createdAt: new Date().toISOString(),
      linkCount: 0
    };
    categories.push(newCategory);
    await this.saveCategories(categories);
    return newCategory;
  },
  
  // 更新分类
  async updateCategory(categoryId, updates) {
    const categories = await this.getCategories();
    const index = categories.findIndex(cat => cat.id === categoryId);
    if (index !== -1) {
      categories[index] = { ...categories[index], ...updates };
      await this.saveCategories(categories);
      return categories[index];
    }
    return null;
  },
  
  // 删除分类
  async deleteCategory(categoryId) {
    const categories = await this.getCategories();
    const filteredCategories = categories.filter(cat => cat.id !== categoryId);
    await this.saveCategories(filteredCategories);
    
    // 同时删除该分类下的所有链接（级联删除）
    const links = await this.getLinks();
    const filteredLinks = links.filter(link => link.categoryId !== categoryId && link.category !== categoryId);
    await this.saveLinks(filteredLinks);
    
    // 返回被删除的链接数量
    const deletedLinksCount = links.length - filteredLinks.length;
    return { deletedLinksCount };
  },
  
  // 获取分类（包含链接数量）
  async getCategoriesWithCounts() {
    const [categories, links] = await Promise.all([
      this.getCategories(),
      this.getLinks()
    ]);
    
    return categories.map(category => {
      const linkCount = links.filter(link => link.categoryId === category.id || link.category === category.id).length;
      return { ...category, linkCount };
    });
  },
  
  // 获取链接
  async getLinks() {
    const result = await chrome.storage.local.get(['links']);
    return result.links || [];
  },
  
  // 保存链接
  async saveLinks(links) {
    await chrome.storage.local.set({ links });
  },
  
  // 添加链接
  async addLink(link) {
    const links = await this.getLinks();
    
    // 检查URL是否已存在
    const duplicateLink = links.find(existingLink => 
      existingLink.url === link.url
    );
    
    if (duplicateLink) {
      // 如果链接已存在，抛出一个特殊的错误
      const error = new Error(`链接 "${duplicateLink.title}" 已存在`);
      error.name = 'DuplicateUrlError';
      error.existingLink = duplicateLink;
      throw error;
    }
    
    const newLink = {
      id: Date.now().toString(),
      url: link.url,
      title: link.title,
      logo: link.logo || this.generateLogo(link.title),
      category: link.category || '',
      note: link.note || '',
      isQuickAccess: link.isQuickAccess || false,
      visitCount: 0,
      createdAt: new Date().toISOString(),
      lastVisited: null
    };
    links.unshift(newLink); // 最新的在前面
    await this.saveLinks(links);
    return newLink;
  },
  
  // 更新链接
  async updateLink(linkId, updates) {
    const links = await this.getLinks();
    const index = links.findIndex(link => link.id === linkId);
    if (index !== -1) {
      links[index] = { ...links[index], ...updates };
      await this.saveLinks(links);
      return links[index];
    }
    return null;
  },
  
  // 记录链接访问
  async recordVisit(linkId) {
    const links = await this.getLinks();
    const index = links.findIndex(link => link.id === linkId);
    if (index !== -1) {
      links[index].visitCount += 1;
      links[index].lastVisited = new Date().toISOString();
      await this.saveLinks(links);
    }
  },
  
  // 生成Logo
  generateLogo(title) {
    if (!title) return '?';
    // 如果是中文，取第一个字
    if (/[一-龥]/.test(title)) {
      return title.charAt(0);
    }
    // 如果是英文，取前两个字母
    const words = title.split(' ');
    if (words.length >= 2) {
      return (words[0].charAt(0) + words[1].charAt(0)).toUpperCase();
    } else {
      return title.substring(0, 2).toUpperCase();
    }
  },
  
  // 删除链接
  async deleteLink(linkId) {
    const links = await this.getLinks();
    const filteredLinks = links.filter(link => link.id !== linkId);
    await this.saveLinks(filteredLinks);
  },
  
  // 获取设置
  async getSettings() {
    const result = await chrome.storage.local.get(['settings']);
    return result.settings || {
      theme: 'light',
      defaultView: 'grid',
      autoCapture: true,
      hasSeenWelcomeNotice: false
    };
  },
  
  // 保存设置
  async saveSettings(settings) {
    await chrome.storage.local.set({ settings });
  },
  
  // 更新设置
  async updateSettings(newSettings) {
    const currentSettings = await this.getSettings();
    const updatedSettings = { ...currentSettings, ...newSettings };
    await this.saveSettings(updatedSettings);
  },
  
  // 获取所有数据
  async getAllData() {
    const result = await chrome.storage.local.get(['categories', 'links', 'settings']);
    return {
      categories: result.categories || [],
      links: result.links || [],
      settings: result.settings || {
        theme: 'light',
        defaultView: 'grid',
        searchEngine: 'bing',
        backgroundType: 'default',
        autoCapture: true
      }
    };
  },
  
  // 导出数据
  async exportData() {
    return await this.getAllData();
  },
  
  // 导入数据
  async importData(data) {
    if (data.categories) await this.saveCategories(data.categories);
    if (data.links) await this.saveLinks(data.links);
    if (data.settings) await this.saveSettings(data.settings);
  },
  
  // 清空所有数据
  async clearAllData() {
    await chrome.storage.local.clear();
  }
};