console.log('form_create.js: Script loaded');

function addQuestion() {
    console.log('addQuestion: Function called');
    try {
        const questionContainer = document.getElementById('questions-container');
        if (!questionContainer) {
            console.error('addQuestion: questions-container not found');
            alert('Error: Questions container not found.');
            return;
        }
        const questionIndex = document.querySelectorAll('.question-item').length;
        const questionDiv = document.createElement('div');
        questionDiv.className = 'question-item mb-3';
        questionDiv.innerHTML = `
            <div class="card">
                <div class="card-body">
                    <div class="form-group mb-3">
                        <label>Question Text</label>
                        <input type="text" name="questions[${questionIndex}][text]" class="form-control" required>
                    </div>
                    <div class="form-group mb-3">
                        <label>Question Type</label>
                        <select name="questions[${questionIndex}][type]" class="form-control question-type" required>
                            <option value="">Select Type</option>
                            <option value="short_answer">Short Answer</option>
                            <option value="paragraph">Paragraph</option>
                            <option value="multiple_choice">Multiple Choice</option>
                            <option value="single_choice">Single Choice</option>
                            <option value="checkboxes">Checkboxes</option>
                            <option value="dropdown">Dropdown</option>
                            <option value="rating">Rating</option>
                            <option value="text">Text</option>
                            <option value="yes_no">Yes/No</option>
                        </select>
                    </div>
                    <div class="form-group mb-3 options-container" style="display: none;">
                        <label>Options (comma-separated)</label>
                        <input type="text" name="questions[${questionIndex}][options]" class="form-control" placeholder="e.g., Option1,Option2,Option3">
                    </div>
                    <button type="button" class="btn btn-danger remove-question-btn">Remove Question</button>
                </div>
            </div>
        `;
        questionContainer.appendChild(questionDiv);
        console.log(`addQuestion: Question ${questionIndex} added`);
    } catch (e) {
        console.error('addQuestion: Error:', e);
        alert('Error adding question: ' + e.message);
    }
}

function removeQuestion(event) {
    console.log('removeQuestion: Called');
    try {
        if (event.target.classList.contains('remove-question-btn')) {
            event.target.closest('.question-item').remove();
            document.querySelectorAll('.question-item').forEach((item, index) => {
                item.querySelector('input[name*="[text]"]').name = `questions[${index}][text]`;
                item.querySelector('select[name*="[type]"]').name = `questions[${index}][type]`;
                const optionsInput = item.querySelector('input[name*="[options]"]');
                if (optionsInput) {
                    optionsInput.name = `questions[${index}][options]`;
                }
            });
            console.log('removeQuestion: Question removed and reindexed');
        }
    } catch (e) {
        console.error('removeQuestion: Error:', e);
        alert('Error removing question: ' + e.message);
    }
}

function toggleOptionsField(event) {
    console.log('toggleOptionsField: Called');
    try {
        if (event.target.classList.contains('question-type')) {
            const optionsContainer = event.target.closest('.card-body').querySelector('.options-container');
            const type = event.target.value;
            optionsContainer.style.display = ['multiple_choice', 'single_choice', 'checkboxes', 'dropdown'].includes(type) ? 'block' : 'none';
            console.log(`toggleOptionsField: Options display set to ${optionsContainer.style.display} for type ${type}`);
        }
    } catch (e) {
        console.error('toggleOptionsField: Error:', e);
        alert('Error toggling options: ' + e.message);
    }
}

function setupEventListeners() {
    console.log('setupEventListeners: Setting up listeners');
    const addQuestionBtn = document.getElementById('add-question-btn');
    if (!addQuestionBtn) {
        console.error('setupEventListeners: add-question-btn not found');
        alert('Error: Add Question button not found.');
        return;
    }
    addQuestionBtn.addEventListener('click', () => {
        console.log('addQuestionBtn: Clicked');
        addQuestion();
    });
    const questionContainer = document.getElementById('questions-container');
    if (questionContainer) {
        questionContainer.addEventListener('click', removeQuestion);
        questionContainer.addEventListener('change', toggleOptionsField);
    }
    console.log('setupEventListeners: Listeners set');
}

// Run setup after DOM is loaded
console.log('form_create.js: Waiting for DOMContentLoaded');
document.addEventListener('DOMContentLoaded', () => {
    console.log('form_create.js: DOMContentLoaded fired');
    setupEventListeners();
    addQuestion(); // Add initial question
});