"use client"
import { useState, useEffect, useCallback, useRef } from 'react'
import Image from 'next/image'
import MGMButton from './MGMButton'
import type { HeroData } from '@/lib/strapi/types'

interface HeroSliderProps {
  data: HeroData
}

export default function HeroSlider({ data }: HeroSliderProps) {
  const slides = data.slides ?? []
  const [activeSlide, setActiveSlide] = useState(0)
  const [isPaused, setIsPaused] = useState(false)
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
  const touchStartX = useRef<number | null>(null)
  const touchEndX = useRef<number | null>(null)

  const goToSlide = useCallback((index: number) => {
    setActiveSlide(index)
  }, [])

  // Touch handlers for mobile swipe
  const handleTouchStart = useCallback((e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX
  }, [])

  const handleTouchMove = useCallback((e: React.TouchEvent) => {
    touchEndX.current = e.touches[0].clientX
  }, [])

  const handleTouchEnd = useCallback(() => {
    if (touchStartX.current === null || touchEndX.current === null) return

    const diff = touchStartX.current - touchEndX.current
    const threshold = 50 // minimum swipe distance

    if (Math.abs(diff) > threshold) {
      if (diff > 0) {
        // Swipe left - go to next slide
        setActiveSlide((prev) => (prev + 1) % slides.length)
      } else {
        // Swipe right - go to previous slide
        setActiveSlide((prev) => (prev - 1 + slides.length) % slides.length)
      }
    }

    touchStartX.current = null
    touchEndX.current = null
  }, [])

  useEffect(() => {
    if (isPaused) return
    intervalRef.current = setInterval(() => {
      setActiveSlide((prev) => (prev + 1) % slides.length)
    }, 5000)
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current)
    }
  }, [isPaused])

  if (slides.length === 0) return null

  return (
    <section
      className="w-full lg:h-[100vh] relative"
      onMouseEnter={() => setIsPaused(true)}
      onMouseLeave={() => setIsPaused(false)}
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
    >
      <div className="relative w-full h-full min-h-[70vh] sm:min-h-[600px] lg:min-h-0 overflow-hidden flex flex-col">
        {/* Mobile Spacer to set height based on first image's aspect ratio */}
        {slides.length > 0 && (
          <div className="lg:hidden w-full relative">
            <Image
              src={(slides[0].mobileBackgroundImage || slides[0].backgroundImage)!}
              alt="spacer"
              width={1000}
              height={1000}
              className="w-full h-auto opacity-0 pointer-events-none"
            />
          </div>
        )}

        {/* Background Images */}
        {slides.map((slide, index) => (
          <div
            key={slide.id}
            className={`absolute inset-0 transition-opacity duration-700 ease-in-out ${index === activeSlide ? 'opacity-100 z-10' : 'opacity-0 z-0'
              }`}
          >
            <Image
              src={(slide.mobileBackgroundImage || slide.backgroundImage)!}
              alt={slide.thumbnailAlt}
              fill
              sizes="100vw"
              loading={index === 0 ? "eager" : "lazy"}
              decoding={index === 0 ? "sync" : "async"}
              fetchPriority={index === 0 ? "high" : "low"}
              className="lg:hidden object-contain object-bottom bg-[#f4f7fb]"
            />
            <Image
              src={slide.backgroundImage!}
              alt={slide.thumbnailAlt}
              fill
              sizes="100vw"
              loading={index === 0 ? "eager" : "lazy"}
              decoding={index === 0 ? "sync" : "async"}
              fetchPriority={index === 0 ? "high" : "low"}
              className="hidden lg:block object-cover object-top"
            />
          </div>
        ))}

        {/* Bottom gradient overlay - stronger on mobile */}
        <div
          className="absolute inset-0 z-20 hidden lg:block"
          style={{
            background: 'linear-gradient(to bottom, rgba(0,0,0,0) 25.8%, rgba(0,0,0,0.7) 86%)',
          }}
        />
        <div
          className="absolute inset-0 z-20 lg:hidden"
          style={{
            background: 'linear-gradient(to bottom, rgba(0,0,0,0) 39.7%, rgba(0,0,0,0.75) 61.2%)',
          }}
        />



        {/* Content - positioned at bottom */}
        <div className="absolute bottom-0 left-0 right-0 z-30 px-[18px] pb-[16px] lg:px-[32px] lg:pb-[32px]">
          <div className="flex items-end justify-between gap-6">
            {/* Left content */}
            <div className="flex flex-col gap-[20px] w-full lg:max-w-[749px]">
              {/* Heading */}
              <div className="relative min-h-[40px] md:min-h-[60px] lg:min-h-[75px]">
                {slides.map((slide, index) => (
                  <h1
                    key={slide.id}
                    className={`font-heading text-white text-[28px] min-[375px]:text-[32px] sm:text-[44px] lg:text-[68px] leading-[1.04] tracking-[-1.32px] lg:tracking-[-2.04px] whitespace-nowrap md:whitespace-pre-line transition-all duration-700 ease-in-out ${index === activeSlide
                      ? 'opacity-100 translate-y-0 relative'
                      : 'opacity-0 translate-y-4 absolute top-0 left-0 pointer-events-none'
                      }`}
                  >
                    {slide.heading}
                  </h1>
                ))}
              </div>

              {/* Description with rotating highlight */}
              <div className="font-sans font-medium text-[16px] lg:text-[18px]">
                <p className="text-white/[0.76] leading-[1.5]">
                  {slides[activeSlide].description}{' '}
                  <span
                    className="inline font-medium text-[#ffffffc2]"
                  >
                    {slides[activeSlide].highlight}
                  </span>
                </p>
              </div>

              {/* CTA Button */}
              <div className="flex items-start">
                <MGMButton text={data.ctaLabel || 'Explore Our Businesses'} href={data.ctaHref || '/about'} />
              </div>

              {/* Mobile progress dots */}
              <div className="flex lg:hidden gap-[4px] items-center">
                {slides.map((_, index) => (
                  <button
                    key={index}
                    onClick={() => goToSlide(index)}
                    className={`h-[5px] w-[44px] rounded-[6.23px] transition-colors duration-300 ${index === activeSlide
                      ? 'bg-[#c5c5c5]'
                      : 'bg-[rgba(235,235,235,0.5)]'
                      }`}
                    aria-label={`Go to slide ${index + 1}`}
                  />
                ))}
              </div>
            </div>

            {/* Desktop thumbnails */}
            <div className="hidden lg:flex gap-[12px] flex-shrink-0">
              {slides.map((slide, index) => (
                <button
                  key={slide.id}
                  onClick={() => goToSlide(index)}
                  className={`relative rounded-[12.718px] overflow-hidden flex-shrink-0 w-[108px] h-[75.6px] transition-all duration-300 ${index === activeSlide
                    ? 'ring-2 ring-white'
                    : 'opacity-70 hover:opacity-100'
                    }`}
                >
                  <Image
                    src={(slide.thumbnail || slide.backgroundImage)!}
                    alt={slide.thumbnailAlt}
                    fill
                    sizes="108px"
                    loading="lazy"
                    className="object-cover"
                  />
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}
