import { useCallback, useEffect, useState } from 'react'
import { getEvents } from '../utils/api'

export function useEvents(autoLoad = true) {
  const [events, setEvents] = useState([])
  const [loading, setLoading] = useState(autoLoad)
  const [error, setError] = useState(null)

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await getEvents()
      setEvents(Array.isArray(data) ? data : [])
    } catch (err) {
      console.error('Failed to load events', err)
      setError(err)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    if (autoLoad) {
      load()
    }
  }, [autoLoad, load])

  return { events, loading, error, reload: load, setEvents }
}
