// Custom hook: useDashboardData
// Encapsulates all dashboard data fetching + state management.
// Loaded as a <script type="text/babel"> before panel.jsx.
// Depends on: React (useState, useEffect, useCallback), get() from api.js

function useDashboardData() {
  const [tab, setTab] = useState("overview");
  const [health, setHealth] = useState(null);
  const [budget, setBudget] = useState(null);
  const [models, setModels] = useState([]);
  const [accounts, setAccounts] = useState([]);
  const [vms, setVMs] = useState([]);
  const [costs, setCosts] = useState(null);
  const [context, setContext] = useState(null);
  const [connected, setConnected] = useState(false);
  const [lastRefresh, setLastRefresh] = useState(null);

  const refresh = useCallback(async () => {
    const h = await get("/health");
    setConnected(!!h);
    setHealth(h);
    if (h) {
      const [b, m, a, v, c, ctx] = await Promise.all([
        get("/v1/budget"),
        get("/v1/models"),
        get("/dashboard/accounts"),
        get("/dashboard/vms"),
        get("/dashboard/costs"),
        get("/v1/context/stats"),
      ]);
      setBudget(b);
      setModels(m?.data || []);
      setAccounts(a?.accounts || []);
      setVMs(v?.vms || []);
      setCosts(c);
      setContext(ctx);
    }
    setLastRefresh(new Date());
  }, []);

  useEffect(() => {
    refresh();
    const i = setInterval(refresh, 15000);
    return () => clearInterval(i);
  }, [refresh]);

  return {
    tab, setTab,
    health, budget, models, accounts, vms, costs, context,
    connected, lastRefresh, refresh,
  };
}
