import { useCallback, useEffect, useState } from "react"; import { fetchMapColorThresholds, updateMapColorThresholds } from "../api/config"; import { handleFetchError, createStringErrorAdapter } from "../utils/fetchError"; import type { MapColorThresholdsResponse, MapColorThresholdsUpdate, } from "../types/config"; export interface UseMapColorThresholdsResult { thresholds: MapColorThresholdsResponse | null; loading: boolean; error: string | null; refresh: () => Promise; updateThresholds: (payload: MapColorThresholdsUpdate) => Promise; } export function useMapColorThresholds(): UseMapColorThresholdsResult { const [thresholds, setThresholds] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const load = useCallback(async (signal?: AbortSignal): Promise => { setLoading(true); setError(null); try { const data = await fetchMapColorThresholds(signal); if (signal?.aborted) return; setThresholds(data); } catch (err: unknown) { if (signal?.aborted) return; handleFetchError(err, createStringErrorAdapter(setError), "Failed to fetch map color thresholds"); } finally { if (!signal?.aborted) { setLoading(false); } } }, []); useEffect(() => { const controller = new AbortController(); void load(controller.signal); return (): void => { controller.abort(); }; }, [load]); const updateThresholds = useCallback( async (payload: MapColorThresholdsUpdate): Promise => { const updated = await updateMapColorThresholds(payload); setThresholds(updated); return updated; }, [], ); return { thresholds, loading, error, refresh: load, updateThresholds, }; }