import { useState, useEffect, useCallback } from "react"; import type { DashboardData, JobUpdate, DashboardMetrics } from "../types/index.ts"; interface UseDashboardDataResult { data: DashboardData | null; loading: boolean; error: string | null; refetch: () => void; } const API_BASE = "/api"; async function fetchJson(url: string): Promise { const token = localStorage.getItem("access_token"); const headers: Record = { "Content-Type": "application/json", }; if (token) { headers["Authorization"] = `Bearer ${token}`; } const response = await fetch(url, { headers }); if (!response.ok) { const body = await response.json().catch(() => ({})); throw new Error( (body as { error?: string }).error || `HTTP ${response.status}: ${response.statusText}` ); } return response.json() as Promise; } export function useDashboardData(): UseDashboardDataResult { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const fetchData = useCallback(async () => { setLoading(true); setError(null); try { const [updates, metrics] = await Promise.all([ fetchJson(`${API_BASE}/updates/latest/`), fetchJson(`${API_BASE}/updates/metrics/`), ]); setData({ updates, metrics }); } catch (err: unknown) { const message = err instanceof Error ? err.message : "An unknown error occurred"; setError(message); } finally { setLoading(false); } }, []); useEffect(() => { fetchData(); }, [fetchData]); return { data, loading, error, refetch: fetchData }; }