// login.page.ts
import { Component } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { Router } from '@angular/router';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
  standalone:false,
})
export class LoginPage {
  username = '';
  password = '';
  isLogin = true; // 切换登录/注册模式
  email = ''; // 注册时使用

  constructor(
    private authService: AuthService,
    private router: Router,
    private toastCtrl: ToastController
  ) {}

  async submit() {
    if (this.isLogin) {
      await this.handleLogin();
    } else {
      await this.handleRegister();
    }
  }

  private async handleLogin() {
    if (!this.username || !this.password) {
      this.showToast('请输入用户名和密码');
      return;
    }

    const success = await this.authService.login(this.username, this.password);
    console.log(success);
    
    if (success) {
      this.showToast('登录成功');
      this.router.navigate(['/tabs/tab4']);
    } else {
      this.showToast('登录失败，请检查用户名和密码');
    }
  }

  private async handleRegister() {
    if (!this.username || !this.password) {
      this.showToast('请输入用户名和密码');
      return;
    }

    const success = await this.authService.register(this.username, this.password, this.email);
    if (success) {
      this.showToast('注册成功，已自动登录');
      this.router.navigate(['/tabs/tab1']);
    } else {
      this.showToast('注册失败，用户名可能已被使用');
    }
  }

  toggleMode() {
    this.isLogin = !this.isLogin;
  }

  private async showToast(message: string) {
    const toast = await this.toastCtrl.create({
      message,
      duration: 2000,
      position: 'top'
    });
    await toast.present();
  }
}