/* Browsernatives ES-Modul; wird ohne Build-Schritt ausgeliefert. */
const dateFormatter = new Intl.DateTimeFormat('de-DE', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
const monthFormatter = new Intl.DateTimeFormat('de-DE', { month: 'long', year: 'numeric' });
const timeFormatter = new Intl.DateTimeFormat('de-DE', { hour: '2-digit', minute: '2-digit' });
const weekdays = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
const sessionProfileKey = 'sufw-booking-profile-v1';
function parseDateTime(value) { return new Date(value.replace(' ', 'T')); }
function parseDate(value) { return new Date(`${value}T12:00:00`); }
export function formatDateKey(date) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}
function eventDateRange(event) { return [event.startsAt.slice(0, 10), event.endsAt.slice(0, 10)]; }
function occursOnDate(event, date) { const [startDate, endDate] = eventDateRange(event); return startDate <= date && endDate >= date; }
export function getSlotsForDate(project, date, events = []) { return events.filter((event) => event.project === project && occursOnDate(event, date)); }
export function requiresIntroductionDetails(event = {}) { return event.project === 'produktionsschule' && event.introductionRequired === true; }
export function formatEventDuration(event) {
const start = parseDateTime(event.startsAt);
const end = parseDateTime(event.endsAt);
const [startDate, endDate] = eventDateRange(event);
if (startDate !== endDate) {
const dayCount = Math.round((parseDate(endDate) - parseDate(startDate)) / 86400000) + 1;
return `${dayCount} Tage`;
}
const hours = Math.round((end - start) / 3600000 * 10) / 10;
return `${String(hours).replace('.', ',')} ${hours === 1 ? 'Stunde' : 'Stunden'}`;
}
function formatEventTime(event) { return `${timeFormatter.format(parseDateTime(event.startsAt))}–${timeFormatter.format(parseDateTime(event.endsAt))} Uhr`; }
function formatEventFormat(event) { return event.format === 'telefonisch' ? 'Telefonisch' : 'Vor Ort'; }
export function validateBookingField(fieldName, value) {
const text = typeof value === 'string' ? value.trim() : '';
if (fieldName === 'name') return text && text.length <= 160 ? '' : 'Bitte geben Sie Ihren Namen ein.';
if (fieldName === 'email') return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text) && text.length <= 254 ? '' : 'Bitte geben Sie eine gültige E-Mail-Adresse ein.';
if (fieldName === 'phone') return /^[0-9+()\-/\s]{6,64}$/.test(text) ? '' : 'Bitte geben Sie eine gültige Telefonnummer ein.';
if (fieldName === 'introductionAttended') return value ? '' : 'Bitte bestätigen Sie die Teilnahme an einer Einführungsveranstaltung.';
if (fieldName === 'introductionDate') return /^\d{4}-\d{2}-\d{2}$/.test(text) ? '' : 'Bitte geben Sie das Datum der Einführungsveranstaltung ein.';
if (fieldName === 'privacy') return value ? '' : 'Bitte bestätigen Sie die Datenschutzhinweise.';
return '';
}
export function validateBookingForm({ name = '', email = '', phone = '', privacyAccepted = false, introductionAttended = false, introductionDate = '', event = {} }) {
const values = { name, email, phone, privacy: privacyAccepted };
if (requiresIntroductionDetails(event)) Object.assign(values, { introductionAttended, introductionDate });
return Object.fromEntries(Object.entries(values).map(([fieldName, value]) => [fieldName, validateBookingField(fieldName, value)]).filter(([, error]) => error));
}
export function canSubmitBookingForm(privacyAccepted) { return privacyAccepted; }
export function bookingConfirmationMessage(appointmentTitle) { return `Ihre Anmeldung für ${appointmentTitle} wurde verbindlich gespeichert.`; }
function escapeHtml(value) { return String(value).replace(/[&<>'"]/g, (character) => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' })[character]); }
function createMonthDates(month) {
const first = new Date(month.getFullYear(), month.getMonth(), 1);
const dates = new Array((first.getDay() + 6) % 7).fill(null);
const lastDay = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
for (let day = 1; day <= lastDay; day += 1) dates.push(new Date(month.getFullYear(), month.getMonth(), day));
return dates;
}
function loadSessionProfile() {
try { const profile = JSON.parse(sessionStorage.getItem(sessionProfileKey) ?? '{}'); return typeof profile === 'object' && profile ? profile : {}; } catch { return {}; }
}
function saveSessionProfile(profile) { try { sessionStorage.setItem(sessionProfileKey, JSON.stringify(profile)); } catch { /* Speicherung ist optional. */ } }
function showFieldError(form, fieldName, error) {
const field = form.elements.namedItem(fieldName);
if (!field) return;
const errorId = `sufw-booking-${fieldName}-error`;
let message = form.querySelector(`#${errorId}`);
if (!message) {
message = document.createElement('span');
message.id = errorId;
message.className = 'sufw-booking__field-error';
message.setAttribute('role', 'alert');
const host = fieldName === 'privacy' || fieldName === 'introductionAttended' ? field.closest('label') : field;
host.insertAdjacentElement('afterend', message);
field.setAttribute('aria-describedby', errorId);
}
message.textContent = error;
message.hidden = !error;
field.setAttribute('aria-invalid', error ? 'true' : 'false');
}
function openConfirmationDialog(container, event) {
const dialog = document.createElement('dialog');
dialog.className = 'sufw-booking__dialog';
dialog.setAttribute('aria-labelledby', 'sufw-booking-confirmation-title');
dialog.innerHTML = ` Termin bestätigt ${escapeHtml(bookingConfirmationMessage(event.title))} ${escapeHtml(event.project === 'perspektivwerk' ? 'PerspektivWerk' : 'Produktionsschule')} Dies ist die lokale Demoversion. Es wird noch keine Bestätigungs-, Erinnerungs- oder Kalender-E-Mail versendet.Vielen Dank für Ihre Anmeldung
${escapeHtml(dateFormatter.format(parseDate(event.startsAt.slice(0, 10))))} · ${formatEventTime(event)} · ${escapeHtml(event.title)}
Terminbuchung
Wählen Sie einen Tag. Termine zeigen Dauer, Format und freie Plätze.
Für diesen Tag liegen keine Termine vor.
'}${escapeHtml(error instanceof Error ? error.message : 'Der Kalender konnte nicht geladen werden.')}
`; } finally { container.removeAttribute('aria-busy'); } }; state.reload = loadAndRender; loadAndRender(); } export function initializeBookingComponents(root = document) { root.querySelectorAll('[data-sufw-booking]').forEach(renderComponent); } if (typeof document !== 'undefined') { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => initializeBookingComponents()); else initializeBookingComponents(); }