"use client";

import React, { useMemo, useRef, useState } from "react";
import Image from "next/image";
import ImageLightbox from "@/src/components/ui/ImageLightbox";
import LanguageAwareLink from "@/src/lib/utils/LanguageAwareLink";
import { detailHref } from "@/src/lib/utils/detailHref";


// Swiper v11+ imports
import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, Mousewheel, Pagination, A11y } from "swiper/modules";

// Swiper CSS (required)
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";

import type { Activity } from "@/src/lib/services/workshopService";
import { Button } from "@/src/components/ui/button";
import { withCDN } from "@/src/lib/utils";
import { useLanguage } from "@/src/lib/context/LanguageContext";
import { mapActivitiesToWorkshopCards, MappedWorkshopCard } from "@/src/lib/utils/workshopMapper";

type Props = { data: Activity[] };

export default function
  SwiperCarouselClient({ data }: Props) {
  const { currentLanguage } = useLanguage();
  const mappedCards = mapActivitiesToWorkshopCards(data);

  // Lightbox over every activity image, opened on the card that was clicked.
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
  const resolveSrc = (src: string) => (src.startsWith("http") ? src : withCDN(src));
  const cardImages = useMemo(
    () => mappedCards.map((c: MappedWorkshopCard) => resolveSrc(c.imageSrc)),
    [mappedCards],
  );
  const prevRef = useRef<HTMLButtonElement | null>(null);
  const loopCount = Math.max(data.length, 3);
  const swiperRef = useRef<any | null>(null);
  const [isBeginning, setIsBeginning] = useState(true);
  const [isEnd, setIsEnd] = useState(false);


return (
    <div className="relative flex flex-row md:gap-2 lg:gap-5">
      {/* LEFT Arrow Only */}
      <div className="w-[30px] flex xl:flex items-center mb-4 z-99 max-[360px]:ml-[-16px]">
        <button
         ref={prevRef}
         disabled={isBeginning}
                aria-label="Previous"
         className={`rounded-full bg-white w-10 h-10 lg:w-13 lg:h-20 mt-[-140px] max-[767px]:mt-[-45px] transition
           ${
             isBeginning
               ? "opacity-40 cursor-not-allowed"
               : "opacity-100 cursor-pointer"
           }`}
       >
         <Image
           src={withCDN("/arrow-left.svg")}
           alt="Prev"
           width={28}
           height={28}
         />
       </button>
      </div>

      <div className="flex-1 overflow-hidden px-2 md:px-0 slider-activity ">
        <Swiper
          className="pb-10 px-2"
          modules={[Navigation, Mousewheel, Pagination, A11y]}
          onSwiper={(swiper) => {
            swiperRef.current = swiper;
            
             setIsBeginning(swiper.isBeginning);
             setIsEnd(swiper.isEnd);

            // make sure navigation is initialized (useful if prevRef became available after init)
            try {
              if (
                swiper.navigation &&
                typeof swiper.navigation.init === "function"
              ) {
                swiper.navigation.init();
                swiper.navigation.update();
              }
            } catch (e) {
              // ignore
            }

            return swiper;
          }}
           onSlideChange={(swiper) => {
           setIsBeginning(swiper.isBeginning);
           setIsEnd(swiper.isEnd);
          }}

          onBeforeInit={(swiper: any) => {
            // set Swiper runtime params so it creates correct clones for auto-width slides
            swiper.params.loopedSlides = loopCount;
            swiper.loopedSlides = loopCount;

            // ── IMPORTANT: wire up our prev button so it becomes Swiper's prevEl
            if (!swiper.params.navigation) swiper.params.navigation = {};
            swiper.params.navigation.prevEl = prevRef.current;
            // (optional) if you had a next button: swiper.params.navigation.nextEl = nextRef.current;
          }}
          slidesPerView={1}
          spaceBetween={12}
          mousewheel={{ forceToAxis: true }}
          grabCursor={true}
          simulateTouch={true}
          allowTouchMove={true}
          loop={false}
          pagination={{ clickable: true }}
          breakpoints={{
             0: {
               slidesPerView: 1,  // 👈 shows slight next slide
               centeredSlides: true,
               spaceBetween: 12,
             },
             600: {
               slidesPerView: 2,
               centeredSlides: false,
             },
             1024: {
               slidesPerView: 3,
            },
           }}

        >

          {mappedCards.map((card, idx) => (
            <SwiperSlide
              key={idx}
              className=" flex justify-center"
            >
              <div className="w-full max-w-[310px] md:max-w-none mx-auto bg-white bg-opacity-90 rounded-3xl overflow-hidden transition-shadow flex flex-col">
                <div
                  className="w-full h-[180px] md:h-[200px] lg:h-[220px] xl:h-[280px] relative rounded-3xl overflow-hidden cursor-pointer"
                  onClick={() => setLightboxIndex(idx)}
                >
                  <Image
                    src={resolveSrc(card.imageSrc)}
                    alt={card.title}
                    fill
                    className="object-cover"
                  />
                 </div>

                <div className="pt-4 flex flex-col flex-grow pb-4">
                  <h3 className="text-[24px] xl:text-[35px] font-bold text-[#0097DC] uppercase mb-1">
                    {card.title}
                  </h3>

                  <p className="text-[16px] lg:text-[18px] text-[#58585A] line-clamp-3 mb-4 xl:text-[22px] lg:w-[90%] lg:min-h-[70px] font-light max-[600px]:min-h-[50px]">
                    <span className="font-medium xl:font-light">{card.idealForText}</span>
                  </p>

                  <Button
                    asChild
                    size="lg"
                    className="w-full bg-[#0097DC] hover:bg-[#0097DC]  hover:shadow-[10px_14px_14px_#0000000D] active:bg-[#0084C1] active:shadow-[10px_14px_14px_#0000000D] text-white text-[13px] md:text-[15px] py-2.5 px-3 md:px-5 rounded-full flex items-center justify-center gap-1.5 md:gap-2 mb-10 cursor-pointer text-center leading-tight whitespace-normal h-auto min-h-[45px] xl:text-[24px] xl:min-h-[60px]"
                  >
                    <LanguageAwareLink href={detailHref("/workshops", card.id, card.title)}>
                      <img
                        src="https://yefranchisees.b-cdn.net/frontend/gear.png"
                        alt="Gear icon"
                        className="w-4 h-4 md:w-5 md:h-5 shrink-0"
                      />
                      {card.ctaButtonText}
                    </LanguageAwareLink>
                  </Button>
                </div>
              </div>
            </SwiperSlide>
          ))}
        </Swiper>
      </div>
      
      <div className="flex xl:flex items-center mb-4 z-99 max-[767px]:mr-[0px] max-[360px]:mr-[-16px]">
      {/* RIGHT BUTTON */}
       <button
         onClick={() => swiperRef.current?.slideNext()}
         disabled={isEnd}
         aria-label="Next"
         className={`flex-shrink-0 bg-white rounded-full mt-[-140px] max-[767px]:mt-[-45px] transition
           ${
             isEnd
               ? "opacity-40 cursor-not-allowed"
               : "opacity-100 cursor-pointer"
           }`}
       >
         <Image
           src={withCDN("/arrow-right.svg")}
           alt="Next"
           width={28}
           height={28}
         />
       </button>
      </div>


<style jsx>{`
 /* Hide scrollbar */
  :global(.swiper) {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
  :global(.swiper::-webkit-scrollbar) {
    display: none;
  }
  :global(.swiper-button-next) {
    display: none !important;
  }

  /* ---------- PAGINATION ---------- */

  /* 40px HITBOX */
  :global(.swiper-pagination-bullet) {
    width: 40px;
    height: 40px;
    background: transparent;
    opacity: 1;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    margin: 0 6px !important;
  }

  /* 16px DOT */
  :global(.swiper-pagination-bullet::after) {
    content: "";
    width: 16px;
    height: 16px;
    border-radius: 9999px;
    background: #dae2ea !important;
    transition: all 0.3s ease;
  }
  /* ACTIVE DOT */
  :global(.swiper-pagination-bullet-active::after) {
    background: #0097DC !important;
    transform: scale(1.15);
  }
@media (min-width: 1024px) {
.swiper-pagination {
    bottom: -7px!important;
}
} 
 `}</style>

      <ImageLightbox
        images={cardImages}
        index={lightboxIndex}
        onClose={() => setLightboxIndex(null)}
      />
    </div>
  );
}