// 迁移提示组件 - 帮助用户从Chrome Storage迁移到IndexedDB
// 在newtab.js中使用

class MigrationPrompt {
  constructor() {
    this.migrationManager = null;
    this.isShowing = false;
  }

  // 初始化迁移管理器
  async init() {
    if (typeof DataMigrationManager !== 'undefined') {
      this.migrationManager = new DataMigrationManager();
    } else {
      console.error('DataMigrationManager 未加载');
      return false;
    }
    return true;
  }

  // 检查是否需要显示迁移提示
  async checkAndShowMigrationPrompt() {
    if (!await this.init()) {
      return;
    }

    try {
      const status = await this.migrationManager.checkMigrationStatus();
      
      // 如果需要迁移且未显示过提示
      if (status.needsMigration && !this.isShowing) {
        this.showMigrationPrompt(status);
      } else if (status.dataConflict && !this.isShowing) {
        this.showConflictPrompt(status);
      }
    } catch (error) {
      console.error('检查迁移状态失败:', error);
    }
  }

  // 显示迁移提示
  showMigrationPrompt(status) {
    this.isShowing = true;
    
    const promptHtml = `
      <div class=\"migration-prompt\" id=\"migrationPrompt\">
        <div class=\"migration-content\">
          <div class=\"migration-header\">
            <h3>🚀 升级到 IndexedDB 存储</h3>
            <button class=\"close-btn\" id=\"closeMigrationPrompt\">×</button>
          </div>
          
          <div class=\"migration-body\">
            <p>我们检测到您在 Chrome Storage 中有数据，现在可以升级到更强大的 IndexedDB 存储！</p>
            
            <div class=\"migration-benefits\">
              <h4>升级优势：</h4>
              <ul>
                <li>✅ 无存储大小限制</li>
                <li>✅ 更快的数据读写性能</li>
                <li>✅ 支持复杂数据查询</li>
                <li>✅ 更好的数据完整性</li>
              </ul>
            </div>
            
            <div class=\"migration-data-info\">
              <p><strong>将要迁移的数据：</strong></p>
              <ul>
                <li>分类: ${status.chromeDataCount?.categories || 0} 个</li>
                <li>链接: ${status.chromeDataCount?.links || 0} 个</li>
                <li>存储类型: ${status.chromeStorageType === 'sync' ? 'Chrome Sync' : 'Chrome Local'}</li>
              </ul>
            </div>
            
            <p class=\"migration-note\">
              <strong>注意：</strong>迁移后，数据将仅保存在本地，不再跨设备同步。
              原有的 Chrome Storage 数据将保留作为备份。
            </p>
          </div>
          
          <div class=\"migration-actions\">
            <button class=\"btn btn-primary\" id=\"startMigrationBtn\">
              <span class=\"btn-text\">开始迁移</span>
              <span class=\"btn-loading\" style=\"display: none;\">迁移中...</span>
            </button>
            <button class=\"btn btn-secondary\" id=\"skipMigrationBtn\">暂时跳过</button>
          </div>
        </div>
      </div>
    `;

    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', promptHtml);
    
    // 绑定事件
    this.bindMigrationEvents();
  }

  // 显示数据冲突提示
  showConflictPrompt(status) {
    this.isShowing = true;
    
    const promptHtml = `
      <div class=\"migration-prompt\" id=\"migrationPrompt\">
        <div class=\"migration-content\">
          <div class=\"migration-header\">
            <h3>⚠️ 检测到数据冲突</h3>
            <button class=\"close-btn\" id=\"closeMigrationPrompt\">×</button>
          </div>
          
          <div class=\"migration-body\">
            <p>我们检测到您同时在 Chrome Storage 和 IndexedDB 中都有数据。</p>
            
            <div class=\"conflict-data-info\">
              <div class=\"data-source\">
                <h4>Chrome Storage:</h4>
                <ul>
                  <li>分类: ${status.chromeDataCount?.categories || 0} 个</li>
                  <li>链接: ${status.chromeDataCount?.links || 0} 个</li>
                </ul>
              </div>
              
              <div class=\"data-source\">
                <h4>IndexedDB:</h4>
                <ul>
                  <li>分类: ${status.indexedDBDataCount?.categories || 0} 个</li>
                  <li>链接: ${status.indexedDBDataCount?.links || 0} 个</li>
                </ul>
              </div>
            </div>
            
            <p>请选择您希望使用的数据源：</p>
          </div>
          
          <div class=\"migration-actions\">
            <button class=\"btn btn-primary\" id=\"useIndexedDBBtn\">使用 IndexedDB 数据</button>
            <button class=\"btn btn-warning\" id=\"migrateChromeStorageBtn\">迁移 Chrome Storage 数据</button>
            <button class=\"btn btn-secondary\" id=\"skipMigrationBtn\">暂时跳过</button>
          </div>
        </div>
      </div>
    `;

    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', promptHtml);
    
    // 绑定冲突解决事件
    this.bindConflictEvents();
  }

