'use client'

import { useState, useRef } from 'react'
import { useRouter } from 'next/navigation'
import Image from 'next/image'
import { motion } from 'framer-motion'
import Hotspot from './Hotspot'
import type { HotspotArea } from '@/lib/types'

/** Znajduje hotspot pod danymi współrzędnymi (w %). Przy nakładce zwraca ostatni (na wierzchu). */
function findHotspotAt(spots: HotspotArea[], xPercent: number, yPercent: number): HotspotArea | null {
  const matches = spots.filter(
    (s) =>
      xPercent >= s.position.x &&
      xPercent <= s.position.x + s.position.width &&
      yPercent >= s.position.y &&
      yPercent <= s.position.y + s.position.height
  )
  return matches.length > 0 ? matches[matches.length - 1]! : null
}

const hotspots: HotspotArea[] = [
  {
    id: 'sklep',
    label: 'Giełda łodzi',
    description: 'Ogłoszenia sprzedaży i kupna',
    href: '/sklep',
    position: { x: 35, y: 65, width: 30, height: 25 }
  },
  {
    id: 'blog',
    label: 'Blog',
    description: 'Porady żeglarskie',
    href: '/blog',
    position: { x: 45, y: 5, width: 10, height: 8 }
  },
  {
    id: 'wynajem',
    label: 'Wynajem',
    description: 'Wypożycz żaglówkę',
    href: '/wynajem',
    position: { x: 40, y: 15, width: 20, height: 20 }
  },
  {
    id: 'serwis',
    label: 'Serwis',
    description: 'Renowacje i naprawy',
    href: '/serwis',
    position: { x: 22, y: 48, width: 15, height: 20 }
  },
  {
    id: 'wyposazenie',
    label: 'Wyposażenie',
    description: 'Osprzęt i akcesoria',
    href: '/wyposazenie',
    position: { x: 35, y: 35, width: 30, height: 25 }
  }
]

