/**
* Quick Event Form Feature
*
* Handles the quick event creation form on the homepage.
* Supports both authenticated (direct API) and unauthenticated (localStorage) flows.
*/
import { authPostJson, SessionExpiredError } from '../../core/auth'
const STORAGE_KEY = 'smokesignal_quick_event'
export function initQuickEventForm(): void {
const form = document.getElementById('quick-event-form') as HTMLFormElement | null
if (!form) return
// Check authentication status from data attribute
const isAuthenticated = form.dataset.authenticated === 'true'
form.addEventListener('submit', (e) => {
e.preventDefault()
const titleInput = document.getElementById('home-quick-event-title') as HTMLInputElement | null
const descriptionInput = document.getElementById(
'home-quick-event-description'
) as HTMLTextAreaElement | null
const startsInput = document.getElementById(
'home-quick-event-starts'
) as HTMLInputElement | null
if (!titleInput || !descriptionInput || !startsInput) return
if (isAuthenticated) {
// Get the datetime-local value and convert to UTC
const localDateTime = startsInput.value
if (!localDateTime) {
alert('Please select a start time')
return
}
// Convert datetime-local to UTC ISO string
const localDate = new Date(localDateTime)
const utcISOString = localDate.toISOString()
// Create JSON payload for the API
const eventData = {
name: titleInput.value,
description: descriptionInput.value,
starts_at: utcISOString,
status: 'scheduled',
mode: 'inperson',
locations: [],
links: [],
require_confirmed_email: false,
send_notifications: true,
}
// Disable submit button
const submitButton = form.querySelector('button[type="submit"]') as HTMLButtonElement | null
if (submitButton) {
submitButton.disabled = true
submitButton.innerHTML =
'Creating...'
}
const resetButton = () => {
if (submitButton) {
submitButton.disabled = false
submitButton.innerHTML = 'Create Event'
}
}
authPostJson('/event', eventData)
.then(async (response) => {
const data = await response.json()
if (response.ok && data.url) {
// Redirect to the created event
window.location.href = data.url
} else {
// Show error
alert(data.error || 'Failed to create event. Please try again.')
resetButton()
}
})
.catch((error) => {
if (error instanceof SessionExpiredError) {
alert(error.message)
} else {
console.error('Error creating event:', error)
alert('Failed to create event. Please try again.')
}
resetButton()
})
} else {
// User is not authenticated, save to localStorage and redirect
const data = {
name: titleInput.value,
description: descriptionInput.value,
starts_at: startsInput.value,
}
localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
window.location.href = '/quick-event'
}
})
}