"use client";

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

export default function BrandSection() {
  const swiperRef = useRef<HTMLDivElement>(null);

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

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

        if (swiperRef.current) {
          new Swiper(swiperRef.current, {
            loop: brandSectionData.brands.length > 8,
            autoplay: {
              delay: 3000,
              disableOnInteraction: false,
            },
            slidesPerView: 6,
            spaceBetween: 20,
            breakpoints: {
              1920: { slidesPerView: 8, spaceBetween: 30 },
              1440: { slidesPerView: 8, spaceBetween: 30 },
              1366: { slidesPerView: 6, spaceBetween: 30 },
              1201: { slidesPerView: 5, spaceBetween: 30 },
              1025: { slidesPerView: 5, spaceBetween: 30 },
              769: { slidesPerView: 4, spaceBetween: 30 },
              577: { slidesPerView: 3, spaceBetween: 30 },
              480: { slidesPerView: 2, spaceBetween: 20 },
              375: { slidesPerView: 2, spaceBetween: 20 },
            },
          });
        }
      } catch (error) {
        console.error("Error initializing Brand Swiper:", error);
      }
    };

    initializeSwiper();
  }, []);

  return (
    <div className="brand-sec space-bottom">
      <div className="container-fluid">
        <h2
          className="brand-title"
          data-aos="fade-down"
          data-aos-duration="900"
          data-aos-delay="200"
        >
          {brandSectionData.title}
        </h2>
        <div
          ref={swiperRef}
          className="swiper brand"
          data-aos="fade-up"
          data-aos-duration="900"
        >
          <div className="swiper-wrapper">
            {brandSectionData.brands.map((brand) => (
              <div key={brand.id} className="swiper-slide">
                <div className="brand-img">
                  <a href="#" title="">
                    <Image
                      src={brand.src}
                      alt={brand.alt}
                      width={143}
                      height={30}
                      className="brand-logo"
                    />
                  </a>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
