import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { ImagesService } from '../../services/images.service';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

@Component({
    selector: 'app-carrusel-home',
    templateUrl: './carrusel-home.component.html',
    styleUrls: ['./carrusel-home.component.css'],
    standalone: false
})
export class CarruselHomeComponent implements OnInit, OnDestroy {
  slides: any[] = [];
  currentIndex: number = 0;
  intervalId: any;

  constructor(
    private _router: Router,
    private _imagesService: ImagesService,
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit(): void {
    this._imagesService.getImages().subscribe((data: any) => {
      this.slides = data.map((image: any) => ({
        ...image,
        URLB: `${image.URLB}`,
        BREF: image.BREF.trim()
      }));
      console.log(this.slides);
      this.startAutoplay();
    });
  }

  startAutoplay(): void {
    this.intervalId = setInterval(() => {
      this.nextSlide();
    }, 4000);
  }

  redirect(index: number) {
    console.log(index);
    console.log(this.slides[index].BREF);
    this._router.navigate([`/${this.slides[index].BREF}`]);

  }

  nextSlide(): void {
    this.currentIndex = (this.currentIndex + 1) % this.slides.length;
  }

  prevSlide(): void {
    this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
  }

  ngOnDestroy(): void {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }
}