import { Component, inject, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router, RouterOutlet } from '@angular/router';
import * as tablerIcons from '@ng-icons/tabler-icons';
import * as tablerIconsFill from '@ng-icons/tabler-icons/fill';
import * as lucideIcons from '@ng-icons/lucide';
import { provideIcons } from '@ng-icons/core';
import { Title } from '@angular/platform-browser';
import { filter, map, mergeMap } from 'rxjs';
import { AuthService } from './core/services/auth.service';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
  styleUrls: ['./app.scss'],
  viewProviders: [
    provideIcons({ ...tablerIcons, ...tablerIconsFill, ...lucideIcons }),
  ],
})
export class App implements OnInit {
  private titleService = inject(Title);
  private router = inject(Router);
  private activatedRoute = inject(ActivatedRoute);
  private authService = inject(AuthService);

  async ngOnInit(): Promise<void> {
    try {
      // Initialiser l'authentification avec gestion d'erreur
      const isAuthenticated = await this.authService.initialize();
      
      console.log('Authentication initialized:', isAuthenticated);
      
      if (!isAuthenticated) {
        console.log('👤 User not authenticated, may redirect to login');
        // Note: Votre AuthService gère déjà la redirection dans logout()
      }
    } catch (error) {
      console.error('Error during authentication initialization:', error);
    }

    // Configurer le titre de la page
    this.setupTitleListener();
  }

  private setupTitleListener(): void {
    this.router.events
      .pipe(
        filter((event): event is NavigationEnd => event instanceof NavigationEnd),
        map(() => {
          let route = this.activatedRoute;
          while (route.firstChild) {
            route = route.firstChild;
          }
          return route;
        }),
        mergeMap((route) => route.data)
      )
      .subscribe((data) => {
        if (data['title']) {
          this.titleService.setTitle(`${data['title']} | DCB BO Admin`);
        }
      });
  }
}
