import { Component } from '@angular/core';
import { AlertController, ModalController, IonicModule } from '@ionic/angular';
import { CloudUser } from 'src/lib/ncloud';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-modal-user-register',
  standalone: true,
  templateUrl: './modal-user-register.component.html',
  styleUrls: ['./modal-user-register.component.scss'],
  imports: [
    CommonModule,
    FormsModule,
    IonicModule
  ]
})
export class ModalUserRegisterComponent {
  username = '';
  password = '';

  constructor(
    private modalCtrl: ModalController,
    private alertCtrl: AlertController
  ) {}

  //注册
  async register() {
    if (!this.username || !this.password) {
      const alert = await this.alertCtrl.create({
        header: '错误',
        message: '请输入用户名和密码',
        buttons: ['确定']
      });
      await alert.present();
      return;
    }

    try {
      const user: any = new CloudUser();
      const signedUpUser = await user.signUp(this.username, this.password);
      if (!signedUpUser) throw new Error('注册失败');

      // ✅ 提示注册成功，关闭当前窗口，返回登录页
      const alert = await this.alertCtrl.create({
        header: '注册成功',
        message: '注册成功，请返回登录页登录。',
        buttons: [{
          text: '确定',
          handler: () => {
            this.modalCtrl.dismiss(null, 'registered');  // 自定义 role
          }
        }]
      });
      await alert.present();
    } catch (error: any) {
      const alert = await this.alertCtrl.create({
        header: '注册失败',
        message: error.message || '注册过程中发生错误',
        buttons: ['确定']
      });
      await alert.present();
    }
  }

  close() {
    this.modalCtrl.dismiss(null, 'cancel');
  }
}
