// IndexedDB存储管理器 - 高性能本地存储
// 优势：无存储大小限制、事务支持、索引查询、异步操作
// 注意：不支持跨设备同步，仅本地存储

class IndexedDBManager {
  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('Frontend: 尝试打开IndexedDB，版本:', this.dbVersion);
      console.log('Frontend: 数据库名称:', this.dbName);
      const request = indexedDB.open(this.dbName, this.dbVersion);

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

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

      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        console.log('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 });
          console.log('创建categories存储');
        }

        // 创建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 });
          console.log('创建links存储');
        }

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

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

        // 创建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 });
          console.log('创建todos存储');
        }
      };
    });
  }

  // 执行事务操作
  async executeTransaction(storeNames, mode, operation) {
    await this.init();
    
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(storeNames, mode);
      
      transaction.onerror = () => {
        console.error('事务执行失败:', transaction.error);
        reject(transaction.error);
      };
      
      transaction.oncomplete = () => {
        resolve();
      };
      
      try {
        operation(transaction);
      } catch (error) {
        reject(error);
      }
    });
  }

  // 获取单个对象存储
  async getStore(storeName, mode = 'readonly') {
    await this.init();
    return new Promise((resolve, reject) => {
      try {
        const transaction = this.db.transaction([storeName], mode);
        const objectStore = transaction.objectStore(storeName);
        resolve(objectStore);
      } catch (error) {
        console.error(`获取对象存储失败: ${storeName}`, error);
        reject(error);
      }
    });
  }

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

  // 获取所有分类
  async getCategories() {
    const store = await this.getStore('categories');
    
    return new Promise((resolve, reject) => {
      const request = store.getAll();
      
      request.onsuccess = () => {
        let categories = request.result || [];
        // 按照order字段排序，如果没有order字段则按创建时间排序
        categories.sort((a, b) => {
          const orderA = a.order !== undefined ? a.order : Infinity;
          const orderB = b.order !== undefined ? b.order : Infinity;
          if (orderA !== orderB) {
            return orderA - orderB;
          }
          // 如果order相同，则按创建时间排序
          return new Date(a.createdAt) - new Date(b.createdAt);
        });
        resolve(categories);
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 添加分类
  async addCategory(category) {
    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
    };

    const store = await this.getStore('categories', 'readwrite');
    
    return new Promise((resolve, reject) => {
      const request = store.add(newCategory);
      
      request.onsuccess = () => {
        resolve(newCategory);
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 更新分类
  async updateCategory(categoryId, updates) {
    const store = await this.getStore('categories', 'readwrite');
    
    return new Promise((resolve, reject) => {
      const getRequest = store.get(categoryId);
      
      getRequest.onsuccess = () => {
        const category = getRequest.result;
        if (!category) {
          reject(new Error('分类不存在'));
          return;
        }
        
        const updatedCategory = { ...category, ...updates };
        const putRequest = store.put(updatedCategory);
        
        putRequest.onsuccess = () => {
          resolve(updatedCategory);
        };
        
        putRequest.onerror = () => {
          reject(putRequest.error);
        };
      };
      
      getRequest.onerror = () => {
        reject(getRequest.error);
      };
    });
  }

  // 删除分类
  async deleteCategory(categoryId) {
    let deletedLinksCount = 0;
    
    // 使用事务确保数据一致性
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['categories', 'links'], 'readwrite');
      const categoriesStore = transaction.objectStore('categories');
      const linksStore = transaction.objectStore('links');
      
      transaction.oncomplete = () => {
        resolve({ deletedLinksCount });
      };
      
      transaction.onerror = () => {
        reject(transaction.error);
      };
      
      // 删除分类
      const deleteCategoryRequest = categoriesStore.delete(categoryId);
      
      // 删除该分类下的所有链接
      const linksIndex = linksStore.index('categoryId');
      const linksRequest = linksIndex.getAll(categoryId);
      
      linksRequest.onsuccess = () => {
        const categoryLinks = linksRequest.result;
        deletedLinksCount = categoryLinks.length;
        
        // 删除所有相关链接
        categoryLinks.forEach(link => {
          linksStore.delete(link.id);
        });
        
        // 同时处理使用category字段的链接
        const categoryIndex = linksStore.index('category');
        const categoryLinksRequest = categoryIndex.getAll(categoryId);
        
        categoryLinksRequest.onsuccess = () => {
          const additionalLinks = categoryLinksRequest.result;
          additionalLinks.forEach(link => {
            linksStore.delete(link.id);
          });
          deletedLinksCount += additionalLinks.length;
        };
      };
    });
  }

  // 更新分类顺序
  async updateCategoryOrder(categoryIds) {
    try {
      // 获取所有分类
      const allCategories = await this.getCategories();
      
      // 创建一个映射，根据ID查找分类对象
      const categoryMap = new Map();
      allCategories.forEach(category => {
        categoryMap.set(category.id, category);
      });
      
      // 按照新的顺序更新分类
      const transaction = this.db.transaction(['categories'], 'readwrite');
      const store = transaction.objectStore('categories');
      
      return new Promise((resolve, reject) => {
        transaction.oncomplete = () => {
          console.log('分类顺序已更新');
          resolve();
        };
        
        transaction.onerror = () => {
          console.error('更新分类顺序失败:', transaction.error);
          reject(transaction.error);
        };
        
        // 按照新的顺序更新分类
        categoryIds.forEach((categoryId, index) => {
          const category = categoryMap.get(categoryId);
          if (category) {
            // 添加一个order字段来表示顺序
            category.order = index;
            store.put(category);
          }
        });
      });
    } catch (error) {
      console.error('更新分类顺序时发生错误:', error);
      throw error;
    }
  }

  // 获取分类（包含链接数量）
  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 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: new Date().toISOString(),
      lastVisited: null
    };

    const store = await this.getStore('links', 'readwrite');
    
    return new Promise((resolve, reject) => {
      const request = store.add(newLink);
      
      request.onsuccess = () => {
        resolve(newLink);
      };
      
      request.onerror = () => {
        // 如果仍然有ID冲突，尝试重新生成ID
        if (request.error.name === 'ConstraintError') {
          console.warn('ID冲突，尝试重新生成ID:', newLink.id);
          this.addLinkWithRetry(link, 3).then(resolve).catch(reject);
        } else {
          reject(request.error);
        }
      };
    });
  }
  
  // 生成唯一ID的辅助方法
  generateUniqueId() {
    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 `link_${timestamp}_${randomStr}_${extraRandom}`;
  }
  
  // 带重试的添加链接方法
  async addLinkWithRetry(link, maxRetries = 3) {
    // 首先检查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;
    }
    
    for (let i = 0; i < maxRetries; i++) {
      try {
        const uniqueId = this.generateUniqueId();
        const linkWithNewId = { ...link, id: uniqueId };
        
        const newLink = {
          id: uniqueId,
          url: linkWithNewId.url,
          title: linkWithNewId.title,
          logo: linkWithNewId.logo || this.generateLogo(linkWithNewId.title),
          category: linkWithNewId.category || '',
          categoryId: linkWithNewId.categoryId || '',
          note: linkWithNewId.note || '',
          isQuickAccess: linkWithNewId.isQuickAccess || false,
          visitCount: 0,
          createdAt: new Date().toISOString(),
          lastVisited: null
        };

        const store = await this.getStore('links', 'readwrite');
        
        return new Promise((resolve, reject) => {
          const request = store.add(newLink);
          
          request.onsuccess = () => {
            resolve(newLink);
          };
          
          request.onerror = () => {
            if (i === maxRetries - 1) {
              reject(new Error(`添加链接失败，已重试${maxRetries}次: ${request.error.message}`));
            } else {
              reject(request.error);
            }
          };
        });
        
      } catch (error) {
        if (i === maxRetries - 1) {
          throw new Error(`添加链接失败，已重试${maxRetries}次: ${error.message}`);
        }
        // 等待一小段时间后重试
        await new Promise(resolve => setTimeout(resolve, 100));
      }
    }
  }

  // 更新链接
  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 = () => {
        resolve();
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 记录链接访问
  async recordVisit(linkId) {
    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;
        }
        
        link.visitCount = (link.visitCount || 0) + 1;
        link.lastVisited = new Date().toISOString();
        
        const putRequest = store.put(link);
        
        putRequest.onsuccess = () => {
          resolve(link);
        };
        
        putRequest.onerror = () => {
          reject(putRequest.error);
        };
      };
      
      getRequest.onerror = () => {
        reject(getRequest.error);
      };
    });
  }

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

  // 获取设置
  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,
          hasSeenWelcomeNotice: false
        });
      };
      
      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);
      };
    });
  }

  // 更新设置
  async updateSettings(newSettings) {
    const currentSettings = await this.getSettings();
    const updatedSettings = { ...currentSettings, ...newSettings };
    await this.saveSettings(updatedSettings);
    return updatedSettings;
  }

  // 确保数据库结构是最新的
  async ensureLatestSchema() {
    // 检查是否缺少todos存储
    if (!this.db.objectStoreNames.contains('todos')) {
      // 关闭当前数据库连接，强制触发升级
      this.db.close();
      
      // 重新打开数据库，触发版本升级
      return new Promise((resolve, reject) => {
        console.log('Frontend: 尝试升级数据库，版本:', this.dbVersion);
        const request = indexedDB.open(this.dbName, this.dbVersion);
        
        request.onerror = () => {
          console.error('数据库结构升级失败:', request.error);
          console.error('Frontend: 升级版本:', this.dbVersion);
          reject(request.error);
        };
        
        request.onsuccess = () => {
          this.db = request.result;
          console.log('数据库结构升级完成');
          resolve();
        };
        
        request.onupgradeneeded = (event) => {
          const db = event.target.result;
          console.log('执行数据库结构升级');
          
          // 创建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 });
            console.log('创建todos存储');
          }
        };
      });
    }
  }

  // 获取待办事项
  async getTodos() {
    // 确保数据库结构是最新的
    await this.ensureLatestSchema();
    
    // 检查数据库是否包含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) {
    // 确保数据库结构是最新的
    await this.ensureLatestSchema();
    
    // 检查数据库是否包含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 getAllData() {
    const [categories, links, settings, todos] = await Promise.all([
      this.getCategories(),
      this.getLinks(),
      this.getSettings(),
      this.getTodos()
    ]);
    
    return {
      categories,
      links,
      settings,
      todos
    };
  }

  // 导入数据
  async importData(data) {
    const transaction = this.db.transaction(['categories', 'links', 'settings', 'todos'], 'readwrite');
    
    return new Promise((resolve, reject) => {
      transaction.oncomplete = () => {
        resolve();
      };
      
      transaction.onerror = () => {
        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 (data.categories && Array.isArray(data.categories)) {
        data.categories.forEach(category => {
          categoriesStore.add(category);
        });
      }
      
      // 导入链接
      if (data.links && Array.isArray(data.links)) {
        data.links.forEach(link => {
          linksStore.add(link);
        });
      }
      
      // 导入设置
      if (data.settings) {
        settingsStore.put({
          key: 'userSettings',
          value: data.settings,
          updatedAt: new Date().toISOString()
        });
      }
      
      // 导入待办事项
      if (data.todos && Array.isArray(data.todos)) {
        data.todos.forEach(todo => {
          todosStore.add(todo);
        });
      }
    });
  }

  // 导出数据
  async exportData() {
    return await this.getAllData();
  }

  // 清空所有数据
  async clearAllData() {
    const transaction = this.db.transaction(['categories', 'links', 'settings', 'metadata', 'todos'], 'readwrite');
    
    return new Promise((resolve, reject) => {
      transaction.oncomplete = () => {
        resolve();
      };
      
      transaction.onerror = () => {
        reject(transaction.error);
      };
      
      transaction.objectStore('categories').clear();
      transaction.objectStore('links').clear();
      transaction.objectStore('settings').clear();
      transaction.objectStore('metadata').clear();
      transaction.objectStore('todos').clear();
    });
  }

  // === 实用工具方法 ===

  // 生成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();
    }
  }

  // 关闭数据库连接
  close() {
    if (this.db) {
      this.db.close();
      this.db = null;
    }
  }

  // 删除数据库
  async deleteDatabase() {
    this.close();
    
    return new Promise((resolve, reject) => {
      const deleteRequest = indexedDB.deleteDB(this.dbName);
      
      deleteRequest.onsuccess = () => {
        console.log('数据库删除成功');
        resolve();
      };
      
      deleteRequest.onerror = () => {
        console.error('数据库删除失败:', deleteRequest.error);
        reject(deleteRequest.error);
      };
      
      deleteRequest.onblocked = () => {
        console.warn('数据库删除被阻塞，请关闭所有相关标签页');
      };
    });
  }
}

