// Custom hooks: specialized data fetchers + useDashboardData aggregator.
// Loaded as a <script type="text/babel"> before panel.jsx.
// Depends on: React (useState, useCallback), get() from api.js

function useHealth() {
  const [health, setHealth] = useState(null);
  const [connected, setConnected] = useState(false);
  const refresh = useCallback(async () => {
    const h = await get("/health");
    setConnected(!!h);
    setHealth(h);
    return !!h;
  }, []);
  return { health, connected, refresh };
}

function useBudget() {
  const [budget, setBudget] = useState(null);
  const [costs, setCosts] = useState(null);
  const refresh = useCallback(async () => {
    const [b, c] = await Promise.all([get("/v1/budget"), get("/dashboard/costs")]);
    setBudget(b);
    setCosts(c);
  }, []);
  return { budget, costs, refresh };
}

function useModels() {
  const [models, setModels] = useState([]);
  const refresh = useCallback(async () => {
    const m = await get("/v1/models");
    setModels(m?.data || []);
  }, []);
  return { models, refresh };
}

function useProviders() {
  const [providers, setProviders] = useState([]);
  const refresh = useCallback(async () => {
    const p = await get("/dashboard/providers");
    setProviders(p?.providers || []);
  }, []);
  return { providers, refresh };
}

function useResources() {
  const [accounts, setAccounts] = useState([]);
  const [vms, setVMs] = useState([]);
  const [context, setContext] = useState(null);
  const refresh = useCallback(async () => {
    const [a, v, ctx] = await Promise.all([
      get("/dashboard/accounts"),
      get("/dashboard/vms"),
      get("/v1/context/stats"),
    ]);
    setAccounts(a?.accounts || []);
    setVMs(v?.vms || []);
    setContext(ctx);
  }, []);
  return { accounts, vms, context, refresh };
}

function useLogs() {
  const [logs, setLogs] = useState([]);
  const [logsError, setLogsError] = useState(null);
  const [logsSource, setLogsSource] = useState(null);
  const refresh = useCallback(async () => {
    try {
      const l = await get("/dashboard/logs?lines=50");
      setLogs(l?.logs || []);
      setLogsError(l?.error || null);
      setLogsSource(l?.source || null);
    } catch (e) {
      setLogsError(e.message);
      setLogs([]);
    }
  }, []);
  return { logs, logsError, logsSource, refresh };
}

function useDashboardData() {
  // Read initial tab from URL hash
  const getInitialTab = () => {
    const hash = window.location.hash.replace("#", "");
    const validTabs = ["overview", "accounts", "models", "vms"];
    return validTabs.includes(hash) ? hash : "overview";
  };

  const [tab, setTabState] = useState(getInitialTab);
  const [lastRefresh, setLastRefresh] = useState(null);

  // Sync tab changes to URL
  const setTab = useCallback((newTab) => {
    setTabState(newTab);
    window.location.hash = newTab;
  }, []);

  // Listen to browser back/forward
  useEffect(() => {
    const handleHashChange = () => {
      const newTab = window.location.hash.replace("#", "") || "overview";
      const validTabs = ["overview", "accounts", "models", "vms"];
      if (validTabs.includes(newTab)) {
        setTabState(newTab);
      }
    };
    window.addEventListener("hashchange", handleHashChange);
    return () => window.removeEventListener("hashchange", handleHashChange);
  }, []);

  const healthHook = useHealth();
  const budgetHook = useBudget();
  const modelsHook = useModels();
  const providersHook = useProviders();
  const resourcesHook = useResources();
  const logsHook = useLogs();

  const refresh = useCallback(async () => {
    const isUp = await healthHook.refresh();
    if (isUp) {
      await Promise.all([budgetHook.refresh(), modelsHook.refresh(), providersHook.refresh(), resourcesHook.refresh(), logsHook.refresh()]);
    }
    setLastRefresh(new Date());
  }, [healthHook.refresh, budgetHook.refresh, modelsHook.refresh, providersHook.refresh, resourcesHook.refresh, logsHook.refresh]);

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

  return {
    tab, setTab,
    health: healthHook.health,
    connected: healthHook.connected,
    budget: budgetHook.budget,
    costs: budgetHook.costs,
    models: modelsHook.models,
    providers: providersHook.providers,
    accounts: resourcesHook.accounts,
    vms: resourcesHook.vms,
    context: resourcesHook.context,
    logs: logsHook.logs,
    logsError: logsHook.logsError,
    logsSource: logsHook.logsSource,
    lastRefresh, refresh,
  };
}
