// Shared data-fetching hook for the SEIS+ Internals dashboard.

function useApi(url, pollMs = 30000) {
  const [data, setData]       = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError]     = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;

    const load = () =>
      fetch(url, { credentials: "include" })
        .then(r => {
          if (!r.ok) throw new Error(`${r.status}`);
          return r.json();
        })
        .then(d => { if (!cancelled) { setData(d); setLoading(false); setError(null); } })
        .catch(e => { if (!cancelled) { setError(e.message); setLoading(false); } });

    load();
    const id = setInterval(load, pollMs);
    return () => { cancelled = true; clearInterval(id); };
  }, [url, pollMs]);

  return [data, loading, error];
}

window.SEIS_API = { useApi };
