"use client";

import { useEffect, useState } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import type { HeroBannerSlide } from "@/types/home";
import { VideoLightbox } from "./VideoLightbox";

interface HeroBannerCarouselProps {
  slides: HeroBannerSlide[];
}

/**
 * The live homepage's `.slider-banner` — a Slick carousel with 4 real tabs
 * (order banner, "how we solve your assignment" video, grammar-checker
 * promo, plain order banner) that this app previously had no JS driving, so
 * only the first, static `.loading-home-banner` frame ever showed. This
 * reproduces the rotate + click-through behaviour using the real slide data
 * resolved server-side in `joomlaService.getHomePage()` — auto-advances like
 * the live template's Slick config (`autoplay: true`), plus the real
 * `.slick-dots` for manual control (not chevron arrows — the live site has
 * none). Autoplay pauses while the video modal is open.
 *
 * Loops via a tripled track (same technique as `WritersCarousel`): the real
 * slides are duplicated before and after themselves, so the track can always
 * keep sliding left past the last slide into a clone of the first one, then
 * snap (no transition) back to the real copy once the animation finishes —
 * instead of jumping backward when wrapping from the last slide to the first.
 */
export function HeroBannerCarousel({ slides }: HeroBannerCarouselProps) {
  const N = slides.length;
  const extendedSlides = [...slides, ...slides, ...slides];

  const [currentIndex, setCurrentIndex] = useState(N);
  const [isTransitioning, setIsTransitioning] = useState(true);
  const [videoUrl, setVideoUrl] = useState<string | null>(null);
  const [videoPoster, setVideoPoster] = useState<string | undefined>(undefined);

  const handleNext = () => {
    setIsTransitioning(true);
    setCurrentIndex((prev) => prev + 1);
  };

  const handlePrev = () => {
    setIsTransitioning(true);
    setCurrentIndex((prev) => prev - 1);
  };

  useEffect(() => {
    if (N <= 1 || videoUrl) return;
    const timer = setInterval(handleNext, 5000);
    return () => clearInterval(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [N, videoUrl]);

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

  if (N === 0) return null;

  const goTo = (index: number) => {
    setIsTransitioning(true);
    setCurrentIndex(N + index);
  };

  const activeDot = ((currentIndex % N) + N) % N;

  return (
    // `aspect-[774/450]` unconditionally (not just mobile) — the real slide
    // images' *actual* dimensions (verified directly: `home_banner_image.jpg`,
    // `AI-and-Plag-free.jpg`, `YT-thumbnail.jpg`, `home-banner-slider3.jpg`
    // are all 774x450, ratio 1.72:1 — not the 772x300 this used to say,
    // which was wrong by a full 1.5x).
    //
    // Two earlier attempts tried to make this exactly match
    // `<ServiceOrderForm>`'s height via the real site's own `align-items:
    // stretch` mechanism (removing the aspect-ratio at desktop, relying on
    // the flex row to stretch this to match) — both broke rendering
    // entirely (blank banner, then the whole row's height blowing out).
    // The underlying issue: once the aspect-ratio is removed, height
    // becomes `auto`, and the `h-full` needed on the descendants below
    // (track/anchor/image) to fill that height is a percentage resolving
    // against an `auto` ancestor — invalid per the CSS spec, and different
    // browsers handle that edge case inconsistently across this many
    // nested levels. Keeping `aspect-ratio` unconditionally trades "exact
    // pixel match with the form" for "a definite, reliable height at every
    // breakpoint with zero dependency on stretch or percentage chains" —
    // close to the form's height in practice (since the live site's own
    // hardcoded box ratio, `padding-top:58%` ≈ 1.724:1, already nearly
    // matches these images' real 1.72:1 ratio), and never collapses.
    <div className="w-full lg:w-[65%] flex flex-col">
      <div className="relative w-full aspect-[774/450] overflow-hidden rounded-[3px]">
        <div
          className={`flex ${isTransitioning ? "transition-transform duration-700 ease-in-out" : ""}`}
          style={{ transform: `translateX(-${currentIndex * 100}%)` }}
          onTransitionEnd={handleTransitionEnd}
        >
          {extendedSlides.map((slide, idx) => (
            <a
              key={`${slide.href}-${idx}`}
              href={slide.href}
              aria-label={slide.alt || "banner"}
              aria-hidden={idx !== currentIndex}
              tabIndex={idx === currentIndex ? undefined : -1}
              onClick={(e) => {
                if (slide.isVideo) {
                  e.preventDefault();
                  if (slide.videoUrl) {
                    setVideoPoster(slide.imageUrl);
                    setVideoUrl(slide.videoUrl);
                  }
                }
              }}
              target={!slide.isVideo && slide.href.startsWith("http") ? "_blank" : undefined}
              rel={!slide.isVideo && slide.href.startsWith("http") ? "noopener noreferrer" : undefined}
              className="w-full shrink-0"
            >
              <img
                src={slide.imageUrl}
                alt={slide.alt || "banner"}
                width={774}
                height={450}
                className="w-full h-auto block"
                loading={idx === currentIndex ? "eager" : "lazy"}
                fetchPriority={idx === currentIndex ? "high" : "low"}
                onError={(e) => {
                  const target = e.target as HTMLImageElement;
                  target.onerror = null;
                  target.src = "/images/home-banner-slider3.jpg";
                }}
              />
            </a>
          ))}
        </div>

        {/* Chevron arrows — desktop only (`hidden lg:flex`) */}
        {N > 1 && (
          <>
            <button
              type="button"
              aria-label="Previous banner"
              onClick={handlePrev}
              className="hidden lg:flex absolute left-0 top-1/2 -translate-y-1/2 z-10 h-5 w-[20px] items-center justify-center bg-[rgba(26,25,25,0.6)] text-black"
            >
              <ChevronLeft size={20} />
            </button>
            <button
              type="button"
              aria-label="Next banner"
              onClick={handleNext}
              className="hidden lg:flex absolute right-0 top-1/2 -translate-y-1/2 z-10 h-10 w-[30px] items-center justify-center bg-[rgba(44,42,42,0.6)] text-black"
            >
              <ChevronRight size={20} />
            </button>
          </>
        )}
      </div>

      {/* Dotted scroller: mobile only, matching live site */}
      {N > 1 && (
        <div className="flex lg:hidden justify-center items-center gap-1.5 pt-2 pb-1 z-10">
          {slides.map((s, i) => (
            <button
              key={`${s.href}-${i}`}
              type="button"
              aria-label={`Go to slide ${i + 1}`}
              onClick={() => goTo(i)}
              className="p-1 focus:outline-none"
            >
              <span
                className={`block h-2 w-2 sm:h-2.5 sm:w-2.5 rounded-full transition-all duration-200 ${
                  i === activeDot ? "scale-125" : "hover:opacity-80"
                }`}
                style={{
                  backgroundColor: i === activeDot ? "#4E6C2F" : "#d1d5db",
                }}
              />
            </button>
          ))}
        </div>
      )}

      {videoUrl && (
        <VideoLightbox videoUrl={videoUrl} poster={videoPoster} onClose={() => setVideoUrl(null)} />
      )}
    </div>
  );
}
