"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import type { ServiceReview } from "@/services/joomlaService";

interface ServiceTestimonialsProps {
  reviews: ServiceReview[];
}

/**
 * The live site's `.new_testimonials` — "What Our Happy Customers Have to
 * Say?", sourced from `ContentHelper::reviews_dynamic()`'s real GAH/
 * `Old`-layout branch (see `getServiceReviews`/the bridge's
 * `type=service-reviews` for where the real data comes from). Sits directly
 * after the blog section, same order as `service.php`
 * (`<?= $reviews_data; ?>` right after `</section>` closes `.blog_section`).
 *
 * Styling copied from the live `.new_testimonials`/`.test-testimonial`
 * rules in `templates/GAH/css/common.css`: green gradient cards
 * (`linear-gradient(270deg, #6E943E 0%, #4E741E 100%)`), 22px radius, the
 * real `quote-right.svg`/`fill-star.svg`/`CaretLeft.svg`/`CaretRight.svg`
 * icons, 3 cards visible at once on desktop (`.new_testimonials_slide`),
 * replicated here as a translate-based carousel (same looping technique as
 * `HeroBannerCarousel`/`WritersCarousel` — the real slides are tripled so
 * the track can keep sliding past the last card into a clone of the first
 * one, then snap back to the real copy once the animation finishes,
 * instead of jumping backward) rather than porting Slick, since this app
 * owns the slide data as real props.
 */
export function ServiceTestimonials({ reviews }: ServiceTestimonialsProps) {
  const [cardsToShow, setCardsToShow] = useState(3);
  const N = reviews.length;
  const [index, setIndex] = useState(N);
  const [isTransitioning, setIsTransitioning] = useState(true);

  // Real breakpoints the live site's own Slick config groups by (1 card
  // below 768px, 2 up to 1023px, 3 at 1024px+).
  useEffect(() => {
    const apply = () => {
      const w = window.innerWidth;
      setCardsToShow(w < 768 ? 1 : w < 1024 ? 2 : 3);
    };
    apply();
    window.addEventListener("resize", apply);
    return () => window.removeEventListener("resize", apply);
  }, []);

  if (N === 0) return null;

  const showArrows = N > cardsToShow;
  const extendedReviews = [...reviews, ...reviews, ...reviews];

  const goPrev = () => {
    setIsTransitioning(true);
    setIndex((i) => i - 1);
  };
  const goNext = () => {
    setIsTransitioning(true);
    setIndex((i) => i + 1);
  };

  // Seamless wrap reset once the slide-into-the-clone animation finishes.
  const handleTransitionEnd = () => {
    if (index >= 2 * N) {
      setIsTransitioning(false);
      setIndex(index - N);
    } else if (index < N) {
      setIsTransitioning(false);
      setIndex(index + N);
    }
  };

  return (
    <section className="bg-white py-6 sm:py-8 lg:py-[50px]">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <h2 className="text-center text-lg sm:text-[22px] lg:text-[28px] font-bold text-[#2A2A2A]">
          What Our Happy Customers Have to Say?
        </h2>
        <div className="mx-auto mt-2.5 h-px w-[110px] bg-[#F58E0E]" />

        <div className="relative mt-5 sm:mt-[30px]">
          {showArrows && (
            <button
              type="button"
              aria-label="Previous review"
              onClick={goPrev}
              className="hidden sm:flex absolute left-0 top-1/2 -translate-y-1/2 -translate-x-1/2 z-10 h-10 w-10 items-center justify-center"
            >
              <Image src="/images/CaretLeft.svg" alt="" width={40} height={40} />
            </button>
          )}

          <div className="overflow-hidden">
            <div
              className={`flex ${isTransitioning ? "transition-transform duration-500 ease-in-out" : ""}`}
              style={{ transform: `translateX(-${(index * 100) / cardsToShow}%)` }}
              onTransitionEnd={handleTransitionEnd}
            >
              {extendedReviews.map((review, idx) => (
                <div
                  key={`${review.id}-${idx}`}
                  className="shrink-0 px-[5px] sm:px-[13px]"
                  style={{ width: `${100 / cardsToShow}%` }}
                >
                  <div
                    className="relative overflow-hidden rounded-[22px] p-3.5 sm:p-[18px] text-white h-full"
                    style={{ background: "linear-gradient(270deg, #6E943E 0%, #4E741E 100%)" }}
                  >
                    <Image
                      src="/images/quote-right.svg"
                      alt=""
                      width={48}
                      height={48}
                      className="absolute right-0 top-0 opacity-90"
                    />

                    <p className="relative font-semibold text-sm sm:text-base leading-[18px] sm:leading-[21px]">
                      {review.position || review.name}
                    </p>
                    <p className="relative mb-0 text-[13px] sm:text-sm leading-[18px] sm:leading-[21px] text-[#f6f6f6]">
                      {review.subject} : {review.pages} Pages Deadline: {review.deadlineDays}{" "}
                      {review.deadlineDays === 1 ? "day" : "days"}
                    </p>

                    <div className="mt-1 flex">
                      {Array.from({ length: Math.max(0, Math.min(5, review.rating)) }).map((_, i) => (
                        <Image
                          key={i}
                          src="/images/fill-star.svg"
                          alt=""
                          width={14}
                          height={15}
                          className="mr-[3px] mt-[3px]"
                        />
                      ))}
                    </div>

                    <p className="relative mt-3 sm:mt-[18px] mb-5 sm:mb-[25px] text-left text-[13px] sm:text-sm leading-[18px] sm:leading-[21px] text-[#f6f6f6]">
                      {review.comment}
                    </p>

                    <p className="relative m-0 text-left font-semibold text-sm leading-[21px]">{review.name}</p>
                    {review.country && (
                      <p className="relative m-0 text-left text-[13px] leading-[21px] text-[#f6f6f6]">
                        {review.country}
                      </p>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {showArrows && (
            <button
              type="button"
              aria-label="Next review"
              onClick={goNext}
              className="hidden sm:flex absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 z-10 h-10 w-10 items-center justify-center"
            >
              <Image src="/images/CaretRight.svg" alt="" width={40} height={40} />
            </button>
          )}
        </div>

        <div className="mt-8 sm:mt-10 text-center">
          <Link
            href="/reviews"
            className="inline-block rounded-[3px] bg-[#f58e0e] px-5 py-2 text-[18px] leading-5 font-semibold text-white hover:bg-[#e07d0d] transition-colors"
          >
            View All Review
          </Link>
        </div>
      </div>
    </section>
  );
}