export default function BoatHero() {
  const router = useRouter()
  const [activeHotspot, setActiveHotspot] = useState<string | null>(null)
  const [flipped, setFlipped] = useState(false)
  const [isZooming, setIsZooming] = useState(false)
  const [zoomTarget, setZoomTarget] = useState<{ x: number; y: number } | null>(null)
  const [zoomingToSpot, setZoomingToSpot] = useState<string | null>(null)
  const heroRef = useRef<HTMLElement>(null)

  const getPercentFromEvent = (e: React.MouseEvent) => {
    const el = heroRef.current
    if (!el) return null
    const rect = el.getBoundingClientRect()
    const x = ((e.clientX - rect.left) / rect.width) * 100
    const y = ((e.clientY - rect.top) / rect.height) * 100
    return { x, y }
  }

  const handleOverlayClick = (e: React.MouseEvent) => {
    const pos = getPercentFromEvent(e)
    if (!pos) return
    const spot = findHotspotAt(hotspots, pos.x, pos.y)
    if (spot) handleHotspotClick(spot)
  }

  const handleOverlayMouseMove = (e: React.MouseEvent) => {
    const pos = getPercentFromEvent(e)
    if (!pos) return
    const spot = findHotspotAt(hotspots, pos.x, pos.y)
    setActiveHotspot(spot?.id ?? null)
  }

  const handleHotspotClick = (spot: HotspotArea) => {
    const targetX = spot.position.x + spot.position.width / 2 - 50
    const targetY = spot.position.y + spot.position.height / 2 - 50

    setZoomTarget({ x: targetX, y: targetY })
    setZoomingToSpot(spot.id)
    setIsZooming(true)

    const href = `${spot.href}?from=hero`

    setTimeout(() => {
      router.push(href)
    }, 2000)
  }

  return (
    <section ref={heroRef} className="relative w-full h-screen overflow-hidden bg-blue-950">
      <div className="absolute inset-0 z-0 overflow-hidden">
        <motion.div
          className="relative w-full h-full"
          animate={
            isZooming && zoomTarget
              ? {
                  scale: 2.5,
                  x: `${-zoomTarget.x}%`,
                  y: `${-zoomTarget.y}%`,
                }
              : { scale: 1, x: '0%', y: '0%' }
          }
          transition={{ duration: 2, ease: 'easeInOut' }}
        >
          <Image
            src="/images/main_image.jpg"
            alt="Widok z góry na żaglówkę"
            fill
            priority
            quality={90}
            className="object-cover"
          />
        </motion.div>

        {/* Overlay gradient for better hotspot visibility */}
        <div className="absolute inset-0 bg-gradient-to-b from-black/30 via-transparent to-black/40 pointer-events-none" />
      </div>

      {/* Biały overlay przy przejściu - zoom + znikanie w biel */}
      {zoomingToSpot && (
        <motion.div
          className="absolute inset-0 z-20 bg-white pointer-events-none"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 2, ease: [0.55, 0, 1, 1] }}
        />
      )}

      {/* Hotspots - hidden on mobile, ukryte podczas zoomu */}
      {!isZooming && (
        <div className="absolute inset-0 z-30 hidden md:block">
          {/* Overlay: mapowanie współrzędnych na hotspoty - pod etykietami, przechwytuje kliknięcia */}
          <div
            className="absolute inset-0 z-0 cursor-pointer"
            onClick={handleOverlayClick}
            onMouseMove={handleOverlayMouseMove}
            onMouseLeave={() => setActiveHotspot(null)}
            aria-hidden
          />
          {hotspots.map((spot) => (
            <Hotspot
              key={spot.id}
              hotspot={spot}
              isActive={activeHotspot === spot.id}
            />
          ))}
        </div>
      )}

      {/* Flip card z pytajnikiem - prawy dolny róg, ukryty podczas zoomu */}
      {!isZooming && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.5, duration: 0.8 }}
          className="absolute bottom-8 right-4 md:bottom-10 md:right-6 z-50 [perspective:1000px]"
        >
          {/* Wrapper o stałym rozmiarze – stabilny obszar hover, zapobiega podwójnemu obrotowi */}
          <div
            className="relative w-[200px] h-[88px] md:w-[240px] md:h-[100px] cursor-pointer"
            onMouseEnter={() => setFlipped(true)}
            onMouseLeave={() => setFlipped(false)}
            onClick={() => setFlipped((f) => !f)}
          >
            <motion.div
              className="absolute inset-0"
              style={{ transformStyle: 'preserve-3d' }}
              animate={{ rotateY: flipped ? 180 : 0 }}
              transition={{ duration: 0.5, ease: [0.4, 0, 0.2, 1] }}
            >
              {/* Przód - animowany znak zapytania */}
              <div
                className="absolute inset-0 rounded-xl bg-white/20 backdrop-blur-md border border-white/30 flex items-center justify-center"
                style={{ backfaceVisibility: 'hidden' }}
              >
                <motion.span
                  className="text-2xl md:text-3xl font-bold text-white select-none"
                  animate={{
                    scale: [1, 1.2, 1],
                    opacity: [0.85, 1, 0.85],
                  }}
                  transition={{
                    duration: 2.5,
                    repeat: Infinity,
                    ease: 'easeInOut',
                  }}
                >
                  ?
                </motion.span>
              </div>
              {/* Tył - informacja */}
              <div
                className="absolute inset-0 rounded-xl bg-black/60 backdrop-blur-md border border-white/20 p-4 flex flex-col items-center justify-center text-center"
                style={{ backfaceVisibility: 'hidden', transform: 'rotateY(180deg)' }}
              >
                <span className="text-base md:text-lg font-bold text-white leading-tight">
                  Twoja Łódka
                </span>
                <span className="text-sm text-white/90 mt-1.5 leading-snug">
                  Kliknij na części łodzi aby odkryć ofertę
                </span>
              </div>
            </motion.div>
          </div>
        </motion.div>
      )}

      {/* Mobile CTA Buttons */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.7, duration: 0.8 }}
        className="md:hidden absolute bottom-10 left-0 right-0 px-6 z-20"
      >
        <div className="grid grid-cols-2 gap-4">
          {hotspots.slice(0, 4).map((spot) => (
            <a
              key={spot.id}
              href={spot.href}
              className="bg-white/95 backdrop-blur-sm rounded-lg px-4 py-3 text-center font-semibold text-blue-950 hover:bg-white transition-colors"
            >
              {spot.label}
            </a>
          ))}
        </div>
      </motion.div>
    </section>
  )
}
