import { defineStore } from 'pinia'
import { ref } from 'vue'

const INACTIVITY_MS = 3 * 60 * 1000 // 3 minutes

export const useScreensaverStore = defineStore('screensaver', () => {
  const isActive = ref(false)
  let inactivityTimer: ReturnType<typeof setTimeout> | null = null

  function activate() {
    isActive.value = true
    clearInactivityTimer()
  }

  function deactivate() {
    isActive.value = false
    resetInactivityTimer()
  }

  function resetInactivityTimer() {
    clearInactivityTimer()
    inactivityTimer = setTimeout(() => {
      inactivityTimer = null
      isActive.value = true
    }, INACTIVITY_MS)
  }

  function clearInactivityTimer() {
    if (inactivityTimer) {
      clearTimeout(inactivityTimer)
      inactivityTimer = null
    }
  }

  return {
    isActive,
    activate,
    deactivate,
    resetInactivityTimer,
    clearInactivityTimer,
  }
})
