"use client"

import { randomPrayer } from '@/utils/randomPrayer'
import { useCallback, useEffect, useState } from 'react'

export const RandomPrayer = () => {
  const [intervalId, setIntervalId] = useState<NodeJS.Timeout | undefined>(undefined)
  const [prayer, setPrayer] = useState("")

  // Set interval to change the prayer
  const newPrayerEveryInterval = useCallback(() => {
    const i = setInterval(() => {
      setPrayer(randomPrayer())
    }, 60 * 1000)

    setIntervalId(i)
  }, [setPrayer, setIntervalId])

  // Set new random prayer and reset timer interval
  const newPrayer = useCallback(() => {
    clearInterval(intervalId)
    setPrayer(randomPrayer())
    newPrayerEveryInterval()
  }, [intervalId, setPrayer, newPrayerEveryInterval])

  // Every 30 seconds set a new prayer
  useEffect(() => {
    setPrayer(randomPrayer())
    newPrayerEveryInterval()
    return () => clearInterval(intervalId)
  }, [newPrayerEveryInterval])

  return (
    <p onClick={newPrayer} style={{cursor: "pointer"}}>
      {prayer}
    </p>
  )
}