import * as React from 'react'

import {motion, HTMLMotionProps} from 'motion/react'

interface LongPressDetectorProps extends HTMLMotionProps<'div'> {
  onLongPress: () => void
  delay?: number
  children: React.ReactNode
}

export const LongPressDetector = ({
  onLongPress,
  delay = 500,
  children,
  ...motionProps
}: LongPressDetectorProps) => {
  const longPressTimeoutRef = React.useRef<number | undefined>(undefined)

  const handleTapStart = React.useCallback(() => {
    longPressTimeoutRef.current = window.setTimeout(() => {
      onLongPress()
      longPressTimeoutRef.current = undefined
    }, delay)
  }, [onLongPress, delay])

  const handleTapEnd = React.useCallback(() => {
    if (longPressTimeoutRef.current) {
      clearTimeout(longPressTimeoutRef.current)
      longPressTimeoutRef.current = undefined
    }
  }, [])

  // Cleanup timer on unmount
  React.useEffect(() => {
    return () => {
      if (longPressTimeoutRef.current) {
        clearTimeout(longPressTimeoutRef.current)
      }
    }
  }, [])

  return (
    <motion.div
      onTapStart={handleTapStart}
      onTap={handleTapEnd}
      onTapCancel={handleTapEnd}
      {...motionProps}
    >
      {children}
    </motion.div>
  )
}
