"use client";

import React, { useRef, useEffect, useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { A11y, Mousewheel, Navigation, Pagination } from "swiper/modules";
import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/navigation";
import Image from "next/image";
import type SwiperType from "swiper";
import { withCDN } from "@/src/lib/utils";
import { getFlagUrl, extractCountry } from "@/src/lib/utils/countryFlag";

type Testimonial = { id: string | number; quote: string; author: string };

type Props = {
  testimonials: Testimonial[];
};

/**
 * The quote is clamped to a fixed height and scrolls, but the NATIVE scrollbar
 * cannot be relied on to advertise that: iOS Safari and Chrome's device
 * emulation both render overlay bars that only surface mid-gesture, and no
 * amount of ::-webkit-scrollbar styling overrides that. So below `md` we hide
 * the native bar (globals.css) and paint our own track + thumb, which is a
 * plain element and therefore always visible.
 *
 * The thumb is sized by the visible/total ratio and offset by scroll progress,
 * so its length also communicates HOW MUCH more text there is.
 */
function ScrollableQuote({ quote }: { quote: string }) {
  const scrollRef = useRef<HTMLParagraphElement | null>(null);
  const [thumb, setThumb] = useState({ height: 0, offset: 0, visible: false });

  const measure = () => {
    const el = scrollRef.current;
    if (!el) return;

    const { scrollHeight, clientHeight, scrollTop } = el;
    const overflow = scrollHeight - clientHeight;

    // Nothing to scroll -> no indicator, so it never implies hidden content.
    if (overflow <= 1) {
      setThumb((t) => (t.visible ? { ...t, visible: false } : t));
      return;
    }

    const MIN_THUMB = 28;
    const height = Math.max((clientHeight / scrollHeight) * clientHeight, MIN_THUMB);
    const offset = (scrollTop / overflow) * (clientHeight - height);

    setThumb({ height, offset, visible: true });
  };

  useEffect(() => {
    const el = scrollRef.current;
    if (!el || typeof ResizeObserver === "undefined") return;

    // ResizeObserver fires once on observe, which gives the initial measurement
    // without calling setState directly in the effect body.
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    return () => ro.disconnect();
  }, [quote]);

  return (
    <div className="relative flex-grow mb-4 sm:mb-6">
      <p
        ref={scrollRef}
        onScroll={measure}
        className="text-white text-[18px] md:text-[16px] 2xl:text-[22px] md:h-[180px] xl:h-[180px] h-full overflow-y-auto testimonial-scrollbar pr-3 leading-relaxed max-[767px]:h-[200px] max-[330px]:text-[16px]"
      >
        &quot;{quote}&quot;
      </p>

      {/* Shown at every breakpoint so mobile, tablet and desktop read the same. */}
      {thumb.visible && (
        <span
          aria-hidden="true"
          className="pointer-events-none absolute right-0 top-0 h-full w-[6px] rounded-full bg-white/20"
        >
          <span
            className="absolute left-0 w-full rounded-full bg-white/80"
            style={{ height: thumb.height, transform: `translateY(${thumb.offset}px)` }}
          />
        </span>
      )}
    </div>
  );
}

export default function TestimonialSwiper({ testimonials }: Props) {
  const prevRef = useRef<HTMLButtonElement | null>(null);
  const loopCount = Math.max(testimonials.length, 3);
  const swiperRef = useRef<any | null>(null);
  

    return (
    <div className="relative flex flex-row md:gap-2 lg:gap-13 testimonial">
      {/* LEFT Arrow Only */}
      <div className="flex xl:flex items-center md:mb-4 max-[991px]:ml-[-20px] max-[767px]:ml-[-10px] max-[767px]:mb-12">
        <button
          ref={prevRef}
          aria-label="Previous"
          className="rounded-full w-10 h-10 lg:w-20 lg:h-20 cursor-pointer "
        >
          <Image
            src={withCDN("/arrow-left-white.svg")}
            alt="Prev"
            width={28}
            height={28}
            className="cursor-pointer"
          />
        </button>
      </div>

      <div className="flex-1 overflow-hidden -mr-5 md:-mr-0 lg:-mx-16 xl:-mr-32 2xl:-mr-1 lg:-mr-20 max-[1200px]:!ml-[-7px] max-[767px]:!ml-[-30px]  max-[380px]:!ml-[-30px] testimonial-track ">
        <Swiper
          className="pb-10 md:pr-12 lg:pr-0"
          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={1}
          spaceBetween={16}
          mousewheel={{ forceToAxis: true }}
          grabCursor={true}
          simulateTouch={true}
          allowTouchMove={true}
          loop={true}
          pagination={{ clickable: true }}
          breakpoints={{
  0: {
    slidesPerView: 1,
    centeredSlides: false,   // 🔥 full width
    spaceBetween: 12,
  },
  768: {
    slidesPerView: 2,      // 👈 partial next slide
    centeredSlides: false,
    spaceBetween: 16,
  },
  1024: {
    slidesPerView: 2,
    spaceBetween: 20,
  },
}}
        >
         {testimonials.map((t) => (
          <SwiperSlide
            key={t.id}
            className="mt-2 md:mt-4 pb-14"
          >
            <div
              className="w-full h-full min-h-[175px] md:min-h-[288px] xl:min-h-[320px] border-2 border-white rounded-tl-[40px] h-full max-[767px]:max-w-[85%] max-[767px]:mx-auto"
            >
              <div className="w-full h-full flex flex-col justify-between p-4 sm:p-6 md:p-5 lg:p-10 bg-transparent max-[676px]:min-h-[234px]">
                <ScrollableQuote quote={t.quote} />
                <p className="text-[#0097DC] text-[12px] sm:text-[18px] md:text-[22px] font-bold uppercase inline-flex items-center gap-2 flex-wrap user-name">
                  <span>— {t.author}</span>
                  {getFlagUrl(extractCountry(t.author)) && (
                    /* eslint-disable-next-line @next/next/no-img-element */
                    <img
                      src={getFlagUrl(extractCountry(t.author))}
                      alt={extractCountry(t.author)}
                      width={28}
                      height={18}
                      loading="lazy"
                      className="inline-block w-[28px] h-auto rounded-[2px] shadow-sm"
                    />
                  )}
                </p>
              </div>
            </div>
          </SwiperSlide>
        ))}
        </Swiper>
      </div>

      {/* right Arrow Only */}
      <button
       onClick={() => swiperRef.current?.slideNext()}
       aria-label="Next"
       className="flex-shrink-0 transition rounded-full cursor-pointer rotate-180 max-[991px]:mr-[-25px] max-[767px]:mr-[-5px]  max-[380px]:mr-[-10px] z-10 max-[767px]:mb-12"
     >
       <Image
         src={withCDN("/arrow-left-white.svg")}
         alt="Next"
         width={28}
         height={28}
       />
     </button>

<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(.testimonial .swiper-pagination-bullet::after) {
    content: "";
    width: 16px;
    height: 16px;
    border-radius: 9999px;
    background: rgba(255,255,255,0.35)!important;
    transition: all 0.3s ease;
  }

  /* ACTIVE DOT */
  :global(.testimonial .swiper-pagination-bullet-active::after) {
    background: #0097DC!important;
    transform: scale(1.15);
  }

.testimonial .swiper-pagination.swiper-pagination-clickable.swiper-pagination-bullets.swiper-pagination-horizontal {
    bottom: -8px!important;
}
button[aria-label="Previous slide"] {
    display: block;
}
    
`}</style>
    </div>
  );
}