import { useEffect, useState } from 'react'; import { getActiveEvent, getAgenda, groupAgenda } from './api'; import { DEFAULT_NOW } from './time'; import type { Event, Session, Slot } from './types'; export interface EventData { event: Event | null; slots: { slot: Slot; sessions: Session[] }[]; sessionById: Map; slotById: Map; now: Date; /** Which clock drives slot status: the simulated mid-event clock or the real one. */ clockMode: 'simulated' | 'realtime'; loading: boolean; error: string | null; reload: () => void; } /** Loads the active event + agenda, exposes them grouped by slot, plus the event clock. */ export function useEvent(): EventData { const [event, setEvent] = useState(null); const [slots, setSlots] = useState<{ slot: Slot; sessions: Session[] }[]>([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [nonce, setNonce] = useState(0); useEffect(() => { let active = true; (async () => { try { const [ev, rows] = await Promise.all([getActiveEvent(), getAgenda()]); if (!active) return; setEvent(ev); setSlots(groupAgenda(rows)); } catch (e) { if (active) setError(e instanceof Error ? e.message : 'Failed to load agenda'); } finally { if (active) setLoading(false); } })(); return () => { active = false; }; }, [nonce]); const sessionById = new Map(); const slotById = new Map(); for (const { slot, sessions } of slots) { slotById.set(slot.id, slot); for (const s of sessions) sessionById.set(s.id, s); } // The event's `use_realtime_clock` flag decides the clock: the real system // time, or the simulated mid-event clock (so the demo always looks live). const clockMode: 'simulated' | 'realtime' = event?.use_realtime_clock ? 'realtime' : 'simulated'; const now = clockMode === 'realtime' ? new Date() : DEFAULT_NOW; return { event, slots, sessionById, slotById, now, clockMode, loading, error, reload: () => setNonce((n) => n + 1), }; }