import { Component, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterOutlet, NavigationEnd, Event } from '@angular/router';
import { Subscription, filter } from 'rxjs';

@Component({
  selector: 'app-route-animations',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  template: `
    <div class="content-container" [class]="animationClass">
      <router-outlet></router-outlet>
    </div>
  `,
  styles: [`
    .content-container {
      width: 100%;
      height: 100%;
    }

    .animate__animated {
      animation-duration: 1.2s;
    }
  `]
})
export class RouteAnimationsComponent implements OnDestroy {
  // Clase de animación actual
  animationClass: string = 'animate__animated animate__fadeIn ';
  
  // Animaciones disponibles 
  private animations: string[] = [
    'animate__fadeIn',
  ];
  
  private routerSub: Subscription;

  constructor(private router: Router) {
    // Suscribirse a los eventos de navegación
    this.routerSub = this.router.events
      .pipe(filter((event: Event) => event instanceof NavigationEnd))
      .subscribe(() => {
        // Resetear la animación primero
        this.animationClass = '';
        
        // Aplicar una nueva animación después de un breve retraso
        setTimeout(() => {
          const randomIndex = Math.floor(Math.random() * this.animations.length);
          this.animationClass = `animate__animated ${this.animations[randomIndex]} `;
        }, 50);
      });
  }

  ngOnDestroy(): void {
    // Cancelar suscripción para evitar memory leaks
    if (this.routerSub) {
      this.routerSub.unsubscribe();
    }
  }
}