"use client"

import { useState, useEffect, useCallback, useRef } from "react"

interface FinalePhoto {
  id: string
  url: string
  title: string
  subject: string
  city: string
  county: string
}

const INTERVAL = 5000
const TRANSITION = 700

export function FinaleSlideshow() {
  const [photos, setPhotos] = useState<FinalePhoto[]>([])
  const [current, setCurrent] = useState(0)
  const [isTransitioning, setIsTransitioning] = useState(false)
  const [isPaused, setIsPaused] = useState(false)
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)

  useEffect(() => {
    fetch("/rovibe/api/finale-photos")
      .then(r => r.json())
      .then((data: FinalePhoto[]) => {
        if (data.length > 0) setPhotos(data)
      })
      .catch(() => {})
  }, [])

  const advance = useCallback((dir: 1 | -1) => {
    if (photos.length <= 1) return
    setIsTransitioning(true)
    setTimeout(() => {
      setCurrent(prev => (prev + dir + photos.length) % photos.length)
      setIsTransitioning(false)
    }, TRANSITION / 2)
  }, [photos.length])

  const goToNext = useCallback(() => advance(1), [advance])
  const goToPrev = useCallback(() => advance(-1), [advance])

  // Keyboard navigation
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === "ArrowRight" || e.key === " ") { e.preventDefault(); goToNext() }
      if (e.key === "ArrowLeft") { e.preventDefault(); goToPrev() }
    }
    window.addEventListener("keydown", handler)
    return () => window.removeEventListener("keydown", handler)
  }, [goToNext, goToPrev])

  // Auto-advance
  useEffect(() => {
    if (photos.length <= 1 || isPaused) return
    timerRef.current = setInterval(goToNext, INTERVAL)
    return () => { if (timerRef.current) clearInterval(timerRef.current) }
  }, [photos.length, isPaused, goToNext])

  if (photos.length === 0) {
    return (
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "center",
        height: "100vh", background: "#0a0a0f", color: "rgba(255,255,255,0.4)",
        fontSize: "1.1rem",
      }}>
        Nu există încă fotografii din etapa finală.
      </div>
    )
  }

  const photo = photos[current]

  return (
    <div
      style={{
        position: "relative",
        width: "100%",
        height: "100vh",
        background: "#0a0a0f",
        overflow: "hidden",
        cursor: "default",
        userSelect: "none",
      }}
      onMouseEnter={() => setIsPaused(true)}
      onMouseLeave={() => setIsPaused(false)}
    >
      {/* Background blur layer */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: `url(${photo.url})`,
        backgroundSize: "cover",
        backgroundPosition: "center",
        filter: "blur(40px) brightness(0.3)",
        transform: "scale(1.2)",
        transition: `opacity ${TRANSITION / 2}ms ease`,
        opacity: isTransitioning ? 0 : 1,
      }} />

      {/* Main photo */}
      <div style={{
        position: "absolute", inset: 0,
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: "2rem",
      }}>
        <img
          key={photo.id}
          src={photo.url}
          alt={photo.title}
          style={{
            maxWidth: "100%",
            maxHeight: "100%",
            objectFit: "contain",
            borderRadius: "0.5rem",
            boxShadow: "0 10px 60px rgba(0,0,0,0.7)",
            transition: `opacity ${TRANSITION / 2}ms ease`,
            opacity: isTransitioning ? 0 : 1,
          }}
        />
      </div>

      {/* Bottom gradient */}
      <div style={{
        position: "absolute", bottom: 0, left: 0, right: 0,
        height: "35%",
        background: "linear-gradient(to top, rgba(0,0,0,0.8), transparent)",
        pointerEvents: "none",
      }} />

      {/* Photo info — no author */}
      <div style={{
        position: "absolute", bottom: 0, left: 0, right: 0,
        padding: "1.5rem 2.5rem",
        transition: `opacity ${TRANSITION / 2}ms ease`,
        opacity: isTransitioning ? 0 : 1,
        display: "flex", justifyContent: "space-between", alignItems: "flex-end",
        flexWrap: "wrap", gap: "1rem",
      }}>
        <div>
          <h2 style={{
            color: "white", fontSize: "clamp(1.1rem, 2.5vw, 1.5rem)",
            fontWeight: 700, marginBottom: "0.3rem",
            textShadow: "0 2px 12px rgba(0,0,0,0.6)",
          }}>
            {photo.title}
          </h2>
          <p style={{
            color: "rgba(255,255,255,0.65)", fontSize: "0.9rem",
            display: "flex", gap: "0.75rem", alignItems: "center", flexWrap: "wrap",
          }}>
            <span>📍 {photo.city}, {photo.county}</span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span style={{ fontStyle: "italic" }}>{photo.subject}</span>
          </p>
        </div>
      </div>

      {/* Nav arrows */}
      <button onClick={goToPrev} aria-label="Anterior" style={arrowStyle("left")}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"/></svg>
      </button>
      <button onClick={goToNext} aria-label="Următor" style={arrowStyle("right")}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6"/></svg>
      </button>

      {/* Counter */}
      <div style={{
        position: "absolute", top: "1.25rem", right: "1.25rem",
        padding: "0.35rem 0.85rem",
        background: "rgba(0,0,0,0.5)", backdropFilter: "blur(12px)",
        borderRadius: "999px", border: "1px solid rgba(255,255,255,0.1)",
        color: "rgba(255,255,255,0.75)", fontSize: "0.82rem", fontWeight: 500,
      }}>
        {current + 1} / {photos.length}
      </div>

      {/* Pause badge */}
      {isPaused && (
        <div style={{
          position: "absolute", top: "1.25rem", left: "1.25rem",
          padding: "0.35rem 0.7rem",
          background: "rgba(0,0,0,0.5)", backdropFilter: "blur(12px)",
          borderRadius: "999px", border: "1px solid rgba(255,255,255,0.1)",
          color: "rgba(255,255,255,0.5)", fontSize: "0.75rem",
        }}>
          ⏸ Pauză
        </div>
      )}

      {/* Progress bar */}
      {!isPaused && (
        <div style={{
          position: "absolute", bottom: 0, left: 0, right: 0, height: "3px",
          background: "rgba(255,255,255,0.1)",
        }}>
          <div
            key={current}
            style={{
              height: "100%",
              background: "linear-gradient(to right, #f59e0b, #f97316)",
              animation: `progressSlide ${INTERVAL}ms linear`,
            }}
          />
        </div>
      )}

      <style>{`
        @keyframes progressSlide {
          from { width: 0% }
          to { width: 100% }
        }
      `}</style>
    </div>
  )
}

function arrowStyle(side: "left" | "right"): React.CSSProperties {
  return {
    position: "absolute",
    top: "50%",
    [side]: "1.25rem",
    transform: "translateY(-50%)",
    width: "48px",
    height: "48px",
    borderRadius: "50%",
    background: "rgba(0,0,0,0.4)",
    backdropFilter: "blur(12px)",
    border: "1px solid rgba(255,255,255,0.12)",
    color: "white",
    cursor: "pointer",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    transition: "background 0.2s, transform 0.15s",
  }
}
