/* global usScheduler */ (function () { 'use strict'; const app = document.getElementById('us-booking-app'); if (!app) return; const slotList = document.getElementById('us-slot-list'); const confirm = document.getElementById('us-booking-confirmation'); const errorBox = document.getElementById('us-booking-error'); const { restUrl, nonce } = usScheduler; function apiFetch(path, options = {}) { return fetch(restUrl + path, { ...options, headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce, ...(options.headers || {}), }, }).then(async (res) => { const data = await res.json(); if (!res.ok) throw new Error(data.message || 'Request failed'); return data; }); } function showError(message) { errorBox.textContent = message; errorBox.style.display = 'block'; } function renderSlots(slots) { if (!slots.length) { slotList.innerHTML = '

No available lesson slots at this time.

'; return; } slotList.innerHTML = slots.map((slot) => `
${escHtml(slot.start_dt)} – ${escHtml(slot.end_dt)}
`).join(''); slotList.querySelectorAll('.us-book-btn').forEach((btn) => { btn.addEventListener('click', () => bookSlot(Number(btn.dataset.slotId))); }); } function escHtml(str) { return String(str) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function bookSlot(slotId) { errorBox.style.display = 'none'; apiFetch('bookings', { method: 'POST', body: JSON.stringify({ slot_id: slotId }), }) .then(() => { slotList.style.display = 'none'; confirm.style.display = 'block'; }) .catch((err) => showError(err.message)); } apiFetch('availability') .then(renderSlots) .catch((err) => showError(err.message)); }());