import { useState, useEffect } from 'react';

export function useData<T>(path: string, fallback: T): { data: T; loading: boolean; error: boolean } {
  const [data, setData] = useState<T>(fallback);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    fetch(path)
      .then(r => {
        if (!r.ok) throw new Error(r.statusText);
        return r.text();
      })
      .then(text => {
        // Handle NaN values in JSON (Python sometimes outputs these)
        const cleaned = text.replace(/:\s*NaN/g, ': null');
        setData(JSON.parse(cleaned));
        setLoading(false);
      })
      .catch(() => {
        setError(true);
        setLoading(false);
      });
  }, [path]);

  return { data, loading, error };
}
