import { useEffect, useState } from 'react'
import { cooldownNow, hasActiveCooldowns } from '../combat/spellCasting'

export function useCooldownClock(
  cooldowns: Record<string, number>,
  active: boolean,
  intervalMs = 100,
) {
  const [now, setNow] = useState(cooldownNow)

  useEffect(() => {
    if (!active || !hasActiveCooldowns(cooldowns)) return undefined

    let timer = 0
    let startTimer = 0
    const tick = () => {
      const nextNow = cooldownNow()
      setNow(nextNow)
      if (timer && !hasActiveCooldowns(cooldowns, nextNow)) {
        window.clearInterval(timer)
        timer = 0
      }
    }

    startTimer = window.setTimeout(() => {
      tick()
      timer = window.setInterval(tick, intervalMs)
    }, 0)
    return () => {
      window.clearTimeout(startTimer)
      if (timer) window.clearInterval(timer)
    }
  }, [active, cooldowns, intervalMs])

  return now
}
