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

/**
 * Minimal SWR-style hook: call `fn`, expose `{ data, error, loading, refetch }`.
 * No global cache — each consumer fetches its own copy. Add caching when you
 * see the same query firing 5+ times across mounted components.
 */
export interface UseFetchResult<T> {
  data: T | null;
  error: Error | null;
  loading: boolean;
  refetch: () => void;
}

export function useFetch<T>(fn: () => Promise<T>, deps: unknown[] = []): UseFetchResult<T> {
  const [data, setData] = useState<T | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const [loading, setLoading] = useState(true);
  const [bump, setBump] = useState(0);

  const refetch = useCallback(() => setBump((b) => b + 1), []);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    fn()
      .then((d) => { if (!cancelled) { setData(d); setLoading(false); } })
      .catch((e: Error) => { if (!cancelled) { setError(e); setLoading(false); } });
    return () => { cancelled = true; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bump, ...deps]);

  return { data, error, loading, refetch };
}
