import { useEffect, useRef } from 'react'

interface UseInactivityTimeoutOptions {
  timeoutMs: number
  onTimeout: () => void
  isEnabled?: boolean
}

const ACTIVITY_EVENTS: Array<keyof WindowEventMap> = [
  'mousemove',
  'mousedown',
  'keydown',
  'scroll',
  'touchstart',
  'focus',
]

export function useInactivityTimeout({
  timeoutMs,
  onTimeout,
  isEnabled = true,
}: UseInactivityTimeoutOptions) {
  const timeoutRef = useRef<number | null>(null)
  const callbackRef = useRef(onTimeout)

  useEffect(() => {
    callbackRef.current = onTimeout
  }, [onTimeout])

  useEffect(() => {
    if (!isEnabled) {
      if (timeoutRef.current) {
        window.clearTimeout(timeoutRef.current)
        timeoutRef.current = null
      }
      return
    }

    const resetTimer = () => {
      if (timeoutRef.current) {
        window.clearTimeout(timeoutRef.current)
      }
      timeoutRef.current = window.setTimeout(() => {
        callbackRef.current()
      }, timeoutMs)
    }

    const handleVisibilityChange = () => {
      if (!document.hidden) {
        resetTimer()
      }
    }

    resetTimer()
    ACTIVITY_EVENTS.forEach((event) => window.addEventListener(event, resetTimer))
    document.addEventListener('visibilitychange', handleVisibilityChange)

    return () => {
      if (timeoutRef.current) {
        window.clearTimeout(timeoutRef.current)
      }
      ACTIVITY_EVENTS.forEach((event) => window.removeEventListener(event, resetTimer))
      document.removeEventListener('visibilitychange', handleVisibilityChange)
    }
  }, [timeoutMs, isEnabled])
}


