"use client";

import { useState, useRef, useEffect } from "react";
import { slides } from "./constants";
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay, Pagination, EffectFade } from "swiper/modules";
import type { Swiper as SwiperClass } from "swiper";
import gsap from "gsap";
import { useGSAP } from "@gsap/react";

type AnySwiper = SwiperClass & {
  autoplay?: { start?: () => void; stop?: () => void; running?: boolean };
};
import Image from "next/image";
import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/effect-fade";

import Title from "@/components/atoms/Title";
import useTitleAnimation from "@/hooks/useTitleAnimation";

const ExcellenceMobile = () => {
  const items = slides.slice(0, 4); // show first 4 cards
  const total = items.length;
  const [active, setActive] = useState(0);
  const sectionRef = useRef<HTMLElement | null>(null);
  const swiperRef = useRef<AnySwiper | null>(null);

  useEffect(() => {
    if (!sectionRef.current) return;
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          const inView = entry.intersectionRatio >= 0.1; // 10% visible
          const s = swiperRef.current;
          if (!s || !s.autoplay) return;
          if (inView) {
            // ensure autoplay params are set before starting
            s.params = s.params || {};
            s.params.autoplay = {
              delay: 2000,
              disableOnInteraction: false,
              stopOnLastSlide: true,
            };
            s.autoplay.start?.();
          } else {
            s.autoplay.stop?.();
          }
        });
      },
      { threshold: [0, 0.1, 0.5, 1] }
    );

    observer.observe(sectionRef.current);
    return () => observer.disconnect();
  }, []);

  const format = (n: number) => String(n).padStart(2, "0");
  const backgroundRef = useRef<HTMLDivElement>(null);

  // Animate background change
  useGSAP(() => {
    if (!backgroundRef.current) return;

    gsap.to(backgroundRef.current, {
      opacity: 0,
      duration: 0.3,
      ease: "power2.inOut",
      onComplete: () => {
        if (backgroundRef.current) {
          backgroundRef.current.style.backgroundImage = `url(${items[active]?.image})`;
          gsap.to(backgroundRef.current, {
            opacity: 1,
            duration: 0.6,
            ease: "power2.inOut",
          });
        }
      },
    });
  }, [active]);

  useTitleAnimation(".excellence-section-title", ".excellence-section", {
    trigger: {
      start: "-10% 75%",
      end: "top 60%",
      toggleActions: "play none none reverse",
    },
    animation: {
      yPercent: 60,
      duration: 0.5,
      stagger: 0.09,
      ease: "power1.inOut",
    },
  });

  return (
    <section
      ref={sectionRef}
      className="relative w-full overflow-hidden excellence-section pt-16"
    >
      {/* Animated background - mobile only */}
      <div
        ref={backgroundRef}
        className="absolute inset-0 -z-10 bg-cover bg-center bg-no-repeat md:hidden"
        style={{
          backgroundImage: `url(${items[0]?.image})`,
        }}
      />
      {/* Black overlay with 40% opacity - mobile only */}
      <div className="absolute inset-0 -z-10 bg-black/40 md:hidden"></div>
      <div className="px-6">
        <div className="relative bg-white">
          <div className="container mx-auto flex justify-center items-end relative transition-opacity duration-1000 ease-in-out">
            <div className="bg-[#F5F5F5]/20 py-10 w-full max-w-[520px] mx-auto flex flex-col justify-between">
              <div className="text-center font-creato">
                <p className="mb-4 flex items-center overflow-hidden justify-center font-normal text-xl">
                  <span
                    id="excellence-number"
                    className="excellence-number overflow-hidden"
                  >
                    {format(active + 1)}
                  </span>
                  <span className="relative -top-[1px] mx-1">-</span>
                  <span className="text-[#A7A7A7]">{format(total)}</span>
                </p>
                <div className="slide-title">
                  <p
                    id="title-text"
                    className="font-normal text-[20px] md:text-[24px] leading-[100%] tracking-[0.1em] uppercase excellence-card-title"
                  >
                    {items[active]?.title}
                  </p>
                </div>
              </div>

              <div className="py-6 px-4 flex justify-center">
                <div className="relative overflow-hidden w-full h-[300px]">
                  <Swiper
                    onSwiper={(s) => (swiperRef.current = s)}
                    direction="horizontal"
                    effect="fade"
                    speed={1000}
                    slidesPerView={1}
                    spaceBetween={0}
                    centeredSlides={true}
                    onSlideChange={(swiper) => setActive(swiper.realIndex)}
                    loop={false}
                    /* autoplay is controlled by IntersectionObserver */
                    pagination={{ clickable: true }}
                    fadeEffect={{
                      crossFade: true,
                    }}
                    modules={[Autoplay, Pagination, EffectFade]}
                    className="h-full"
                  >
                    {items.map((data) => (
                      <SwiperSlide key={data.id}>
                        <div className="w-full h-[300px] relative">
                          <Image
                            src={data.image}
                            alt={data.title}
                            fill
                            className="object-cover"
                          />
                        </div>
                      </SwiperSlide>
                    ))}
                  </Swiper>
                </div>
              </div>

              <div className="text-center overflow-hidden mt-4 flex items-center justify-center px-4">
                <p
                  id="excellence-description"
                  className="max-w-full mx-auto font-creato text-[#333] text-[clamp(14px,1.5vw,16px)] leading-relaxed tracking-wide excellence-description text-left"
                >
                  {items[active]?.description}
                </p>
              </div>

              <style jsx global>{`
                .swiper-pagination-bullet {
                  background: #d1d1d1 !important;
                  opacity: 1;
                }
                .swiper-pagination-bullet-active {
                  background: #dd577f !important;
                }
              `}</style>
            </div>
          </div>
        </div>
      </div>

      <div className="pb-4 pt-12">
        <h3 className="font-times-sans text-white text-left pl-4 text-[clamp(30px,10.7vw,36px)]">
          All Eyes on Designs
        </h3>
      </div>
      {/* <div className="w-full h-32 "></div> */}
    </section>
  );
};

export default ExcellenceMobile;
