"use client"

import { useState, useRef, useCallback, useEffect } from "react"
import Image from "next/image"
import type { EntertainmentRidesData, EntertainmentRideData } from "@/lib/strapi/types"
import { SectionBadge, ArrowButton, CtaButton } from "./shared"

function RideCard({ ride }: { ride: EntertainmentRideData }) {
  const videoRef = useRef<HTMLVideoElement>(null)

  const handleMouseEnter = () => {
    if (videoRef.current) {
      videoRef.current.play().catch(() => {})
    }
  }

  const handleMouseLeave = () => {
    if (videoRef.current) {
      videoRef.current.pause()
      videoRef.current.currentTime = 0
    }
  }

  return (
    <div
      data-ride-card
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      className="contain-paint flex-shrink-0 w-[287px] md:w-[311px] h-[416px] md:h-[424px] rounded-2xl overflow-hidden relative flex flex-col justify-end p-4 md:p-6 group cursor-pointer"
    >
      <Image
        src={ride.image}
        alt={ride.name}
        fill
        sizes="(min-width: 800px) 311px, 287px"
        loading="lazy"
        className={`object-cover rounded-2xl transition-all duration-500 group-hover:scale-105 ${ride.video ? 'group-hover:opacity-0' : ''}`}
      />
      {ride.video && (
        <video
          ref={videoRef}
          src={ride.video}
          preload="none"
          poster={ride.image}
          muted
          loop
          playsInline
          className="absolute inset-0 w-full h-full object-cover rounded-2xl opacity-0 transition-opacity duration-500 group-hover:opacity-100"
        />
      )}
      <div
        className="absolute inset-0 rounded-2xl pointer-events-none"
        style={{ background: "linear-gradient(180deg, rgba(8,19,37,0) 42%, rgb(3,9,18) 100%)" }}
      />
      <div className="relative z-10 flex flex-col gap-1 pointer-events-none">
        <h3 className="font-accent text-white text-[24px] md:text-[32px] leading-[1.04] tracking-[-0.72px] md:tracking-[-0.96px] font-bold">
          {ride.name}
        </h3>
        <p className="font-sans text-white/80 text-[14px] leading-[1.5] font-medium">
          {ride.description}
        </p>
      </div>
    </div>
  )
}

