import { isCoolRouteId } from '#shared/cool' import type { CoolRouteId, CoolRound, CoolVoteResponse, CoolVoteTally } from '#shared/cool' const SESSION_KEY = 'cool-city-session-v1' /** One anonymous vote per browser and round. No PII. */ export function useCoolVote(round: Ref) { const mounted = ref(false) const sessionId = ref('') const myVote = ref('') const busy = ref(false) const error = ref('') const tally = ref(null) function voteKey(value: CoolRound) { return `cool-city-vote-v1:${value}` } function makeSessionId(): string { if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID() return `cool_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}` } function readStoredVote(value: CoolRound): CoolRouteId | '' { const stored = localStorage.getItem(voteKey(value)) return isCoolRouteId(stored) ? stored : '' } onMounted(() => { let storedSession = localStorage.getItem(SESSION_KEY) if (!storedSession || storedSession.length < 8) { storedSession = makeSessionId() localStorage.setItem(SESSION_KEY, storedSession) } sessionId.value = storedSession myVote.value = readStoredVote(round.value) mounted.value = true }) watch(round, (value) => { if (!mounted.value) return myVote.value = readStoredVote(value) tally.value = null error.value = '' }) async function vote(route: CoolRouteId) { if (!mounted.value || busy.value || myVote.value || !sessionId.value) return busy.value = true error.value = '' try { const response = await $fetch('/api/cool/vote', { method: 'POST', body: { route, sessionId: sessionId.value, round: round.value }, }) myVote.value = response.yourRoute tally.value = response.tally localStorage.setItem(voteKey(round.value), response.yourRoute) } catch (cause) { const status = (cause as { statusCode?: number; status?: number })?.statusCode ?? (cause as { status?: number })?.status error.value = status === 409 ? 'Voting is not open right now.' : 'The vote could not be recorded. Try again.' } finally { busy.value = false } } return { mounted, myVote, busy, error, tally, vote } }