(function () { const root = document.getElementById('visitor-ideas'); if (!root) return; const messages = { thanks: root.dataset.statusThanks, invalid: root.dataset.statusInvalid, slow: root.dataset.statusSlow, error: root.dataset.statusError, }; const status = new URLSearchParams(window.location.search).get('idea'); if (status && messages[status]) { const statusEl = document.createElement('p'); statusEl.className = `idea-status idea-status-${status}`; statusEl.textContent = messages[status]; const form = root.querySelector('.idea-form'); root.insertBefore(statusEl, form || root.firstChild); } function addIdeaText(parent, text) { String(text || '').split('\n').forEach((line, index) => { if (index > 0) parent.appendChild(document.createElement('br')); parent.appendChild(document.createTextNode(line)); }); } function renderIdeas(ideas) { const existing = root.querySelector('.visitor-idea-list'); if (existing) existing.remove(); if (!Array.isArray(ideas) || ideas.length === 0) return; const list = document.createElement('div'); list.className = 'visitor-idea-list'; const heading = document.createElement('h4'); heading.textContent = root.dataset.recentTitle || 'Recent visitor ideas'; list.appendChild(heading); ideas.forEach((idea) => { const article = document.createElement('article'); article.className = 'visitor-idea-card'; const body = document.createElement('p'); addIdeaText(body, idea.idea); article.appendChild(body); const footer = document.createElement('footer'); const name = document.createElement('span'); name.textContent = idea.name || 'Anonymous visitor'; const time = document.createElement('time'); time.dateTime = idea.created_at || ''; time.textContent = String(idea.created_at || '').slice(0, 10); footer.appendChild(name); footer.appendChild(time); article.appendChild(footer); list.appendChild(article); }); root.appendChild(list); } fetch('/visitor_ideas.php', { headers: { Accept: 'application/json' } }) .then((response) => (response.ok ? response.json() : { ideas: [] })) .then((data) => renderIdeas(data.ideas)) .catch(() => renderIdeas([])); })();