import Swiper from "swiper/bundle";
import ScrollTrigger from "gsap/ScrollTrigger";

export class CenteredSwiper {
  private swiper: Swiper;

  constructor() {
    this.swiper = this.initSwiper();
    this.swiper.autoplay.start();
  }

  private initSwiper(): Swiper {
    return new Swiper(".swiper", {
      loop: true,
      slidesPerView: 1.6,
      spaceBetween: 16,
      speed: 700,
      initialSlide: 1,
      autoplay: {
        delay: 5000,
        disableOnInteraction: false,
        waitForTransition: false,
      },
      breakpoints: {
        1024: {
          spaceBetween: 64,
        },
      },
      pagination: {
        el: ".swiper-pagination",
        clickable: true,
      },

      on: {
        init: (swiper) => {
          requestAnimationFrame(() => {
            this.centerActiveSlide(swiper);
            ScrollTrigger.refresh();
          });
        },
        slideChange: (swiper) => {
          this.centerActiveSlide(swiper);
        },
      },
    });
  }

  private centerActiveSlide(swiper: Swiper): void {
    const activeSlide = swiper.slides[swiper.activeIndex];
    if (!activeSlide) return;

    const slideWidth = activeSlide.offsetWidth;
    const containerWidth = swiper.width;

    const offset = (containerWidth - slideWidth) / 2;
    const targetTranslate = -activeSlide.offsetLeft + offset;

    swiper.setTranslate(targetTranslate);
  }
}
