"use client"

import { useState, useRef, useCallback } from "react"
import Image from "next/image"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { Button } from "@/components/ui/button"

const TOTAL_SLIDES = 12
const SWIPE_THRESHOLD = 50

export default function SponsorshipFlipbook() {
  const [currentSlide, setCurrentSlide] = useState(0)
  const [isFlipping, setIsFlipping] = useState(false)
  const [flipDirection, setFlipDirection] = useState<"left" | "right">("left")
  const touchStartX = useRef(0)
  const touchEndX = useRef(0)

  const goTo = useCallback(
    (direction: "prev" | "next") => {
      if (isFlipping) return
      if (direction === "prev" && currentSlide === 0) return
      if (direction === "next" && currentSlide >= TOTAL_SLIDES - 1) return

      setFlipDirection(direction === "next" ? "left" : "right")
      setIsFlipping(true)

      setTimeout(() => {
        setCurrentSlide((s) =>
          direction === "next"
            ? Math.min(TOTAL_SLIDES - 1, s + 1)
            : Math.max(0, s - 1)
        )
        setIsFlipping(false)
      }, 400)
    },
    [currentSlide, isFlipping]
  )

  const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
    const rect = e.currentTarget.getBoundingClientRect()
    const clickX = e.clientX - rect.left
    if (clickX < rect.width / 2) {
      goTo("prev")
    } else {
      goTo("next")
    }
  }

  const handleTouchStart = (e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX
    touchEndX.current = e.touches[0].clientX
  }

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

  const handleTouchEnd = () => {
    const diff = touchStartX.current - touchEndX.current
    if (Math.abs(diff) > SWIPE_THRESHOLD) {
      goTo(diff > 0 ? "next" : "prev")
    }
  }

  return (
    <div className="flex flex-col items-center gap-4">
      <div
        className="relative w-full overflow-hidden rounded-xl border border-border shadow-lg bg-black cursor-pointer select-none"
        style={{ perspective: "1200px" }}
        onClick={handleClick}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        <div
          className="w-full"
          style={{
            transformOrigin:
              flipDirection === "left" ? "left center" : "right center",
            transition: isFlipping
              ? "transform 0.4s ease-in-out, opacity 0.4s ease-in-out"
              : "none",
            transform: isFlipping
              ? `rotateY(${flipDirection === "left" ? "-90deg" : "90deg"})`
              : "rotateY(0deg)",
            opacity: isFlipping ? 0 : 1,
          }}
        >
          <Image
            src={`/slides/slide-${String(currentSlide + 1).padStart(2, "0")}.jpg`}
            alt={`Sponsorship deck slide ${currentSlide + 1}`}
            width={1200}
            height={675}
            className="w-full h-auto"
            priority
            draggable={false}
          />
        </div>
      </div>

      <div className="flex items-center gap-4">
        <Button
          variant="outline"
          size="icon"
          onClick={() => goTo("prev")}
          disabled={currentSlide === 0}
          aria-label="Previous slide"
        >
          <ChevronLeft className="w-4 h-4" />
        </Button>
        <span className="text-sm text-muted-foreground min-w-[4rem] text-center">
          {currentSlide + 1} / {TOTAL_SLIDES}
        </span>
        <Button
          variant="outline"
          size="icon"
          onClick={() => goTo("next")}
          disabled={currentSlide >= TOTAL_SLIDES - 1}
          aria-label="Next slide"
        >
          <ChevronRight className="w-4 h-4" />
        </Button>
      </div>
    </div>
  )
}
