'use client'
import { useEffect, useRef } from 'react'
import styles from './CustomCursor.module.css'

export default function CustomCursor() {
  const dotRef  = useRef<HTMLDivElement>(null)
  const ringRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    let ringX = 0, ringY = 0
    let animId: number

    function onMove(e: MouseEvent) {
      const { clientX: x, clientY: y } = e

      if (dotRef.current) {
        dotRef.current.style.transform = `translate(${x}px, ${y}px)`
      }

      // Ring follows with smooth lag
      function animate() {
        ringX += (x - ringX) * 0.12
        ringY += (y - ringY) * 0.12
        if (ringRef.current) {
          ringRef.current.style.transform = `translate(${ringX}px, ${ringY}px)`
        }
        animId = requestAnimationFrame(animate)
      }
      cancelAnimationFrame(animId)
      animId = requestAnimationFrame(animate)
    }

    function onDown() {
      dotRef.current?.classList.add(styles.pressed)
      ringRef.current?.classList.add(styles.pressed)
    }

    function onUp() {
      dotRef.current?.classList.remove(styles.pressed)
      ringRef.current?.classList.remove(styles.pressed)
    }

    function onEnterLink() {
      dotRef.current?.classList.add(styles.hover)
      ringRef.current?.classList.add(styles.hover)
    }

    function onLeaveLink() {
      dotRef.current?.classList.remove(styles.hover)
      ringRef.current?.classList.remove(styles.hover)
    }

    document.addEventListener('mousemove', onMove)
    document.addEventListener('mousedown', onDown)
    document.addEventListener('mouseup', onUp)

    // Hover effect on interactive elements
    function attachHover() {
      document.querySelectorAll('a, button, [role="button"], input, select, textarea, label').forEach(el => {
        el.addEventListener('mouseenter', onEnterLink)
        el.addEventListener('mouseleave', onLeaveLink)
      })
    }
    attachHover()

    // Re-attach on DOM mutations (dynamic content)
    const obs = new MutationObserver(attachHover)
    obs.observe(document.body, { childList: true, subtree: true })

    return () => {
      document.removeEventListener('mousemove', onMove)
      document.removeEventListener('mousedown', onDown)
      document.removeEventListener('mouseup', onUp)
      cancelAnimationFrame(animId)
      obs.disconnect()
    }
  }, [])

  // Only show on desktop (no touch)
  if (typeof window !== 'undefined' && window.matchMedia('(hover: none)').matches) return null

  return (
    <>
      <div ref={dotRef}  className={styles.dot}  aria-hidden="true" />
      <div ref={ringRef} className={styles.ring} aria-hidden="true" />
    </>
  )
}
