import { useCallback, useEffect, useState } from 'react'
import { fetchCompetitions, type CompetitionResponse } from './competitionApi'

export function useCompetitions(token: string) {
  const [competitions, setCompetitions] = useState<CompetitionResponse[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [version, setVersion] = useState(0)

  useEffect(() => {
    let isActive = true

    async function load() {
      try {
        const data = await fetchCompetitions(token)
        if (isActive) setCompetitions(data)
      } catch (err) {
        if (isActive) setError(err instanceof Error ? err.message : 'Failed to load competitions')
      } finally {
        if (isActive) setLoading(false)
      }
    }

    void load()

    return () => { isActive = false }
  }, [token, version])

  const refetch = useCallback(() => setVersion((v) => v + 1), [])

  return { competitions, loading, error, refetch }
}
