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

// Loads the logged-in player's fate points and spends them (persisted to the
// sheet via the backend). `fate` is { current, total } or null while unknown.
export function useFate(authedPlayer) {
  const [fate, setFate] = useState(null)

  const loadFate = useCallback(async () => {
    if (!authedPlayer) { setFate(null); return }
    try {
      const res = await fetch(`/api/players/${authedPlayer}`, { cache: 'no-store' })
      if (!res.ok) return
      const player = await res.json()
      const raw = player?.tabInfo?.fate
      if (raw && typeof raw === 'object') setFate({ current: Number(raw.current) || 0, total: Number(raw.total) || 0 })
      else if (raw != null) setFate({ current: Number(raw) || 0, total: Number(raw) || 0 })
      else setFate({ current: 0, total: 0 })
    } catch {
      // Leave fate as-is; the roller still works without it.
    }
  }, [authedPlayer])

  useEffect(() => { loadFate() }, [loadFate])

  // Returns true if a point was spent. Updates local state from the server.
  const spendFate = useCallback(async () => {
    if (!authedPlayer) return false
    if (fate && fate.current <= 0) return false
    try {
      const res = await fetch(`/api/players/${authedPlayer}/spend-fate`, { method: 'POST' })
      if (!res.ok) return false
      const data = await res.json()
      if (data?.fate) setFate({ current: Number(data.fate.current) || 0, total: Number(data.fate.total) || 0 })
      return true
    } catch {
      return false
    }
  }, [authedPlayer, fate])

  return { fate, spendFate, refreshFate: loadFate }
}
