'use client'

import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { motion, AnimatePresence } from 'framer-motion'
import type { HotspotArea } from '@/lib/types'

interface HotspotProps {
  hotspot: HotspotArea
  isActive: boolean
}

export default function Hotspot({ hotspot, isActive }: HotspotProps) {
  const { position, label, description } = hotspot
  const [tooltipRect, setTooltipRect] = useState<DOMRect | null>(null)

  // Etykieta renderowana przez portal nad Headerem (z-50) – wymaga pomiaru pozycji
  useEffect(() => {
    if (!isActive) {
      setTooltipRect(null)
      return
    }
    if (typeof document === 'undefined') return
    const measure = () => {
      const hero = document.querySelector('main section')
      if (!hero) return
      const el = hero
      const rect = el.getBoundingClientRect()
      const centerX = rect.left + (rect.width * (position.x + position.width / 2)) / 100
      const centerY = rect.top + (rect.height * (position.y + position.height / 2)) / 100
      setTooltipRect(new DOMRect(centerX, centerY, 0, 0))
    }
    // Krótkie opóźnienie – hero może nie być jeszcze zmierzony
    const id = requestAnimationFrame(() => {
      measure()
    })
    window.addEventListener('resize', measure)
    return () => {
      cancelAnimationFrame(id)
      window.removeEventListener('resize', measure)
    }
  }, [isActive, position])

  const tooltipOnLeft = position.x > 55

  return (
    <>
      <div
        aria-label={label}
        className="absolute overflow-visible block pointer-events-none"
        style={{
          left: `${position.x}%`,
          top: `${position.y}%`,
          width: `${position.width}%`,
          height: `${position.height}%`,
        }}
      >
        {/* Wspólny kontener - kropka i fale w tym samym miejscu */}
        <div className="absolute top-1/2 left-1/2 w-4 h-4 -translate-x-1/2 -translate-y-1/2">
          {/* Efekt plusku - fale rozchodzą się z centrum kropki */}
          {isActive &&
            [0, 1, 2].map((i) => (
              <div
                key={i}
                className="absolute inset-0 rounded-full border-2 border-white shadow-[0_0_10px_rgba(255,255,255,0.8)] pointer-events-none animate-ripple"
                style={{ animationDelay: `${i * 120}ms` }}
              />
            ))}

          {/* Białe kropki */}
          <motion.div
            className="absolute inset-0 rounded-full bg-white shadow-lg z-20 pointer-events-none"
            animate={{ scale: isActive ? 1.4 : 1 }}
            transition={{ type: 'spring', stiffness: 400, damping: 20 }}
          />
        </div>
      </div>

      {/* Etykieta w portalu – nad Headerem (z-[100]), bez overflow-hidden */}
      {typeof document !== 'undefined' &&
        createPortal(
          <AnimatePresence>
            {isActive && tooltipRect && (
              <motion.div
                key={hotspot.id}
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.9 }}
                transition={{ duration: 0.2 }}
                className="fixed z-[100] min-w-[200px] max-w-[280px] pointer-events-none"
                style={{
                  left: tooltipOnLeft ? tooltipRect.x - 16 : tooltipRect.x + 16,
                  top: tooltipRect.y,
                  transform: tooltipOnLeft ? 'translate(-100%, -50%)' : 'translateY(-50%)',
                }}
              >
                <div className="bg-white/95 backdrop-blur-md rounded-2xl shadow-2xl px-6 py-4">
                  <h3 className="text-xl font-bold text-blue-950 mb-2">{label}</h3>
                  <p className="text-gray-700 text-sm">{description}</p>
                </div>
              </motion.div>
            )}
          </AnimatePresence>,
          document.body
        )}
    </>
  )
}
