(() => { "use strict"; const $ = (selector, root = document) => root.querySelector(selector); const $$ = (selector, root = document) => Array.from(root.querySelectorAll(selector)); const STORAGE_KEY = "mama-boek-voortgang"; const SOUND_KEY = "mama-boek-geluid"; const EMBLEMS = { moon: ` `, feather: ` `, key: ` `, leaf: ` `, ship: ` `, star: ` `, owl: ` `, teacup: ` ` }; const els = { shelves: $$(".shelf"), slots: $("#slots"), secret: $("#secret-word"), secretHint: $("#secret-hint"), log: $("#log"), progressText: $("#progress-text"), progressPercent: $("#progress-percent"), progressTrack: $("#progress-track"), progressBar: $("#progress-bar"), drawer: $("#drawer"), drawerLabel: $("#drawer-label"), drawerHint: $("#drawer-hint"), bookModal: $("#book-modal"), bookDialog: $("#book-dialog"), bookClose: $("#book-close"), dialogEmblem: $("#dialog-emblem"), dialogTitle: $("#book-dialog-title"), dialogAuthor: $("#book-dialog-author"), dialogIntro: $("#book-dialog-intro"), dialogQuote: $("#book-dialog-quote"), question: $("#book-question"), options: $("#book-options"), feedback: $("#book-feedback"), hint: $("#book-hint"), stamp: $("#letter-stamp"), stampLetter: $("#stamp-letter"), doneBtn: $("#book-done-btn"), voucherModal: $("#voucher-modal"), voucherLead: $("#voucher-lead"), voucherCode: $("#voucher-code"), voucherRecipient: $("#voucher-recipient"), voucherDate: $("#voucher-date"), voucherNote: $("#voucher-note"), voucherClose: $("#voucher-close"), copyButton: $("#copy-code"), playAgain: $("#play-again"), soundButton: $("#sound-toggle"), confetti: $("#confetti") }; const confettiContext = els.confetti.getContext("2d"); const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; const state = { config: null, books: new Map(), order: [], solvedCount: 0, soundOn: true, finished: false, currentBookId: null, requestInFlight: false, requestSerial: 0, bookReturnFocus: null, voucherReturnFocus: null, audio: null, confettiFrame: null, confettiParticles: [] }; try { state.soundOn = window.localStorage.getItem(SOUND_KEY) !== "uit"; } catch { state.soundOn = true; } function pick(list) { return list[Math.floor(Math.random() * list.length)]; } function renderEmblem(name) { return EMBLEMS[name] || EMBLEMS.star; } function setLog(message, kind = "normal") { els.log.textContent = message; els.log.classList.toggle("is-warning", kind === "warning"); els.log.classList.toggle("is-done", kind === "done"); } function updateSoundButton() { els.soundButton.setAttribute("aria-pressed", String(state.soundOn)); const label = state.soundOn ? "Geluid dempen" : "Geluid aanzetten"; els.soundButton.setAttribute("aria-label", label); els.soundButton.title = label; } function ensureAudio() { if (!state.soundOn) { return null; } if (!state.audio) { const AudioContextClass = window.AudioContext || window.webkitAudioContext; if (!AudioContextClass) { return null; } try { state.audio = new AudioContextClass(); } catch { return null; } } if (state.audio.state === "suspended") { state.audio.resume().catch(() => {}); } return state.audio; } function playTone({ freq = 200, endFreq = freq, type = "sine", duration = 0.16, gain = 0.15, delay = 0 }) { const context = ensureAudio(); if (!context) { return; } const start = context.currentTime + delay; const oscillator = context.createOscillator(); const volume = context.createGain(); oscillator.type = type; oscillator.frequency.setValueAtTime(Math.max(20, freq), start); oscillator.frequency.exponentialRampToValueAtTime(Math.max(20, endFreq), start + duration); volume.gain.setValueAtTime(0.0001, start); volume.gain.exponentialRampToValueAtTime(Math.max(0.0001, gain), start + 0.012); volume.gain.exponentialRampToValueAtTime(0.0001, start + duration); oscillator.connect(volume).connect(context.destination); oscillator.start(start); oscillator.stop(start + duration + 0.03); } function playNoise({ duration = 0.2, gain = 0.2, frequency = 900, delay = 0 } = {}) { const context = ensureAudio(); if (!context) { return; } const frames = Math.max(1, Math.floor(context.sampleRate * duration)); const buffer = context.createBuffer(1, frames, context.sampleRate); const data = buffer.getChannelData(0); for (let index = 0; index < frames; index += 1) { data[index] = (Math.random() * 2 - 1) * (1 - index / frames); } const source = context.createBufferSource(); source.buffer = buffer; const filter = context.createBiquadFilter(); filter.type = "bandpass"; filter.frequency.value = frequency; filter.Q.value = 0.8; const volume = context.createGain(); volume.gain.value = gain; source.connect(filter).connect(volume).connect(context.destination); source.start(context.currentTime + delay); } function playPageTurn() { playNoise({ duration: 0.15, gain: 0.06, frequency: 1600 }); playTone({ freq: 520, endFreq: 340, type: "sine", duration: 0.09, gain: 0.035 }); } function playCorrect() { playTone({ freq: 659.25, endFreq: 659.25, type: "triangle", duration: 0.16, gain: 0.09 }); playTone({ freq: 987.77, endFreq: 987.77, type: "sine", duration: 0.2, gain: 0.075, delay: 0.1 }); playTone({ freq: 1318.51, endFreq: 1318.51, type: "sine", duration: 0.28, gain: 0.06, delay: 0.2 }); } function playWrong() { playTone({ freq: 300, endFreq: 210, type: "triangle", duration: 0.12, gain: 0.06 }); playTone({ freq: 180, endFreq: 140, type: "sine", duration: 0.18, gain: 0.05, delay: 0.08 }); } function playUnlock() { playNoise({ duration: 0.07, gain: 0.08, frequency: 2500 }); playTone({ freq: 340, endFreq: 120, type: "square", duration: 0.13, gain: 0.05 }); playTone({ freq: 660, endFreq: 660, type: "triangle", duration: 0.09, gain: 0.04, delay: 0.06 }); } function playFanfare() { const notes = [523.25, 659.25, 783.99, 1046.5]; notes.forEach((frequency, index) => { playTone({ freq: frequency, endFreq: frequency, type: "triangle", duration: 0.26, gain: 0.11, delay: index * 0.12 }); }); playTone({ freq: 1318.51, endFreq: 1318.51, type: "sine", duration: 0.55, gain: 0.08, delay: 0.52 }); } function loadProgress() { try { const raw = window.localStorage.getItem(STORAGE_KEY); if (!raw) { return {}; } const parsed = JSON.parse(raw); const saved = parsed && typeof parsed === "object" ? parsed.solved : null; if (!saved || typeof saved !== "object") { return {}; } const clean = {}; Object.entries(saved).forEach(([id, value]) => { if (!value || typeof value !== "object") { return; } if (typeof value.letter !== "string" || value.letter.length !== 1) { return; } clean[id] = { letter: value.letter.toUpperCase(), answer: Number.isInteger(value.answer) ? value.answer : null, done: typeof value.done === "string" ? value.done : "", explanation: typeof value.explanation === "string" ? value.explanation : "" }; }); return clean; } catch { return {}; } } function saveProgress() { const solved = {}; state.books.forEach((book) => { if (!book.solved) { return; } solved[book.id] = { letter: book.letter, answer: book.answerIndex, done: book.doneText, explanation: book.explanation }; }); try { window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ solved })); } catch { } } function buildBook(meta) { const button = document.createElement("button"); button.type = "button"; button.className = "book"; button.dataset.id = meta.id; button.style.setProperty("--cover", meta.color || "#2e4a30"); button.style.setProperty("--cover-2", meta.color2 || "#557c4c"); button.style.setProperty("--book-ink", meta.ink || "#f7eedb"); button.setAttribute("aria-label", `${meta.title} van ${meta.author} openen`); const cover = document.createElement("span"); cover.className = "book-cover"; const frame = document.createElement("span"); frame.className = "book-frame"; frame.setAttribute("aria-hidden", "true"); const emblem = document.createElement("span"); emblem.className = "book-emblem"; emblem.setAttribute("aria-hidden", "true"); emblem.innerHTML = renderEmblem(meta.emblem); const title = document.createElement("span"); title.className = "book-title"; title.textContent = meta.title; const author = document.createElement("span"); author.className = "book-author"; author.textContent = meta.author; const status = document.createElement("span"); status.className = "book-state"; status.setAttribute("aria-hidden", "true"); cover.append(frame, emblem, title, author, status); const bookmark = document.createElement("span"); bookmark.className = "bookmark"; bookmark.setAttribute("aria-hidden", "true"); button.append(cover, bookmark); button.addEventListener("click", () => openBook(meta.id)); return button; } function buildBooks(config) { els.shelves.forEach((shelf) => shelf.replaceChildren()); state.books.clear(); state.order = []; const saved = loadProgress(); config.books.forEach((meta, index) => { const element = buildBook(meta); const shelf = els.shelves[Math.floor(index / 4)] || els.shelves[els.shelves.length - 1]; if (shelf) { shelf.appendChild(element); } const book = { id: meta.id, meta, element, solved: false, attempts: 0, letter: "", answerIndex: null, doneText: "", explanation: "" }; state.books.set(meta.id, book); state.order.push(book); if (saved[meta.id]) { applySolvedState(book, saved[meta.id]); } }); buildSlots(); updateProgress(); updateSlots(); } function buildSlots() { els.slots.replaceChildren(); state.order.forEach((book, index) => { const slot = document.createElement("span"); slot.className = "slot"; slot.dataset.id = book.id; slot.dataset.index = String(index); slot.setAttribute("aria-label", `Letter ${index + 1}: nog niet gevonden`); els.slots.appendChild(slot); }); } function updateSlots() { state.order.forEach((book, index) => { const slot = els.slots.children[index]; if (!slot) { return; } if (book.solved && book.letter) { if (slot.textContent !== book.letter) { slot.textContent = book.letter; } slot.classList.add("filled"); slot.setAttribute("aria-label", `Letter ${index + 1}: ${book.letter}`); } else { slot.textContent = ""; slot.classList.remove("filled"); slot.setAttribute("aria-label", `Letter ${index + 1}: nog niet gevonden`); } }); const complete = state.order.length > 0 && state.order.every((book) => book.solved); els.secret.classList.toggle("is-complete", complete); els.secretHint.textContent = complete ? "De letters vormen samen het wachtwoord van de lade." : "Elk gelezen boek onthult één letter."; } function updateProgress() { const total = state.order.length; state.solvedCount = state.order.filter((book) => book.solved).length; const percentage = total === 0 ? 0 : Math.round((state.solvedCount / total) * 100); els.progressText.textContent = `${state.solvedCount} / ${total} boeken gelezen`; els.progressPercent.textContent = `${percentage}%`; els.progressBar.style.width = `${percentage}%`; els.progressTrack.setAttribute("aria-valuenow", String(percentage)); state.finished = total > 0 && state.solvedCount === total; } function applySolvedState(book, saved) { book.solved = true; book.attempts = 0; book.letter = saved.letter; book.answerIndex = saved.answer; book.doneText = saved.done; book.explanation = saved.explanation; book.element.classList.add("is-solved"); book.element.setAttribute( "aria-label", `${book.meta.title} van ${book.meta.author}, gelezen` ); } function renderOptions(book) { els.options.replaceChildren(); const keys = ["A", "B", "C", "D", "E", "F"]; book.meta.options.forEach((text, index) => { const button = document.createElement("button"); button.type = "button"; button.className = "option"; button.dataset.index = String(index); button.disabled = book.solved; const key = document.createElement("span"); key.className = "option-key"; key.setAttribute("aria-hidden", "true"); key.textContent = keys[index] || String(index + 1); const label = document.createElement("span"); label.className = "option-text"; label.textContent = text; button.append(key, label); button.addEventListener("click", () => answerBook(book, index)); els.options.appendChild(button); }); if (book.solved) { $$(".option", els.options).forEach((button, index) => { button.disabled = true; if (index === book.answerIndex) { button.classList.add("is-correct"); } }); showSolvedState(book); } } function showSolvedState(book) { els.feedback.className = "feedback is-correct"; els.feedback.textContent = book.explanation || book.doneText || `Juist. De letter ${book.letter} is gevonden.`; els.hint.hidden = true; els.hint.textContent = ""; els.stampLetter.textContent = book.letter; els.stamp.hidden = false; els.stamp.classList.remove("is-visible"); void els.stamp.offsetWidth; els.stamp.classList.add("is-visible"); els.doneBtn.hidden = false; els.doneBtn.textContent = "Terug naar de kast"; } function openBook(id) { const book = state.books.get(id); if (!book) { return; } state.currentBookId = id; state.bookReturnFocus = document.activeElement; state.requestSerial += 1; state.requestInFlight = false; els.dialogEmblem.innerHTML = renderEmblem(book.meta.emblem); els.dialogTitle.textContent = book.meta.title; els.dialogAuthor.textContent = book.meta.author; els.dialogIntro.textContent = book.meta.intro; els.dialogQuote.textContent = book.meta.quote; els.question.textContent = book.meta.question; els.feedback.textContent = ""; els.feedback.className = "feedback"; els.hint.hidden = true; els.hint.textContent = ""; els.stamp.hidden = true; els.stamp.classList.remove("is-visible"); els.doneBtn.hidden = true; els.doneBtn.textContent = "Terug naar de kast"; renderOptions(book); els.bookModal.hidden = false; syncBodyLock(); playPageTurn(); window.setTimeout(() => { if (book.solved) { els.doneBtn.focus(); return; } const firstOption = $(".option", els.options); (firstOption || els.bookClose).focus(); }, 90); } async function answerBook(book, index) { if (book.solved || state.requestInFlight) { return; } const serial = ++state.requestSerial; state.requestInFlight = true; const isCurrent = () => serial === state.requestSerial && state.currentBookId === book.id; const optionButtons = $$(".option", els.options); optionButtons.forEach((button) => { button.disabled = true; }); els.feedback.className = "feedback"; els.feedback.textContent = "Even bladeren..."; ensureAudio(); try { const response = await fetch("/api/solve", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ bookId: book.id, answer: index }) }); const data = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(data.error || "De leeshoek is even niet bereikbaar."); } if (data.ok) { markSolved(book, data, index, isCurrent()); return; } if (book.solved || !isCurrent()) { return; } book.attempts += 1; const chosen = optionButtons[index]; if (chosen) { chosen.classList.add("is-wrong"); window.setTimeout(() => chosen.classList.remove("is-wrong"), 700); } const page = $(".page-right", els.bookDialog); page.classList.remove("is-shaking"); void page.offsetWidth; page.classList.add("is-shaking"); window.setTimeout(() => page.classList.remove("is-shaking"), 360); els.feedback.className = "feedback is-error"; els.feedback.textContent = data.error || "Nog niet helemaal. Probeer het nog eens."; if (book.attempts >= 2) { els.hint.textContent = data.hint || book.meta.hint; els.hint.hidden = false; } playWrong(); const extra = book.attempts >= 2 ? "De hint staat in het boek." : "Lees rustig verder."; setLog(`Nog niet helemaal bij "${book.meta.title}". ${extra}`, "warning"); } catch (error) { if (isCurrent()) { els.feedback.className = "feedback is-error"; els.feedback.textContent = `${error.message} Probeer het zo nog eens.`; playWrong(); } } finally { if (serial === state.requestSerial) { state.requestInFlight = false; if (!book.solved && isCurrent()) { optionButtons.forEach((button) => { button.disabled = false; }); const firstOption = $(".option", els.options); if (firstOption) { firstOption.focus(); } } } } } function markSolved(book, data, answerIndex, updateDialog) { book.solved = true; book.letter = String(data.letter || "").toUpperCase(); book.answerIndex = answerIndex; book.doneText = data.done || ""; book.explanation = data.explanation || ""; book.element.classList.add("is-solved"); book.element.setAttribute( "aria-label", `${book.meta.title} van ${book.meta.author}, gelezen` ); updateProgress(); updateSlots(); saveProgress(); playCorrect(); setLog(book.doneText || `Juist. De letter ${book.letter} is gevonden.`, "done"); if (updateDialog) { $$(".option", els.options).forEach((button, index) => { button.disabled = true; if (index === answerIndex) { button.classList.add("is-correct"); } }); showSolvedState(book); window.setTimeout(() => els.doneBtn.focus(), 260); } if (state.solvedCount === state.order.length) { unlockDrawer({ announce: true, sound: true }); } } function lockDrawer() { els.drawer.classList.remove("is-unlocked", "is-locked-shake"); els.drawerLabel.textContent = "Geheime lade"; els.drawerHint.textContent = "Nog op slot"; els.drawer.setAttribute("aria-label", "Geheime lade, nog op slot"); } function unlockDrawer({ announce = true, sound = true } = {}) { const wasLocked = !els.drawer.classList.contains("is-unlocked"); els.drawer.classList.add("is-unlocked"); els.drawerLabel.textContent = "Open de geheime lade"; els.drawerHint.textContent = "Klik om te openen"; els.drawer.setAttribute("aria-label", "Open de geheime lade"); if (wasLocked && sound) { playUnlock(); } if (wasLocked && announce) { setLog( "Alle acht boeken zijn gelezen. De letters vormen LEESHOEK — de lade klikt open!", "done" ); } } function handleDrawer() { if (state.order.length === 0) { setLog("De boekenkast is nog niet geladen. Probeer de pagina even opnieuw.", "warning"); return; } if (state.solvedCount !== state.order.length) { const remaining = state.order.length - state.solvedCount; els.drawer.classList.remove("is-locked-shake"); void els.drawer.offsetWidth; els.drawer.classList.add("is-locked-shake"); window.setTimeout(() => els.drawer.classList.remove("is-locked-shake"), 420); const message = remaining === 1 ? "De lade zit nog op slot. Er is nog één boek te lezen." : `De lade zit nog op slot. Er zijn nog ${remaining} boeken te lezen.`; setLog(message, "warning"); playWrong(); return; } openVoucher(); } function openVoucher() { state.voucherReturnFocus = document.activeElement; els.voucherModal.hidden = false; syncBodyLock(); els.voucherCode.textContent = "code wordt gezocht..."; els.voucherNote.textContent = ""; els.voucherNote.style.color = ""; els.copyButton.textContent = "Kopieer"; els.copyButton.classList.remove("is-copied"); window.setTimeout(() => els.voucherClose.focus(), 80); requestVoucher(); } async function requestVoucher() { const completed = state.order.filter((book) => book.solved).map((book) => book.id); try { const response = await fetch("/api/reveal", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ completed }) }); const data = await response.json().catch(() => ({})); if (!response.ok || !data.ok) { throw new Error(data.error || "De code kon niet worden opgehaald."); } els.voucherCode.textContent = data.code; els.voucherRecipient.textContent = `Voor ${data.recipient || state.config.recipient}`; els.voucherDate.textContent = data.eventDate || state.config.eventDate; els.voucherNote.textContent = "De code staat klaar. Kopieer hem of houd deze pagina open."; els.voucherNote.style.color = ""; playFanfare(); launchConfetti(); } catch (error) { els.voucherCode.textContent = "—"; els.voucherNote.textContent = `${error.message} Probeer het opnieuw.`; els.voucherNote.style.color = "#a33b22"; } } function syncBodyLock() { const open = !els.bookModal.hidden || !els.voucherModal.hidden; document.body.classList.toggle("has-modal", open); } function closeBookModal() { if (els.bookModal.hidden) { return; } els.bookModal.hidden = true; state.currentBookId = null; state.requestInFlight = false; state.requestSerial += 1; syncBodyLock(); const target = state.bookReturnFocus; if (target && typeof target.focus === "function") { target.focus(); } } function closeVoucher() { if (els.voucherModal.hidden) { return; } els.voucherModal.hidden = true; stopConfetti(); syncBodyLock(); const target = state.voucherReturnFocus; if (target && typeof target.focus === "function") { target.focus(); } else { els.drawer.focus(); } } function resetGame() { state.books.forEach((book) => { book.solved = false; book.attempts = 0; book.letter = ""; book.answerIndex = null; book.doneText = ""; book.explanation = ""; book.element.classList.remove("is-solved"); book.element.setAttribute( "aria-label", `${book.meta.title} van ${book.meta.author} openen` ); }); try { window.localStorage.removeItem(STORAGE_KEY); } catch { } lockDrawer(); updateProgress(); updateSlots(); els.secret.classList.remove("is-complete"); els.log.className = "log"; setLog("Nieuwe ronde, dezelfde kast. Kies een boek en begin opnieuw.", "done"); closeVoucher(); state.currentBookId = null; state.requestInFlight = false; state.requestSerial += 1; if (state.order[0]) { state.order[0].element.focus(); } } function resizeConfetti() { const ratio = Math.min(2, window.devicePixelRatio || 1); els.confetti.width = Math.floor(window.innerWidth * ratio); els.confetti.height = Math.floor(window.innerHeight * ratio); confettiContext.setTransform(ratio, 0, 0, ratio, 0, 0); } function launchConfetti() { if (reduceMotion) { return; } resizeConfetti(); const colors = ["#f0c96a", "#d9a441", "#f6ecd8", "#8c3b3b", "#6f8f6a", "#3b7a6e", "#62477c", "#fff7e3"]; state.confettiParticles = Array.from({ length: 180 }, () => ({ x: Math.random() * window.innerWidth, y: -30 - Math.random() * window.innerHeight * 0.55, vx: (Math.random() - 0.5) * 120, vy: 80 + Math.random() * 170, width: 5 + Math.random() * 7, height: 8 + Math.random() * 11, rotation: Math.random() * Math.PI, spin: (Math.random() - 0.5) * 11, color: pick(colors) })); if (state.confettiFrame) { window.cancelAnimationFrame(state.confettiFrame); } let last = performance.now(); const tick = (now) => { const delta = Math.min(0.05, (now - last) / 1000); last = now; confettiContext.clearRect(0, 0, window.innerWidth, window.innerHeight); let visible = 0; state.confettiParticles.forEach((particle) => { particle.vy += 190 * delta; particle.x += particle.vx * delta; particle.y += particle.vy * delta; particle.rotation += particle.spin * delta; if (particle.y < window.innerHeight + 40) { visible += 1; } confettiContext.save(); confettiContext.translate(particle.x, particle.y); confettiContext.rotate(particle.rotation); confettiContext.fillStyle = particle.color; confettiContext.fillRect( -particle.width / 2, -particle.height / 2, particle.width, particle.height ); confettiContext.restore(); }); if (visible > 0) { state.confettiFrame = window.requestAnimationFrame(tick); } else { state.confettiFrame = null; confettiContext.clearRect(0, 0, window.innerWidth, window.innerHeight); } }; state.confettiFrame = window.requestAnimationFrame(tick); window.setTimeout(stopConfetti, 8000); } function stopConfetti() { if (state.confettiFrame) { window.cancelAnimationFrame(state.confettiFrame); state.confettiFrame = null; } state.confettiParticles = []; confettiContext.clearRect(0, 0, window.innerWidth, window.innerHeight); } function legacyCopy(text) { const field = document.createElement("textarea"); field.value = text; field.setAttribute("readonly", ""); field.style.position = "fixed"; field.style.opacity = "0"; document.body.appendChild(field); field.select(); try { document.execCommand("copy"); } catch { } field.remove(); } async function copyCode() { const code = els.voucherCode.textContent.trim(); const busy = !code || code === "..." || code.startsWith("code wordt") || code === "—"; if (busy) { return; } try { await navigator.clipboard.writeText(code); } catch { legacyCopy(code); } els.copyButton.textContent = "Gekopieerd"; els.copyButton.classList.add("is-copied"); els.voucherNote.textContent = "De code staat op je klembord."; els.voucherNote.style.color = ""; window.setTimeout(() => { els.copyButton.textContent = "Kopieer"; els.copyButton.classList.remove("is-copied"); }, 2200); } function applyConfig(config) { const setText = (selector, value) => { const node = $(selector); if (node && value) { node.textContent = value; } }; setText("#recipient-name", config.recipient); setText("#footer-name", config.recipient); setText("#footer-date", config.eventDate); setText("#plaque-recipient", `Voor ${config.recipient}`); setText("#voucher-recipient", `Voor ${config.recipient}`); setText("#voucher-date", config.eventDate); setText("#game-title", config.title); setText("#game-subtitle", config.subtitle); setText( "#voucher-lead", `${config.recipient}, je hebt alle acht boeken gelezen. Achter de kast lag een envelop met iets om zelf een nieuw verhaal uit te kiezen.` ); if (config.title) { document.title = config.title; } } function trapFocus(event, container) { if (event.key !== "Tab") { return; } const focusable = $$( 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])', container ).filter((element) => element.getClientRects().length > 0); if (focusable.length === 0) { return; } const first = focusable[0]; const last = focusable[focusable.length - 1]; if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } } function bindEvents() { els.soundButton.addEventListener("click", () => { state.soundOn = !state.soundOn; try { window.localStorage.setItem(SOUND_KEY, state.soundOn ? "aan" : "uit"); } catch { } updateSoundButton(); if (state.soundOn) { playTone({ freq: 660, endFreq: 880, type: "triangle", duration: 0.12, gain: 0.08 }); } }); els.bookClose.addEventListener("click", closeBookModal); els.doneBtn.addEventListener("click", closeBookModal); els.voucherClose.addEventListener("click", closeVoucher); els.playAgain.addEventListener("click", resetGame); els.copyButton.addEventListener("click", copyCode); els.drawer.addEventListener("click", handleDrawer); $$("[data-close]").forEach((node) => { node.addEventListener("click", () => { if (node.dataset.close === "book") { closeBookModal(); } else { closeVoucher(); } }); }); document.addEventListener("keydown", (event) => { if (event.key === "Escape") { if (!els.voucherModal.hidden) { closeVoucher(); return; } if (!els.bookModal.hidden) { closeBookModal(); } return; } if (!els.voucherModal.hidden) { trapFocus(event, els.voucherModal); } else if (!els.bookModal.hidden) { trapFocus(event, els.bookDialog); } }); window.addEventListener("resize", () => { if (state.confettiParticles.length > 0) { resizeConfetti(); } }); } async function init() { updateSoundButton(); bindEvents(); lockDrawer(); try { const response = await fetch("/api/config", { cache: "no-store" }); if (!response.ok) { throw new Error("De boekenkast is niet bereikbaar."); } const config = await response.json(); state.config = config; applyConfig(config); buildBooks(config); if (state.solvedCount === state.order.length) { unlockDrawer({ announce: false, sound: false }); setLog( "Welkom terug. Alle acht boeken zijn al gelezen — de lade staat op je te wachten.", "done" ); } else if (state.solvedCount > 0) { setLog( `Welkom terug. Je was bij ${state.solvedCount} van ${state.order.length} boeken. De kast houdt je plekje warm.`, "done" ); } else { setLog("De kast staat klaar. Kies een boek en los de kleine opdracht op."); } } catch (error) { setLog(`De boekenkast kon niet geladen worden: ${error.message}`, "warning"); els.progressText.textContent = "Niet geladen"; els.progressPercent.textContent = "—"; } } init(); })();