import { Component } from '@angular/core';
import { Platform, NavController, LoadingController } from '@ionic/angular';
import { EventService } from './services/event.service';
import { StatusBar, Style } from '@capacitor/status-bar';
import { SplashScreen } from '@capacitor/splash-screen';
import { Browser } from '@capacitor/browser';
import { AuthService } from './services/auth.service';
import { LanguageService } from './services/language.service';
import { AlertService } from './services/alert.service';
import { TranslateService } from '@ngx-translate/core';
import { Capacitor } from '@capacitor/core';
import { OneSignalService } from './services/onesignal.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {

  private loading: any;

  public appPages: any[] = [];

  constructor(
    private platform: Platform,
    private authService: AuthService,
    private languageService: LanguageService,
    private translateService: TranslateService,
    private navCtrl: NavController,
    private events: EventService,
    private alertService: AlertService,
    private loadingCtrl: LoadingController,
    private oneSignalService: OneSignalService,
  ) {
    this.initializeApp();
    this.events.subscribe('set_role', role => {
      // Set OneSignal user tags when role is set (user logged in)
      this.setupOneSignalUser(role);
      if (role >= 2){
        this.appPages = [
          {
            title: this.translateService.instant('menu.home'),
            url: '/dashboard',
            icon: 'home'
          },
          {
            title: this.translateService.instant('menu.cards'),
            url: '/cards',
            icon: 'card'
          },
          {
            title: this.translateService.instant('menu.postulations'),
            url: '/postulations',
            icon: 'hammer'
          },
          {
            title: this.translateService.instant('menu.contracts'),
            url: '/contracts',
            icon: 'filing'
          },
          {
            title: this.translateService.instant('menu.faq'),
            url: '/faq',
            icon: 'information-circle'
          },
          {
            title: this.translateService.instant('menu.start'),
            url: '/start',
            icon: 'send'
          }
        ];
      } else {
        this.appPages = [
          {
            title: this.translateService.instant('menu.home'),
            url: '/dashboard',
            icon: 'home'
          },
          {
            title: this.translateService.instant('menu.cards'),
            url: '/cards',
            icon: 'card'
          },
          {
            title: this.translateService.instant('menu.contracts'),
            url: '/contracts',
            icon: 'filing'
          },
          {
            title: this.translateService.instant('menu.faq'),
            url: '/faq',
            icon: 'information-circle'
          },
          {
            title: this.translateService.instant('menu.hero'),
            url: '/hero',
            icon: 'ribbon'
          }
        ];
      }
    });
  }
  async initializeApp() {
    await this.platform.ready();

    // Solo ejecutar plugins nativos en dispositivos móviles
    if (Capacitor.isNativePlatform()) {
      await StatusBar.setStyle({ style: Style.Light });
      await StatusBar.setOverlaysWebView({ overlay: false });
      await StatusBar.setBackgroundColor({ color: '#0080ff' });

      // Initialize OneSignal push notifications
      await this.oneSignalService.init();
    }

    this.languageService.getDefaultLanguage();
    this.authService.getToken();
  }

  private async setupOneSignalUser(role: number) {
    if (this.authService.token && this.authService.token.user_id) {
      await this.oneSignalService.setUserId(this.authService.token.user_id);
      await this.oneSignalService.setUserRole(role);
    }
  }

  // When Logout Button is pressed
  async logout() {
    this.loading = await this.loadingCtrl.create();
    await this.loading.present();

    this.authService.logout().subscribe(
      async data => {
        this.alertService.presentToast(this.translateService.instant('alerts.logout'));
        // Clear OneSignal user tags on logout
        await this.oneSignalService.logout();
      },
      error => {
        this.loading.dismiss();
        console.log(error);
      },
      () => {
        this.loading.dismiss();
        this.navCtrl.navigateRoot('/landing');
      }
    );
  }

  async openUrl(url: string) {
    await Browser.open({ url });
  }
}
