let questionIndex = 0; // Initialize SortableJS document.addEventListener("DOMContentLoaded", function() { var canvas = document.getElementById('builder-canvas'); if (canvas) { new Sortable(canvas, { animation: 150, handle: '.builder-handle', ghostClass: 'sortable-ghost', }); } }); function addQuestion(type) { const canvas = document.getElementById('builder-canvas'); const emptyState = document.getElementById('empty-state'); if (emptyState) { emptyState.remove(); } questionIndex++; const id = 'q_' + Date.now() + '_' + questionIndex; let typeLabel = ''; const needsOptions = ['single_choice', 'multiple_choice', 'dropdown'].includes(type); switch(type) { case 'text': typeLabel = 'Text Input'; break; case 'textarea': typeLabel = 'Text Area'; break; case 'single_choice': typeLabel = 'Single Choice'; break; case 'multiple_choice': typeLabel = 'Multiple Choice'; break; case 'dropdown': typeLabel = 'Dropdown'; break; } const div = document.createElement('div'); div.className = 'builder-item'; div.dataset.id = id; div.dataset.type = type; let html = `
☰ ${typeLabel}
`; if (needsOptions) { html += `
`; } div.innerHTML = html; canvas.appendChild(div); } function removeQuestion(btn) { btn.closest('.builder-item').remove(); const canvas = document.getElementById('builder-canvas'); if (canvas.children.length === 0) { canvas.innerHTML = '
No questions added yet. Use the buttons above to add one.
'; } } function prepareSubmission(e) { const questions = []; const items = document.querySelectorAll('.builder-item'); if (items.length === 0) { e.preventDefault(); alert("Please add at least one question."); return; } let hasEmptyLabel = false; let hasEmptyOptions = false; items.forEach((item) => { let labelInput = item.querySelector('.question-label'); let optionsInput = item.querySelector('.question-options'); let label = labelInput ? labelInput.value.trim() : ''; if (!label) { hasEmptyLabel = true; } let options = []; if (optionsInput) { options = optionsInput.value.split('\\n').map(o => o.trim()).filter(o => o); if (options.length === 0) { hasEmptyOptions = true; } } questions.push({ id: item.dataset.id, type: item.dataset.type, label: label, options: options }); }); if (hasEmptyLabel) { e.preventDefault(); alert("Please fill out all question labels."); return; } if (hasEmptyOptions) { e.preventDefault(); alert("Please provide at least one option for your choice/dropdown questions."); return; } document.getElementById('questions_input').value = JSON.stringify(questions); }