// 创建全局实例（内部使用）
const IndexedDBStorageManager = new IndexedDBManager();

// 兼容性API - 保持与现有代码的接口一致
const StorageAPI = {
  // 分类相关
  getCategories: () => IndexedDBStorageManager.getCategories(),
  saveCategories: (categories) => {
    // 注意：这里需要逐个添加，因为IndexedDB不支持批量替换
    console.warn('saveCategories方法在IndexedDB中需要特殊处理');
    return Promise.resolve();
  },
  addCategory: (category) => IndexedDBStorageManager.addCategory(category),
  updateCategory: (categoryId, updates) => IndexedDBStorageManager.updateCategory(categoryId, updates),
  deleteCategory: (categoryId) => IndexedDBStorageManager.deleteCategory(categoryId),
  getCategoriesWithCounts: () => IndexedDBStorageManager.getCategoriesWithCounts(),
  
  // 链接相关
  getLinks: () => IndexedDBStorageManager.getLinks(),
  saveLinks: (links) => {
    // 注意：这里需要逐个添加，因为IndexedDB不支持批量替换
    console.warn('saveLinks方法在IndexedDB中需要特殊处理');
    return Promise.resolve();
  },
  addLink: (link) => IndexedDBStorageManager.addLink(link),
  updateLink: (linkId, updates) => IndexedDBStorageManager.updateLink(linkId, updates),
  deleteLink: (linkId) => IndexedDBStorageManager.deleteLink(linkId),
  recordVisit: (linkId) => IndexedDBStorageManager.recordVisit(linkId),
  
  // 设置相关
  getSettings: () => IndexedDBStorageManager.getSettings(),
  saveSettings: (settings) => IndexedDBStorageManager.saveSettings(settings),
  updateSettings: (newSettings) => IndexedDBStorageManager.updateSettings(newSettings),
  
  // 数据管理
  getAllData: () => IndexedDBStorageManager.getAllData(),
  exportData: () => IndexedDBStorageManager.exportData(),
  importData: (data) => IndexedDBStorageManager.importData(data),
  clearAllData: () => IndexedDBStorageManager.clearAllData(),
  
  // 工具方法
  generateLogo: (title) => IndexedDBStorageManager.generateLogo(title)
};

// 导出API，保持与原有storage.js的兼容性
if (typeof module !== 'undefined' && module.exports) {
  module.exports = { IndexedDBManager, StorageAPI };
} else {
  // 浏览器环境下的全局暴露
  window.IndexedDBManager = IndexedDBManager;
  window.IndexedDBStorageAPI = StorageAPI;
}