import { defaultCoolState, emptyCoolTally } from '#shared/cool' import type { CoolDemoState, CoolRound, CoolVoteTally } from '#shared/cool' /** State + tally polling for the stage and phone. 2 s is the demo fallback. */ export function useCoolDemo( round: Ref, initialState?: CoolDemoState | null, initialTally?: CoolVoteTally | null, ) { const state = ref(initialState ?? defaultCoolState(round.value)) const tally = ref(initialTally ?? emptyCoolTally(round.value)) const feedError = ref(false) let timer: ReturnType | undefined watch(round, () => { state.value = defaultCoolState(round.value) tally.value = emptyCoolTally(round.value) void poll() }) async function poll() { const [stateResult, tallyResult] = await Promise.allSettled([ $fetch('/api/cool/state', { query: { round: round.value }, headers: { accept: 'application/json', 'cache-control': 'no-cache' }, }), $fetch('/api/cool/vote', { query: { round: round.value }, headers: { accept: 'application/json', 'cache-control': 'no-cache' }, }), ]) if (stateResult.status === 'fulfilled') state.value = stateResult.value if (tallyResult.status === 'fulfilled') tally.value = tallyResult.value feedError.value = stateResult.status === 'rejected' || tallyResult.status === 'rejected' } async function update(patch: Partial>) { state.value = { ...state.value, ...patch, updatedAt: new Date().toISOString() } try { const next = await $fetch('/api/cool/state', { method: 'POST', body: { round: round.value, ...patch }, }) state.value = next } catch { feedError.value = true } } async function reset() { try { const result = await $fetch<{ state: CoolDemoState; tally: CoolVoteTally }>('/api/cool/reset', { method: 'POST', body: { round: round.value }, }) state.value = result.state tally.value = result.tally feedError.value = false } catch { feedError.value = true } } onMounted(() => { timer = setInterval(() => void poll(), 2000) }) onBeforeUnmount(() => { if (timer) clearInterval(timer) }) return { state, tally, feedError, update, reset, poll } }