import { useEffect, useRef, useState } from "react"; import type { SightingType, SightingWidgetType } from "../types/types"; async function fetchSighting( url: string, ref: number ): Promise { const res = await fetch(`${url}${ref}`); if (!res.ok) throw new Error(String(res.status)); return await res.json(); } export function useSightingFeed(url: string) { const [sightings, setSightings] = useState([]); const [selectedRef, setSelectedRef] = useState(null); const [mostRecent, setMostRecent] = useState(null); const [selectedSighting, setSelectedSighting] = useState( null ); const currentRef = useRef(-1); const pollingTimeout = useRef | null>(null); const lastValidTimestamp = useRef(Date.now()); useEffect(() => { const poll = async () => { try { const data = await fetchSighting(url, currentRef.current); const now = Date.now(); if (data.ref === -1) { if (now - lastValidTimestamp.current > 60000) { console.warn("No valid sighting in over a minute. Restarting..."); currentRef.current = -1; lastValidTimestamp.current = now; } pollingTimeout.current = setTimeout(poll, 400); } else { currentRef.current = data.ref; lastValidTimestamp.current = now; setSightings((prev) => { const updated = [data, ...prev].slice(0, 7); return updated; }); setMostRecent(data); setSelectedRef(data.ref); pollingTimeout.current = setTimeout(poll, 100); } } catch (err) { console.error("Polling error:", err); pollingTimeout.current = setTimeout(poll, 100); } }; poll(); return () => { if (pollingTimeout.current) clearTimeout(pollingTimeout.current); }; }, [url]); // const selected = sightings.find(s => s?.ref === selectedRef) ?? mostRecent; return { sightings, selectedRef, setSelectedRef, mostRecent, setSelectedSighting, selectedSighting, // effectiveSelected: selected, }; }