import { useMemo } from 'react'
import type { Spell } from '../game'
import type { SpellSlot } from '../components/SpellBars'
import { cooldownRemaining } from '../combat/spellCasting'
import { useCooldownClock } from './useCooldownClock'

type UseSpellSlotsOptions = {
  spells: readonly Spell[]
  cooldowns: Record<string, number>
  active: boolean
  cost: (spell: Spell) => number
  abilitySlots?: readonly (number | null)[]
}

export function useSpellSlots({
  spells,
  cooldowns,
  active,
  cost,
  abilitySlots,
}: UseSpellSlotsOptions) {
  const now = useCooldownClock(cooldowns, active)

  return useMemo<SpellSlot[]>(() => {
    const slotCount = abilitySlots?.length ?? spells.length
    return Array.from({ length: slotCount }, (_, slotIndex) => {
      if (abilitySlots && !abilitySlots[slotIndex]) return null
      const spell = spells[slotIndex]
      if (!spell) return null
      return {
        ...spell,
        cost: cost(spell),
        slotIndex,
        remaining: cooldownRemaining(cooldowns, spell.id, now),
      }
    })
  }, [abilitySlots, cooldowns, cost, now, spells])
}
