"use client";

import { externalHref } from "@/features/events/eventLifecycle";
import { useState, useEffect, useRef } from "react";
import Image from "next/image";
import { useTranslation } from "react-i18next";
import { useLanguageStore } from "@/store/languageStore";
import {
  pickLocalized,
  type HeroBanner,
  type HomeStatistics,
} from "@/features/shared";
import BannerStats from "./BannerStats";

interface BannerCarouselProps {
  /** Hero slides of the home placement (`GET /banner-images/`, see `toHeroBanners`). */
  banners: HeroBanner[];
  /** Platform counters shown in the cards below the slider; null hides them. */
  statistics: HomeStatistics | null;
  /** Hero headline from the CMS (`hero.title_en` / `hero.title_ar`). */
  heroTitleEn?: string | null;
  heroTitleAr?: string | null;
  showStatistics?: boolean;
}

/** Placeholder for the dots-only strip; never rendered as counters. */
const EMPTY_STATISTICS: HomeStatistics = { volunteer_count: 0, volunteer_team_count: 0, organization_count: 0 };

export default function BannerCarousel({
  banners,
  statistics,
  heroTitleEn,
  heroTitleAr,
  showStatistics = true,
}: BannerCarouselProps) {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const carouselIntervalRef = useRef<ReturnType<typeof setInterval> | null>(
    null,
  );

  /*
   * Admin-managed (PDF p.11): with no current banner there is no hero. A
   * bundled artwork used to stand in, so a banner the admin had removed or
   * scheduled out stayed on the homepage as a stock image with its own baked-in
   * wording. Slides without a file are dropped for the same reason.
   */
  const slides: HeroBanner[] = banners.filter((banner) => Boolean(banner.image));
  const counters = showStatistics ? statistics : null;
  const slideCount = slides.length;

  // Auto-advance carousel every 5 s when there are multiple slides
  useEffect(() => {
    if (slideCount > 1) {
      carouselIntervalRef.current = setInterval(() => {
        setCurrentImageIndex((prev) => (prev + 1) % slideCount);
      }, 5000);
    }
    return () => {
      if (carouselIntervalRef.current)
        clearInterval(carouselIntervalRef.current);
    };
  }, [slideCount]);

  const heroTitle = pickLocalized(heroTitleEn, heroTitleAr, language);

  /**
   * The banner artwork carries its own baked-in wording, so the CMS headline is
   * used as the image's accessible name instead of being drawn over it.
   */
  const altFor = (index: number) => {
    const base = heroTitle || t("COMMON.BANNER") || "banner";
    return slides.length > 1 ? `${base} ${index + 1}` : base;
  };

  const renderSlide = (banner: HeroBanner, index: number, sizes: string) => {
    const isFirst = index === 0;
    const img = (
      <Image
        src={banner.image as string}
        alt={altFor(index)}
        fill
        sizes={sizes}
        className="object-cover"
        // First image is the LCP — load immediately with high priority
        priority={isFirst}
        loading={isFirst ? "eager" : "lazy"}
        fetchPriority={isFirst ? "high" : "low"}
      />
    );

    return (
      <div
        key={banner.id || index}
        className={`absolute w-full h-full transition-opacity duration-500 ${
          index === currentImageIndex
            ? "opacity-100 pointer-events-auto"
            : "opacity-0 pointer-events-none"
        }`}
        // Non-visible slides must not be reachable via keyboard/AT
        aria-hidden={index !== currentImageIndex ? true : undefined}
      >
        {externalHref(banner.banner_url) ? (
          <a
            href={externalHref(banner.banner_url) as string}
            target="_blank"
            rel="noopener noreferrer"
            tabIndex={index === currentImageIndex ? 0 : -1}
            style={{ display: "block", width: "100%", height: "100%" }}
            aria-label={`${altFor(index)} – ${t("COMMON.OPEN_LINK")}`}
          >
            {img}
          </a>
        ) : (
          img
        )}
      </div>
    );
  };

  if (slides.length === 0) {
    // The counters do not depend on the artwork; keep them on pages that show them.
    return counters ? <BannerStats statistics={counters} slideCount={0} currentImageIndex={0} setCurrentImageIndex={() => {}} standalone /> : null;
  }

  return (
    <div className="w-full">
      {heroTitle && <h1 className="sr-only">{heroTitle}</h1>}
      <div className="relative flex justify-center items-center">
        {/* ── Desktop Banner ────────────────────────────────── */}
        <div className="relative hidden w-full lg:block">
          <div className="flex items-center justify-center w-full">
            <div className="relative 2xl:w-[83%] w-[100%] rounded-3xl overflow-hidden laptopmain:w-[88%] laptop:w-[87%] lg:w-[90%] laptopitm:w-[90%] mx-auto 2xl:h-[680px] laptopmain:h-[600px] laptops:h-[550px] laptop:h-[635px] xl:h-[550px] lg:h-[500px] h-[450px]">
              {slides.map((banner, index) =>
                renderSlide(banner, index, "(max-width: 1024px) 100vw, 85vw"),
              )}
            </div>
          </div>
        </div>

        {/* Fixed-height containing block for the absolute slides, including tablets. */}
        <div className="relative block h-[480px] w-full md:h-[592px] lg:hidden xsl:h-[350px] xss:h-[250px]">
          {slides.map((banner, index) => renderSlide(banner, index, "100vw"))}
        </div>
      </div>

      <BannerStats
        showStatistics={Boolean(counters)}
        statistics={counters ?? EMPTY_STATISTICS}
        slideCount={slides.length}
        currentImageIndex={currentImageIndex}
        setCurrentImageIndex={setCurrentImageIndex}
      />
    </div>
  );
}