export default function EntertainmentRides({ data }: { data: EntertainmentRidesData }) {
  const categories = data.categories
  const [activeCategory, setActiveCategory] = useState(0)
  const scrollRef = useRef<HTMLDivElement>(null)
  const filterRef = useRef<HTMLDivElement>(null)
  const tabRefs = useRef<(HTMLButtonElement | null)[]>([])
  const mobileTabRefs = useRef<(HTMLButtonElement | null)[]>([])
  const [iconLeft, setIconLeft] = useState(0)
  const [mobileIconLeft, setMobileIconLeft] = useState(0)
  const [activePage, setActivePage] = useState(0)

  const safeCategory = categories.length > 0 ? Math.min(activeCategory, categories.length - 1) : 0
  const activeRides = categories[safeCategory]?.rides ?? []
  const CARDS_PER_PAGE = 4
  const totalPages = Math.max(1, Math.ceil(activeRides.length / CARDS_PER_PAGE))

  const goToPage = useCallback((page: number) => {
    if (!scrollRef.current) return
    const card = scrollRef.current.firstElementChild as HTMLElement | null
    const cardWidth = card?.offsetWidth || 311
    const gap = 24
    const scrollTo = page * CARDS_PER_PAGE * (cardWidth + gap)
    scrollRef.current.scrollTo({ left: scrollTo, behavior: "smooth" })
    setActivePage(page)
  }, [])

  const scrollRides = useCallback(
    (direction: "left" | "right") => {
      if (direction === "right") {
        if (activePage < totalPages - 1) {
          goToPage(activePage + 1)
        } else if (safeCategory < categories.length - 1) {
          setActiveCategory((prev) => prev + 1)
        }
      } else {
        if (activePage > 0) {
          goToPage(activePage - 1)
        } else if (safeCategory > 0) {
          setActiveCategory((prev) => prev - 1)
        }
      }
    },
    [activePage, totalPages, safeCategory, categories.length, goToPage],
  )

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollLeft = 0
    const id = window.setTimeout(() => setActivePage(0), 0)
    return () => window.clearTimeout(id)
  }, [safeCategory])

  const updateIconPosition = useCallback(() => {
    const tab = tabRefs.current[safeCategory]
    const container = filterRef.current
    if (tab && container) {
      const containerRect = container.getBoundingClientRect()
      const tabRect = tab.getBoundingClientRect()
      const tabCenterRelative = tabRect.left - containerRect.left + tabRect.width / 2
      setIconLeft(tabCenterRelative)
    }

    const mTab = mobileTabRefs.current[safeCategory]
    if (mTab) {
      const center = mTab.offsetLeft + mTab.offsetWidth / 2
      setMobileIconLeft(center)
    }
  }, [safeCategory])

  useEffect(() => {
    updateIconPosition()
  }, [safeCategory, updateIconPosition])

  useEffect(() => {
    // Use a small timeout to let fonts/layouts settle
    const timeout = setTimeout(updateIconPosition, 100)
    window.addEventListener("resize", updateIconPosition)
    return () => {
      clearTimeout(timeout)
      window.removeEventListener("resize", updateIconPosition)
    }
  }, [updateIconPosition])

  const handleScroll = useCallback(() => {
    if (!scrollRef.current) return
    const card = scrollRef.current.firstElementChild as HTMLElement | null
    const cardWidth = card?.offsetWidth || 311
    const gap = 24
    const page = Math.round(scrollRef.current.scrollLeft / (CARDS_PER_PAGE * (cardWidth + gap)))
    setActivePage(Math.min(page, totalPages - 1))
  }, [totalPages])

  useEffect(() => {
    const el = scrollRef.current
    if (!el) return
    el.addEventListener("scroll", handleScroll, { passive: true })
    return () => el.removeEventListener("scroll", handleScroll)
  }, [handleScroll])

  if (categories.length === 0) return null

  return (
    <section
      className="relative w-full overflow-hidden"
      style={{ background: "linear-gradient(130deg, #9c1d35 12%, #ba010f 90%)" }}
    >
      <div className="max-w-[1440px] mx-auto flex items-center justify-between px-5 md:px-8 lg:px-[72px] pt-10">
        <SectionBadge label={data.badge} />
        <div className="hidden md:flex gap-2">
          <ArrowButton direction="left" theme="dark" disabled={activePage === 0 && safeCategory === 0} onClick={() => scrollRides("left")} />
          <ArrowButton direction="right" theme="dark" disabled={activePage >= totalPages - 1 && safeCategory >= categories.length - 1} onClick={() => scrollRides("right")} />
        </div>
      </div>

      <div ref={filterRef} className="relative w-full mt-8 h-[140px] hidden md:block">
        <div
          className="absolute z-20 pointer-events-none transition-all duration-500 ease-in-out"
          style={{ left: `${iconLeft}px`, bottom: "-12px", transform: "translateX(-50%)" }}
        >
          <img
            src="/assets/entertainment/ride-filter-image.png"
            alt=""
            loading="lazy"
            className="h-[120px] w-auto"
            aria-hidden="true"
          />
          <div className="absolute left-[-12px] top-[38%] flex flex-col gap-[6px]">
            <div className="w-[20px] h-[1.5px] bg-[#d9d9d7]" />
            <div className="w-[20px] h-[1.5px] bg-[#d9d9d7]" />
            <div className="w-[20px] h-[1.5px] bg-[#d9d9d7]" />
          </div>
        </div>

        <div className="absolute bottom-[22px] left-0 right-0 h-[10px]">
          <img
            src="/assets/entertainment/ride-filter-vector.svg"
            alt=""
            loading="lazy"
            className="w-full h-full"
            aria-hidden="true"
            style={{ minWidth: "100%" }}
          />
        </div>

        <div className="absolute bottom-0 left-0 right-0">
          <div className="max-w-[1440px] mx-auto px-8 lg:px-[72px]">
            <div className="flex items-center justify-between">
              {categories.map((cat, i) => (
                <button
                  key={i}
                  ref={(el) => { tabRefs.current[i] = el }}
                  onClick={() => setActiveCategory(i)}
                  className={`font-heading text-[16px] uppercase whitespace-nowrap transition-colors leading-none ${
                    i === safeCategory ? "text-white font-semibold" : "text-[#bbb] hover:text-white font-normal"
                  }`}
                >
                  {cat.name}
                </button>
              ))}
              <div className="flex-shrink-0 w-5 md:w-8" />
            </div>
          </div>
        </div>
      </div>

      <div className="md:hidden px-5 mt-7 overflow-x-auto scrollbar-hide relative">
        <div className="flex items-center gap-5 min-w-max relative pt-[75px] pb-2">
          <div
            className="absolute z-20 pointer-events-none transition-all duration-500 ease-in-out"
            style={{ left: `${mobileIconLeft}px`, top: "0px", transform: "translateX(-50%)" }}
          >
            <img
              src="/assets/entertainment/ride-filter-image.png"
              alt=""
              loading="lazy"
              className="h-[75px] w-auto"
              aria-hidden="true"
            />
          </div>

          <div className="absolute top-[62px] left-0 right-0 h-[4px] w-full overflow-hidden">
             <img src="/assets/entertainment/ride-filter-vector.svg" alt="" className="w-full h-full" style={{ minWidth: "100%" }} />
          </div>

          {categories.map((cat, i) => (
            <button
              key={i}
              ref={(el) => { mobileTabRefs.current[i] = el }}
              onClick={() => setActiveCategory(i)}
              className={`font-heading text-[12px] uppercase text-center transition-colors leading-[1.2] pb-[5px] whitespace-nowrap z-10 ${
                i === safeCategory ? "text-white font-semibold" : "text-[#bbb] hover:text-white font-normal"
              }`}
            >
              {cat.name}
            </button>
          ))}
        </div>
      </div>

      <div className="mt-7 md:mt-8 pl-5 md:pl-8 lg:pl-[calc((100vw-1440px)/2+72px)] pr-5 md:pr-8">
        <div ref={scrollRef} className="flex gap-4 md:gap-6 overflow-x-auto scrollbar-hide pb-4">
          {activeRides.map((ride, i) => (
            <RideCard key={i} ride={ride} />
          ))}
        </div>
      </div>

      <div className="md:hidden flex items-center justify-end px-5 mt-2">
        <div className="flex gap-3">
          <ArrowButton direction="left" theme="dark" size="small" disabled={activePage === 0 && safeCategory === 0} onClick={() => scrollRides("left")} />
          <ArrowButton direction="right" theme="dark" size="small" disabled={activePage >= totalPages - 1 && safeCategory >= categories.length - 1} onClick={() => scrollRides("right")} />
        </div>
      </div>

      <div className="md:hidden flex justify-center mt-12 pb-8">
        <CtaButton label={data.ctaLabel} variant="white" href={data.ctaHref} />
      </div>

      <div className="hidden md:flex max-w-[1440px] mx-auto items-center justify-between px-8 lg:px-[72px] pb-38 mt-6">
        <p className="font-sans text-white/80 text-[16px] leading-[1.04]">
          Showing <span className="text-white font-semibold">{activeRides.length} </span>
          {categories[safeCategory]?.name}
        </p>
        <CtaButton label={data.ctaLabel} variant="white" href={data.ctaHref} />
      </div>

      <p
        className="font-accent font-bold absolute bottom-[91px] md:bottom-[10px] left-1/2 -translate-x-1/2 text-[59px] sm:text-[96px] md:text-[120px] lg:text-[210px] leading-[0.7] tracking-[-2px] sm:tracking-[-5.13px] md:tracking-[-6.3px] whitespace-nowrap select-none pointer-events-none"
        style={{ color: "rgba(255,255,255,0.08)" }}
      >
        {data.watermarkText}
      </p>
    </section>
  )
}



