export interface UseIdleDetectionOptions {
  timeout?: number
  onIdle?: () => void
}

export function useIdleDetection(options: UseIdleDetectionOptions = {}) {
  const { timeout = 30000, onIdle } = options

  const isIdle = ref(false)
  let timeoutId: ReturnType<typeof setTimeout> | null = null

  function resetTimer() {
    isIdle.value = false
    if (timeoutId) {
      clearTimeout(timeoutId)
    }
    timeoutId = setTimeout(() => {
      isIdle.value = true
      onIdle?.()
    }, timeout)
  }

  const events = ['mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart']

  if (import.meta.client) {
    onMounted(() => {
      events.forEach((event) => {
        window.addEventListener(event, resetTimer, { passive: true })
      })
      resetTimer()
    })

    onUnmounted(() => {
      events.forEach((event) => {
        window.removeEventListener(event, resetTimer)
      })
      if (timeoutId) {
        clearTimeout(timeoutId)
      }
    })
  }

  return { isIdle: readonly(isIdle) }
}