  // 绑定迁移事件
  bindMigrationEvents() {
    const prompt = document.getElementById('migrationPrompt');
    const startBtn = document.getElementById('startMigrationBtn');
    const skipBtn = document.getElementById('skipMigrationBtn');
    const closeBtn = document.getElementById('closeMigrationPrompt');

    startBtn?.addEventListener('click', () => this.performMigration());
    skipBtn?.addEventListener('click', () => this.hideMigrationPrompt());
    closeBtn?.addEventListener('click', () => this.hideMigrationPrompt());

    // 点击外部关闭
    prompt?.addEventListener('click', (e) => {
      if (e.target === prompt) {
        this.hideMigrationPrompt();
      }
    });
  }

  // 绑定冲突解决事件
  bindConflictEvents() {
    const prompt = document.getElementById('migrationPrompt');
    const useIDBBtn = document.getElementById('useIndexedDBBtn');
    const migrateChromeBtn = document.getElementById('migrateChromeStorageBtn');
    const skipBtn = document.getElementById('skipMigrationBtn');
    const closeBtn = document.getElementById('closeMigrationPrompt');

    useIDBBtn?.addEventListener('click', () => this.useIndexedDBData());
    migrateChromeBtn?.addEventListener('click', () => this.performMigration());
    skipBtn?.addEventListener('click', () => this.hideMigrationPrompt());
    closeBtn?.addEventListener('click', () => this.hideMigrationPrompt());

    // 点击外部关闭
    prompt?.addEventListener('click', (e) => {
      if (e.target === prompt) {
        this.hideMigrationPrompt();
      }
    });
  }

  // 执行迁移
  async performMigration() {
    const startBtn = document.getElementById('startMigrationBtn');
    const migrateChromeBtn = document.getElementById('migrateChromeStorageBtn');
    const activeBtn = startBtn || migrateChromeBtn;
    
    if (!activeBtn) return;

    // 显示加载状态
    const btnText = activeBtn.querySelector('.btn-text');
    const btnLoading = activeBtn.querySelector('.btn-loading');
    
    if (btnText) btnText.style.display = 'none';
    if (btnLoading) btnLoading.style.display = 'inline';
    activeBtn.disabled = true;

    try {
      const result = await this.migrationManager.quickMigration();
      
      if (result.success) {
        this.showMigrationSuccess(result);
        
        // 标记已迁移
        await chrome.storage.local.set({ indexeddb_migrated: true });
        
        // 刷新页面以使用新的存储
        setTimeout(() => {
          window.location.reload();
        }, 2000);
      } else {
        this.showMigrationError(result.message || '迁移失败');
      }
    } catch (error) {
      console.error('迁移失败:', error);
      this.showMigrationError(error.message || '迁移过程中发生错误');
    }

    // 恢复按钮状态
    if (btnText) btnText.style.display = 'inline';
    if (btnLoading) btnLoading.style.display = 'none';
    activeBtn.disabled = false;
  }

  // 使用IndexedDB数据
  async useIndexedDBData() {
    try {
      // 标记已迁移
      await chrome.storage.local.set({ indexeddb_migrated: true });
      
      this.showSuccessMessage('已选择使用 IndexedDB 数据');
      
      // 刷新页面
      setTimeout(() => {
        window.location.reload();
      }, 1500);
    } catch (error) {
      console.error('设置失败:', error);
      this.showMigrationError('设置失败: ' + error.message);
    }
  }

  // 显示迁移成功
  showMigrationSuccess(result) {
    const body = document.querySelector('#migrationPrompt .migration-body');
    if (body) {
      body.innerHTML = `
        <div class=\"migration-success\">
          <div class=\"success-icon\">✅</div>
          <h4>迁移完成！</h4>
          <p>成功迁移了 ${result.migratedData?.categories || 0} 个分类和 ${result.migratedData?.links || 0} 个链接。</p>
          <p>页面将在 2 秒后自动刷新...</p>
        </div>
      `;
    }
    
    // 隐藏操作按钮
    const actions = document.querySelector('#migrationPrompt .migration-actions');
    if (actions) {
      actions.style.display = 'none';
    }
  }

  // 显示成功消息
  showSuccessMessage(message) {
    const body = document.querySelector('#migrationPrompt .migration-body');
    if (body) {
      body.innerHTML = `
        <div class=\"migration-success\">
          <div class=\"success-icon\">✅</div>
          <h4>设置完成！</h4>
          <p>${message}</p>
          <p>页面将在 1.5 秒后自动刷新...</p>
        </div>
      `;
    }
    
    // 隐藏操作按钮
    const actions = document.querySelector('#migrationPrompt .migration-actions');
    if (actions) {
      actions.style.display = 'none';
    }
  }

  // 显示迁移错误
  showMigrationError(errorMessage) {
    const body = document.querySelector('#migrationPrompt .migration-body');
    if (body) {
      body.innerHTML = `
        <div class=\"migration-error\">
          <div class=\"error-icon\">❌</div>
          <h4>迁移失败</h4>
          <p>${errorMessage}</p>
          <p>您可以稍后在设置中手动进行迁移，或联系技术支持。</p>
        </div>
      `;
    }
  }

  // 隐藏迁移提示
  hideMigrationPrompt() {
    const prompt = document.getElementById('migrationPrompt');
    if (prompt) {
      prompt.remove();
    }
    this.isShowing = false;
  }
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
  module.exports = MigrationPrompt;
} else {
  window.MigrationPrompt = MigrationPrompt;
}