"use client";

import { useEffect, useRef } from "react";
import { SectionIcon } from "./icons";

export interface TestimonialItem {
  featured?: boolean;
  tone?: "default" | "green" | "sand";
  stamp?: string;
  quote: string;
  trip_strip?: string;
  author_initial: string;
  author_name: string;
  author_meta?: string;
}

interface TestimonialsSliderProps {
  items: ReadonlyArray<TestimonialItem>;
}

interface SwiperHandle {
  destroy: (deleteInstance?: boolean, cleanStyles?: boolean) => void;
  update: () => void;
}

/**
 * 3D coverflow slider used at every breakpoint. Slides per view scales with
 * width (1 → 2 → 3) and the centred slide tilts forward with adjacent slides
 * faded behind it.
 */
export function TestimonialsSlider({ items }: TestimonialsSliderProps) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!containerRef.current || items.length === 0) return;

    let cancelled = false;
    let instance: SwiperHandle | null = null;

    const init = async () => {
      const [{ default: Swiper }, modules] = await Promise.all([
        import("swiper"),
        import("swiper/modules"),
      ]);
      if (cancelled || !containerRef.current) return;

      const { EffectCoverflow, Pagination, Keyboard, A11y, Autoplay } = modules;
      type SwiperCtor = new (el: Element, opts: Record<string, unknown>) => SwiperHandle;

      instance = new (Swiper as unknown as SwiperCtor)(containerRef.current, {
        modules: [EffectCoverflow, Pagination, Keyboard, A11y, Autoplay],
        effect: "coverflow",
        grabCursor: true,
        centeredSlides: true,
        slidesPerView: "auto",
        loop: items.length > 2,
        speed: 700,
        coverflowEffect: {
          rotate: 14,
          stretch: 0,
          depth: 220,
          modifier: 1,
          slideShadows: false,
        },
        autoplay: {
          delay: 5500,
          disableOnInteraction: false,
          pauseOnMouseEnter: true,
        },
        keyboard: { enabled: true },
        pagination: { el: ".t-swiper-pagination", clickable: true },
        breakpoints: {
          // Desktop opens up more slides, with the coverflow angle exaggerated.
          1024: {
            coverflowEffect: {
              rotate: 22,
              depth: 320,
              stretch: -10,
              modifier: 1,
              slideShadows: false,
            },
          },
        },
      });
    };

    void init();

    return () => {
      cancelled = true;
      try {
        instance?.destroy(true, true);
      } catch {
        // ignore
      }
    };
  }, [items]);

  if (items.length === 0) return null;

  return (
    <div className="t-swiper-wrap" aria-roledescription="carousel">
      <div className="swiper t-swiper" ref={containerRef}>
        <div className="swiper-wrapper">
          {items.map((t, i) => {
            const classes = ["t-card"];
            if (t.featured) classes.push("featured");
            if (t.tone && t.tone !== "default") classes.push(t.tone);
            return (
              <div className="swiper-slide" key={i}>
                <article className={classes.join(" ")}>
                  {t.stamp ? (
                    <span className="stamp">
                      <span className="d" />
                      {t.stamp}
                    </span>
                  ) : null}
                  <span className="qmark" aria-hidden="true">،،</span>
                  <span className="stars" aria-label="5 stars">★★★★★</span>
                  <p className="quote">{t.quote}</p>
                  {t.trip_strip ? (
                    <span className="trip-strip">
                      <SectionIcon name="map-pin" size={14} />
                      {t.trip_strip}
                    </span>
                  ) : null}
                  <div className="author">
                    <span className="avatar">{t.author_initial}</span>
                    <div className="meta">
                      <span className="name">{t.author_name}</span>
                      {t.author_meta ? <span className="sub">{t.author_meta}</span> : null}
                    </div>
                  </div>
                </article>
              </div>
            );
          })}
        </div>
      </div>
      <div className="t-swiper-pagination" />
    </div>
  );
}
