"use client";

import { useEffect, useMemo, useRef } from "react";
import { testimonials } from "../../data/home/testimonials";
import Image from "next/image";

export default function Testimonials() {
  const PAGINATION_BULLETS = 4;
  const swiperRef = useRef<HTMLDivElement>(null);
  const sliderTestimonials = useMemo(() => {
    if (testimonials.length >= 9) return testimonials;

    // Keep enough physical slides for centered + loop + auto width layouts.
    return [...testimonials, ...testimonials, ...testimonials];
  }, []);

  useEffect(() => {
    if (typeof window === "undefined" || !swiperRef.current) return;

    const initializeSwiper = async () => {
      try {
        const { default: Swiper } = await import("swiper/bundle");

        if (swiperRef.current) {
          const swiper = new Swiper(swiperRef.current, {
            slidesPerView: "auto",
            spaceBetween: 20,
            centeredSlides: true,
            loopAdditionalSlides: sliderTestimonials.length,
            initialSlide: 0,
            autoplay: {
              delay: 3000,
              disableOnInteraction: false,
            },
            pagination: {
              el: ".testi-pagination",
              clickable: false,
              renderBullet: (index, className) => {
                if (index < PAGINATION_BULLETS) {
                  return `<span class="${className}" data-index="${index}"></span>`;
                }

                return "";
              },
            },
            on: {
              init: (swiper) => {
                swiper.slideToLoop(0, 0, false);

                const bullets = document.querySelectorAll<HTMLElement>(
                  ".testi-pagination .swiper-pagination-bullet",
                );

                bullets.forEach((bullet) => {
                  bullet.onclick = () => {
                    const indexValue = Number(bullet.dataset.index ?? "0");
                    const targetSlide = indexValue % sliderTestimonials.length;
                    swiper.slideToLoop(targetSlide);
                  };
                });
              },
              slideChange: (swiper) => {
                const bullets = document.querySelectorAll(
                  ".testi-pagination .swiper-pagination-bullet",
                );

                bullets.forEach((bullet) => {
                  bullet.classList.remove("swiper-pagination-bullet-active");
                });

                const activeIndex = swiper.realIndex % PAGINATION_BULLETS;
                bullets[activeIndex]?.classList.add(
                  "swiper-pagination-bullet-active",
                );
              },
            },
          });

          return () => swiper.destroy(true, true);
        }
      } catch (error) {
        console.error("Error initializing Testimonials Swiper:", error);
      }
    };

    let cleanup: (() => void) | undefined;

    initializeSwiper().then((destroySwiper) => {
      cleanup = destroySwiper;
    });

    return () => {
      cleanup?.();
    };
  }, [sliderTestimonials.length]);

  return (
    <section className="testimonial-sec space">
      <div className="sec-title white">
        <span
          className="sub-title"
          data-aos="fade-up"
          data-aos-duration="900"
          data-aos-delay="300"
        >
          Clients Testimonials
        </span>
        <h2
          className="title"
          data-aos="fade-up"
          data-aos-duration="900"
          data-aos-delay="400"
        >
          Clients Say About Our Startup Services we have more then 800+
        </h2>
      </div>
      <div ref={swiperRef} className="swiper testi">
        <div className="swiper-wrapper">
          {sliderTestimonials.map((testimonial, index) => (
            <div key={index} className="swiper-slide">
              <div className="testi-card">
                <Image
                  src={testimonial.image}
                  alt={`${testimonial.name} testimonial image`}
                  width={124}
                  height={124}
                  className="testimonial-avatar"
                />
                <span className="sub-title">{testimonial.subtitle}</span>
                <h3 className="title">{testimonial.title}</h3>
                <span className="name">
                  {testimonial.name}, <small>{testimonial.role}</small>
                </span>
              </div>
            </div>
          ))}
        </div>
        <div className="swiper-pagination testi-pagination"></div>
      </div>
    </section>
  );
}
