"use client";

import { useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay } from "swiper/modules";
import "swiper/css";
import type { CarouselBlock, GalleryImage } from "@/types";

interface Props {
  data: CarouselBlock;
}

export default function GalleryClient({ data }: Props) {
  const images: GalleryImage[] = Array.isArray(data?.images) ? data.images : [];
  const [activeIndex, setActiveIndex] = useState(0);
  const totalSlides = images.length;
  const progressWidth = totalSlides > 0 ? ((activeIndex + 1) / totalSlides) * 100 : 0;

  if (!totalSlides) return null;

  return (
    <section className="w-full bg-[#efe9de] pb-[5px] overflow-hidden">
      <Swiper
        modules={[Autoplay]}
        spaceBetween={10}
        slidesPerView={"auto"}
        centeredSlides={true}
        loop={true}
        autoplay={{ delay: 3000, disableOnInteraction: false }}
        onSlideChange={(swiper) => setActiveIndex(swiper.realIndex)}
        className="pb-8"
      >
        {images.map((img, idx) => {
          if (!img.url) return null;
          return (
            <SwiperSlide
              key={img.id ?? idx}
              className="!w-[100vw] md:!w-[485px] lg:!w-[800px]"
            >
              {() => (
                <div
                  className="relative block w-full md:w-[485px] lg:w-[800px] h-[300px] md:h-[335px] lg:h-[500px] mb-5 mt-2 select-none touch-pan-y overflow-hidden"
                  style={{ backgroundImage: `url(${img.url})`, backgroundSize: "cover", backgroundPosition: "center" }}
                />
              )}
            </SwiperSlide>
          );
        })}
      </Swiper>

      <div className="max-w-xl mx-auto px-4 mt-8 flex items-center justify-between gap-6 pb-10">
        <span className="text-[14px] font-bold text-black">
          {(activeIndex + 1).toString().padStart(2, "0")}
        </span>
        <div className="relative flex-1 h-[2px] bg-gray-300 overflow-hidden">
          <div
            className="absolute top-0 left-0 h-full bg-[#555] transition-all duration-500 ease-out"
            style={{ width: `${progressWidth}%` }}
          />
        </div>
        <span className="text-[14px] font-bold text-black">
          {totalSlides.toString().padStart(2, "0")}
        </span>
      </div>
    </section>
  );
}
