"use client";

import React, { useMemo, useRef, useState } from "react";
import Image from "next/image";
import ImageLightbox from "@/src/components/ui/ImageLightbox";
// 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 { withCDN } from "@/src/lib/utils";

type Teacher = {
  id: string | number;
  name: string;
  image: string;
  experienceYears: string | number;
  qualification: string;
};

export default function TeacherSwiper({ teachers }: { teachers: Teacher[] }) {
  const prevRef = useRef<HTMLButtonElement | null>(null);

  // Lightbox over the teacher portraits, opened on the one clicked.
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
  const teacherImages = useMemo(
    () => teachers.map((t) => t.image).filter(Boolean),
    [teachers],
  );
  const loopCount = Math.max(teachers.length, 3);
  const swiperRef = useRef<any | null>(null);
const showNavigation = teachers.length > 3;
    return (
    <div className="relative flex flex-row gap-3 lg:gap-5 teacher-slider-container ">
      {/* LEFT Arrow Only */}
      <div className="flex xl:flex items-center mb-4 md:w-[40px] max-[767px]:mb-35 max-[360px]:ml-[-20px]">
        <button
          ref={prevRef}
          aria-label="Previous"
          className="py-2 rounded-full w-10 h-10 lg:w-20 lg:h-20 cursor-pointer pl-3 pr-0"
        >
          <Image
            src={withCDN("/arrow-left.svg")}
            alt="Prev"
            width={28}
            height={28}
            className="cursor-pointer"
          />
        </button>
      </div>

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

            // 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;
          }}
          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={3}
          spaceBetween={12}
          mousewheel={{ forceToAxis: true }}
          grabCursor={true}
          simulateTouch={true}
          allowTouchMove={true}
          loop={false}
          pagination={{ clickable: true }}
          breakpoints={{
            0: {
              slidesPerView: 1,
              centeredSlides: false,
              spaceBetween: 12,
            },
            768: {
              slidesPerView: 3,
              spaceBetween: 10,   // reduce gap
            },
            1024: {
              slidesPerView: 3,
              spaceBetween: 24,
            },
          }}
        >
          {teachers.map((t, idx) => (
            <SwiperSlide key={t.id} className="flex justify-center">
              <article className="w-full bg-white rounded-2xl pb-14">
                <div className="relative m-[4px] rounded-2xl overflow-hidden bg-slate-100">
                  {/* Click target is the wrapper so the experience badge
                      overlaying the photo doesn't swallow the click. */}
                  <div
                    className="relative aspect-[3/3] w-full h-[255px] md:h-[200px] lg:h-[255px] xl:w-[380px] xl:h-[300px] overflow-hidden rounded-xl cursor-pointer teacher-slider-image"
                    onClick={() => setLightboxIndex(idx)}
                  >
                    <Image
                      src={t.image}
                      alt={t.name}
                      fill
                      className="object-cover"
                    />

                    <div className="absolute bottom-8 left-0 w-[144px] h-[50px] md:w-[124px] lg:w-[174px] md:h-[60px]">
                      <Image
                        src={withCDN("/Rectangle.svg")}
                        alt="Experience badge"
                        fill
                      />

                      <div className="absolute inset-0 flex items-center pl-4 md:pl-2 lg:pl-4">
                        <span className="text-white font-bold text-[30px] lg:text-[50px] leading-none">
                          {t.experienceYears}
                        </span>

                        <div className="flex flex-col leading-none ml-2">
                          <span className="text-white text-[14px] md:text-[11px] lg:text-[14px] font-light">
                            years of
                          </span>
                          <span className="text-white text-[14px] md:text-[11px] lg:text-[14px] font-light">
                            experience
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="px-1 md:px-4 pb-4 pt-2">
                  <p className="text-[20px] xl:text-[30px] xl:leading-[40px] tracking-wide text-[#0097DC] uppercase font-bold">
                    {t.name}
                  </p>
                  <p className="mt-1 text-[18px] xl:text-[22px] xl:leading-[30px]">
                    <span className="font-[300] text-[#58585A]">
                      Qualification:
                    </span>{" "}
                    <span className="font-[300] text-[#58585A]">
                    {t.qualification}
                    </span>
                  </p>
                </div>
              </article>
            </SwiperSlide>
          ))}
        </Swiper>
      </div>

    {showNavigation && (
  <div className="flex xl:flex items-center mb-4 max-[767px]:mb-35 max-[360px]:mr-[-10px]">
    {/* RIGHT BUTTON */}
    <button
      onClick={() => swiperRef.current?.slideNext()}
      aria-label="Next"
      className="flex-shrink-0 transition bg-white rounded-[50%] cursor-pointer"
    >
      <Image
        src={withCDN("/arrow-right.svg")}
        alt="Next"
        width={28}
        height={28}
      />
    </button>
  </div>
)}

<style jsx>{`
/* Pagination container spacing */
:global(.swiper-pagination-bullet) {
  width: 40px;
  height: 40px;
  background: transparent;
  opacity: 1;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin: 0 !important;
}

/* Actual dot */
:global(.swiper-pagination-bullet::after) {
  content: "";
  width: 16px;
  height: 16px;
  background: #0097dc;
  border-radius: 50%;
  opacity: 0.3;
  transition: all 0.2s ease;
}

/* Active dot */
:global(.swiper-pagination-bullet-active::after) {
  opacity: 1;
}
.swiper-pagination.swiper-pagination-clickable.swiper-pagination-bullets.swiper-pagination-horizontal {
    height: 40px;
}  
`}</style>

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