import { useEffect, useMemo, useRef, useState } from 'react'; import { supabase } from '../lib/supabase'; import { deleteEventSchedule, getAllContacts, getAllSessionSpeakers, getActiveEvent, getSessions, getSlots, setSessionSpeakers, uploadSessionMaterial, } from '../lib/api'; import type { Contact, Event, Session, SessionSpeaker, Slot, SlotType } from '../lib/types'; import { useSilentRefresh } from '../lib/useSilentRefresh'; import { useToast } from '../context/ToastContext'; import { MaterialPanel } from '../components/MaterialPanel'; import { Empty, Modal, Spinner, TypeBadge } from '../components/ui'; const SLOT_TYPES: SlotType[] = ['session', 'service_session']; export function Schedule() { const { push } = useToast(); const [event, setEvent] = useState(null); const [loaded, setLoaded] = useState(false); const [slots, setSlots] = useState([]); const [sessions, setSessions] = useState([]); const [speakers, setSpeakers] = useState([]); const [contacts, setContacts] = useState([]); const [error, setError] = useState(null); const [slotModal, setSlotModal] = useState<{ slot: Slot | null } | null>(null); const [sessModal, setSessModal] = useState<{ session: Session | null; slotId: number } | null>(null); const [deleteModal, setDeleteModal] = useState<{ eventId: string; eventName: string; slotsCount: number; sessionsCount: number; } | null>(null); const [busy, setBusy] = useState(false); const [deleting, setDeleting] = useState(false); const mountedRef = useRef(false); const loadSeqRef = useRef(0); async function load(expectedEventId?: string, silent = false) { const seq = ++loadSeqRef.current; try { const ev = await getActiveEvent(); if (!mountedRef.current || seq !== loadSeqRef.current) return; if (expectedEventId && ev?.id !== expectedEventId) { throw new Error('Active event changed before the schedule could refresh'); } setEvent(ev); if (ev) { const [s, ss, sp, c] = await Promise.all([ getSlots(ev.id), getSessions(ev.id), getAllSessionSpeakers(), getAllContacts(), ]); if (!mountedRef.current || seq !== loadSeqRef.current) return; setSlots(s); setSessions(ss); const ids = new Set(ss.map((x) => x.id)); setSpeakers(sp.filter((x) => ids.has(x.session_id))); setContacts(c); } else { setSlots([]); setSessions([]); setSpeakers([]); setContacts([]); } setLoaded(true); } catch (e) { if (!mountedRef.current || seq !== loadSeqRef.current) return; // A failed background tick must not replace a good table with the error // screen — this view renders `if (error) return ` — so it stays quiet. if (silent) return; setError(e instanceof Error ? e.message : 'Failed to load'); throw e; } } useEffect(() => { mountedRef.current = true; void load().catch(() => {}); return () => { mountedRef.current = false; loadSeqRef.current++; }; }, []); // Pull the schedule quietly in the background. Paused while a modal is open so // the form is never re-rendered underneath whoever is typing in it. Writes here // already `await load()`, so no refreshSoon is needed. useSilentRefresh(() => load(event?.id, true), { enabled: loaded && slotModal === null && sessModal === null && deleteModal === null, }); const speakersFor = useMemo(() => { const m = new Map(); for (const sp of speakers) { const arr = m.get(sp.session_id) ?? []; arr.push(sp.contact_email); m.set(sp.session_id, arr); } return m; }, [speakers]); const nameOf = (email: string) => contacts.find((c) => c.email === email)?.full_name ?? email; async function deleteSlot(slot: Slot) { if (!confirm(`Delete "${slot.name}" and all its sessions?`)) return; setBusy(true); try { const { error: err } = await supabase.from('slots').delete().eq('id', slot.id); if (err) throw err; await load(); push('success', `Deleted ${slot.name}`); } catch (e) { push('error', e instanceof Error ? e.message : 'Delete failed'); } finally { setBusy(false); } } async function deleteSession(sess: Session) { if (!confirm(`Delete session "${sess.title}"?`)) return; setBusy(true); try { const { error: err } = await supabase.from('sessions').delete().eq('id', sess.id); if (err) throw err; await load(); push('success', `Deleted ${sess.title}`); } catch (e) { push('error', e instanceof Error ? e.message : 'Delete failed'); } finally { setBusy(false); } } async function deleteCurrentSchedule() { const target = deleteModal; if (!target || deleting) return; setDeleting(true); try { const result = await deleteEventSchedule(target.eventId); if (!mountedRef.current) return; setDeleteModal(null); try { await load(target.eventId); if (!mountedRef.current) return; push( 'success', `Deleted ${result.slots_deleted} slots and ${result.sessions_deleted} sessions from ${target.eventName}`, ); } catch (refreshError) { if (!mountedRef.current) return; push( 'error', `Schedule deleted for ${target.eventName}, but refresh failed: ${ refreshError instanceof Error ? refreshError.message : 'unknown error' }`, ); } } catch (e) { if (!mountedRef.current) return; push('error', e instanceof Error ? e.message : 'Delete schedule failed'); } finally { if (mountedRef.current) setDeleting(false); } } if (error) return ; if (!loaded) return (
); if (!event) { return (

Schedule

Slots, sessions, speakers, and materials.
); } const hasSchedule = slots.length > 0 || sessions.length > 0; const mutating = busy || deleting; return (

Schedule

{event.name} · {slots.length} slots · {sessions.length} sessions.
{slots.map((slot) => { const slotSessions = sessions.filter((s) => s.slot_id === slot.id); return (
{slot.name}
{fmtDate(slot.slot_date)} · {fmtTime(slot.start_time)}–{fmtTime(slot.end_time)}
{slotSessions.length === 0 ? (
No sessions in this slot.
) : (
{slotSessions.map((s) => { const spk = (speakersFor.get(s.id) ?? []).map(nameOf).join(', '); return (
{s.title}
{[s.room, spk || 'no speakers', s.capacity ? `cap ${s.capacity}` : null, s.level ? `📶 ${s.level}` : null, s.area ? `🗂 ${s.area}` : null].filter(Boolean).join(' · ')}
{s.average_feedback != null && ⭐ {s.average_feedback.toFixed(1)}} · {s.material_path ? '📎 material submitted' : '⬜ material not submitted'}
); })}
)}
); })}
{slotModal && ( setSlotModal(null)} onSaved={async (msg) => { setSlotModal(null); await load(); push('success', msg); }} /> )} {deleteModal && ( { if (!deleting) setDeleteModal(null); }} footer={ <> } >

Delete the schedule for {deleteModal.eventName}?

This irreversibly deletes {deleteModal.slotsCount} slots and {deleteModal.sessionsCount} sessions, including speaker links, preferences, check-ins and feedback. Registrations are preserved. Material file paths are removed with the sessions, but Storage objects are not physically purged.

)} {sessModal && ( s.id === sessModal.slotId)} eventId={event.id} contacts={contacts} currentSpeakers={speakersFor.get(sessModal.session?.id ?? '') ?? []} onClose={() => setSessModal(null)} onSaved={async (msg) => { setSessModal(null); await load(); push('success', msg); }} /> )}
); } function SlotModal({ slot, eventId, onClose, onSaved, }: { slot: Slot | null; eventId: string; onClose: () => void; onSaved: (msg: string) => void; }) { const [name, setName] = useState(slot?.name ?? ''); const [type, setType] = useState(slot?.type ?? 'session'); const [date, setDate] = useState(slot ? slot.slot_date.slice(0, 10) : ''); const [start, setStart] = useState(slot ? slot.start_time.slice(0, 5) : '09:00'); const [end, setEnd] = useState(slot ? slot.end_time.slice(0, 5) : '10:00'); const [busy, setBusy] = useState(false); async function save() { if (!name.trim() || !date) return; setBusy(true); try { const payload = { name: name.trim(), type, slot_date: date, start_time: start, end_time: end, event_id: eventId }; if (slot) { const { error: err } = await supabase.from('slots').update(payload).eq('id', slot.id); if (err) throw err; } else { const { error: err } = await supabase.from('slots').insert(payload); if (err) throw err; } onSaved(slot ? 'Slot updated' : 'Slot created'); } catch (e) { onSaved(e instanceof Error ? e.message : 'Save failed'); } finally { setBusy(false); } } return ( } >
setName(e.target.value)} placeholder="e.g. Morning keynote" />
setDate(e.target.value)} />
setStart(e.target.value)} />
setEnd(e.target.value)} />
); } function SessionModal({ session, slotId, slot, eventId, contacts, currentSpeakers, onClose, onSaved, }: { session: Session | null; slotId: number; /** Slot this session belongs to; used to show when material unlocks for attendees. */ slot?: Slot; eventId: string; contacts: Contact[]; currentSpeakers: string[]; onClose: () => void; onSaved: (msg: string) => void; }) { const [title, setTitle] = useState(session?.title ?? ''); const [room, setRoom] = useState(session?.room ?? ''); const [capacity, setCapacity] = useState(session?.capacity?.toString() ?? ''); const [description, setDescription] = useState(session?.description ?? ''); const [level, setLevel] = useState(session?.level ?? ''); const [area, setArea] = useState(session?.area ?? ''); const [speakerEmails, setSpeakerEmails] = useState(currentSpeakers); const [material, setMaterial] = useState(null); const [busy, setBusy] = useState(false); async function save() { if (!title.trim()) return; setBusy(true); try { const payload = { title: title.trim(), room: room.trim() || null, capacity: capacity ? parseInt(capacity, 10) : null, description: description.trim() || null, level: level.trim() || null, area: area.trim() || null, slot_id: slotId, event_id: eventId, }; let sessionId = session?.id; if (session) { const { error: err } = await supabase.from('sessions').update(payload).eq('id', session.id); if (err) throw err; } else { const { data: ins, error: err } = await supabase.from('sessions').insert(payload).select().single(); if (err) throw err; sessionId = (ins as Session).id; } // Speakers (a session must keep >= 1 speaker). if (sessionId && speakerEmails.length > 0) { await setSessionSpeakers(sessionId, speakerEmails); } // Material upload (if a new file was chosen). Passes the old path so a // replacement removes the previous object instead of orphaning it. if (sessionId && material) { await uploadSessionMaterial(sessionId, material, session?.material_path); } onSaved(session ? 'Session updated' : 'Session created'); } catch (e) { onSaved(e instanceof Error ? e.message : 'Save failed'); } finally { setBusy(false); } } function toggleSpeaker(email: string) { setSpeakerEmails((prev) => prev.includes(email) ? prev.filter((x) => x !== email) : [...prev, email], ); } return ( } >
setTitle(e.target.value)} placeholder="e.g. The future of networking" />
setRoom(e.target.value)} placeholder="—" />
setCapacity(e.target.value)} placeholder="—" />