"use client"; import { t } from "./i18n"; import { useCallback, useEffect, useState, useSyncExternalStore } from "react"; import { fetchHealth, type Health } from "./client-api"; import { settingsStore } from "./settings"; /** * Health status for the current browser (re-checks whenever the API key * changes). Used by the settings dialog and the API-key gate. */ export function useHealth() { const apiKey = useSyncExternalStore( settingsStore.subscribe, () => settingsStore.getSnapshot().apiKey, () => "", ); const [health, setHealth] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [checkedAt, setCheckedAt] = useState(null); const refresh = useCallback(async () => { setLoading(true); setError(null); try { setHealth(await fetchHealth()); } catch (loadError) { setError(loadError instanceof Error ? loadError.message : t("api.unreachableShort")); } finally { // Even a failed check is a check: the panel can say when it last ran. setCheckedAt(Date.now()); setLoading(false); } }, []); useEffect(() => { void refresh(); }, [refresh, apiKey]); return { health, loading, error, refresh, apiKey, checkedAt }; }