import { useEffect, useState } from 'react'
import styles from './ArcadeDiscoReflect.module.css'

const PARALLAX_X = 22
const PARALLAX_Y = 16

function usePrefersReducedMotion(): boolean {
  const [reduced, setReduced] = useState(
    () => typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches,
  )

  useEffect(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)')
    const onChange = () => setReduced(mq.matches)
    mq.addEventListener('change', onChange)
    return () => mq.removeEventListener('change', onChange)
  }, [])

  return reduced
}

/** Disco-ball light reflections + mouse parallax — shared by leaderboard & song select */
export function ArcadeDiscoReflect() {
  const reducedMotion = usePrefersReducedMotion()
  const [shift, setShift] = useState({ x: 0, y: 0 })

  useEffect(() => {
    if (reducedMotion) return

    function onMove(e: MouseEvent) {
      const nx = (e.clientX / window.innerWidth) * 2 - 1
      const ny = (e.clientY / window.innerHeight) * 2 - 1
      setShift({ x: nx * PARALLAX_X, y: ny * PARALLAX_Y })
    }

    window.addEventListener('mousemove', onMove, { passive: true })
    return () => window.removeEventListener('mousemove', onMove)
  }, [reducedMotion])

  return (
    <div className={styles.wrap} aria-hidden="true">
      <div
        className={styles.parallaxGroup}
        style={
          reducedMotion ? undefined : { transform: `translate(${shift.x}px, ${shift.y}px)` }
        }
      >
        <div className={styles.beamSweep} />
        <div className={`${styles.blob} ${styles.blob1}`} />
        <div className={`${styles.blob} ${styles.blob2}`} />
        <div className={`${styles.blob} ${styles.blob3}`} />
        <div className={`${styles.blob} ${styles.blob4}`} />
        <div className={styles.shimmer} />
      </div>
    </div>
  )
}
