'use client'

import { useCallback, useEffect, useState } from 'react'

type RandomPrayerProps = {
  prayers: string[]
}

const pickRandom = (prayers: string[]) =>
  prayers[Math.floor(Math.random() * prayers.length)] || ''

export const RandomPrayer = ({ prayers }: RandomPrayerProps) => {
  const [prayer, setPrayer] = useState('')

  const newPrayer = useCallback(() => {
    setPrayer(pickRandom(prayers))
  }, [prayers])

  useEffect(() => {
    setPrayer(pickRandom(prayers))
    const interval = setInterval(() => {
      setPrayer(pickRandom(prayers))
    }, 60 * 1000)
    return () => clearInterval(interval)
  }, [prayers])

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