'use client'

import { useEffect, useState } from 'react'
import { motion, useMotionValue, useSpring } from 'framer-motion'

export function CustomCursor() {
  const cursorX = useMotionValue(-100)
  const cursorY = useMotionValue(-100)

  const springConfig = { stiffness: 500, damping: 40, mass: 0.5 }
  const ringConfig = { stiffness: 120, damping: 18, mass: 0.8 }

  const dotX = useSpring(cursorX, springConfig)
  const dotY = useSpring(cursorY, springConfig)
  const ringX = useSpring(cursorX, ringConfig)
  const ringY = useSpring(cursorY, ringConfig)

  const [isHovering, setIsHovering] = useState(false)
  const [isOnCanvas] = useState(false)

  useEffect(() => {
    const move = (e: MouseEvent) => {
      cursorX.set(e.clientX)
      cursorY.set(e.clientY)
    }

    const handleEnterInteractive = () => setIsHovering(true)
    const handleLeaveInteractive = () => setIsHovering(false)

    const bindInteractives = () => {
      document.querySelectorAll('a, button, [data-cursor]').forEach(el => {
        el.addEventListener('mouseenter', handleEnterInteractive)
        el.addEventListener('mouseleave', handleLeaveInteractive)
      })
    }

    window.addEventListener('mousemove', move, { passive: true })
    bindInteractives()

    const observer = new MutationObserver(bindInteractives)
    observer.observe(document.body, { childList: true, subtree: true })

    return () => {
      window.removeEventListener('mousemove', move)
      observer.disconnect()
    }
  }, [cursorX, cursorY])

  return (
    <>
      {/* Dot */}
      <motion.div
        className="fixed pointer-events-none z-[99999] mix-blend-difference"
        style={{ x: dotX, y: dotY, translateX: '-50%', translateY: '-50%' }}
      >
        <motion.div
          className="rounded-full bg-white-soft"
          animate={{
            width: isOnCanvas ? 28 : isHovering ? 6 : 8,
            height: isOnCanvas ? 28 : isHovering ? 6 : 8,
          }}
          transition={{ type: 'spring', stiffness: 400, damping: 30 }}
        />
      </motion.div>

      {/* Ring */}
      <motion.div
        className="fixed pointer-events-none z-[99998]"
        style={{ x: ringX, y: ringY, translateX: '-50%', translateY: '-50%' }}
      >
        <motion.div
          className="rounded-full border border-white-soft/60"
          animate={{
            width: isHovering ? 48 : isOnCanvas ? 0 : 32,
            height: isHovering ? 48 : isOnCanvas ? 0 : 32,
            borderColor: isHovering ? '#0044FF' : 'rgba(240,240,255,0.6)',
            opacity: isOnCanvas ? 0 : 1,
          }}
          transition={{ type: 'spring', stiffness: 200, damping: 20 }}
        />
      </motion.div>
    </>
  )
}
