{% extends "base.html" %}

{% block content %}
    <h1>{{ assessment.name }}</h1>
    <p class="lead">{{ assessment.description }}</p>

    <form method="POST" action="{{ url_for('main.submit_assessment', token=assignment.unique_token) }}" id="assessmentForm">
        {# Conditionally render tabbed view or simple list view #}
        {% if assessment.show_domain_wise %}
        <!-- Navigation Tabs for Domains -->
        <ul class="nav nav-tabs" id="domainTabs" role="tablist">
            {% for domain, questions_in_domain in questions_by_domain %}
                <li class="nav-item">
                    {# Use a filter to create a valid HTML ID from the domain name #}
                    <a class="nav-link {% if loop.first %}active{% endif %}" id="{{ domain|replace(' ', '-')|replace('/', '-') }}-tab" data-toggle="tab" href="#{{ domain|replace(' ', '-')|replace('/', '-') }}" role="tab" aria-controls="{{ domain|replace(' ', '-')|replace('/', '-') }}" aria-selected="{{ 'true' if loop.first else 'false' }}">{{ domain }}</a>
                </li>
            {% endfor %}
        </ul>

        <!-- Tab Content Panes -->
        <div class="tab-content" id="domainTabsContent">
            {% for domain, questions_in_domain in questions_by_domain %}
                <div class="tab-pane fade {% if loop.first %}show active{% endif %}" id="{{ domain|replace(' ', '-')|replace('/', '-') }}" role="tabpanel" aria-labelledby="{{ domain|replace(' ', '-')|replace('/', '-') }}-tab">
                    <div class="pt-3"> {# Add some padding to the top of the tab content #}
                        {% for question in questions_in_domain %}
                            <div class="card mb-3" data-domain="{{ domain }}">
                                <div class="card-body">
                                    <h5 class="card-title">{{ loop.index }}. {{ question.text }}</h5>
                                    {% if question.question_type == 'blank' %}
                                        <div class="form-group">
                                            <input type="text" class="form-control" id="blank_text_{{ question.id }}" name="blank_text_{{ question.id }}" placeholder="Type your answer or use dictation" required>
                                            <input type="hidden" id="blank_audio_{{ question.id }}" name="blank_audio_{{ question.id }}">
                                        </div>
                                        <div class="btn-group mb-2" role="group">
                                            <button type="button" class="btn btn-outline-secondary btn-sm" data-qid="{{ question.id }}" onclick="startDictationBtn(this)">Start Dictation</button>
                                            <button type="button" class="btn btn-outline-secondary btn-sm" data-qid="{{ question.id }}" onclick="stopDictationBtn(this)">Stop Dictation</button>
                                        </div>
                                        <div class="btn-group mb-2 ml-2" role="group">
                                            <button type="button" class="btn btn-outline-primary btn-sm" data-qid="{{ question.id }}" onclick="startRecordingBtn(this)">Start Recording</button>
                                            <button type="button" class="btn btn-outline-danger btn-sm" data-qid="{{ question.id }}" onclick="stopRecordingBtn(this)">Stop Recording</button>
                                        </div>
                                        <div>
                                            <audio id="audio_preview_{{ question.id }}" controls style="display:none"></audio>
                                        </div>
                                    {% else %}
                                        {% for choice in question.choices_unique %}
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="question_{{ question.id }}" id="choice_{{ choice.id }}" value="{{ choice.id }}" required>
                                                <label class="form-check-label" for="choice_{{ choice.id }}">
                                                    {{ choice.text }}
                                                </label>
                                            </div>
                                        {% endfor %}
                                    {% endif %}
                                </div>
                            </div>
                        {% endfor %}

                        {% if loop.last and 'cbcl' in assessment.name.lower() %}
                            <div class="card mb-3">
                                <div class="card-body">
                                    <h5 class="card-title">Therapist Notes</h5>
                                    <div class="form-group">
                                        <textarea class="form-control" id="therapist_notes" name="therapist_notes" rows="3" placeholder="Enter any notes here..."></textarea>
                                    </div>
                                </div>
                            </div>
                        {% endif %}

                        <!-- Tab Navigation Buttons -->
                        <div class="mt-4 d-flex justify-content-between">
                            {% if not loop.first %}
                                <button type="button" class="btn btn-secondary" data-target="{{ loop.previtem[0]|replace(' ', '-')|replace('/', '-') }}-tab" onclick="navigateToTab(this.dataset.target)">Previous</button>
                            {% else %}
                                <!-- This empty span ensures the 'Next' button stays on the right for the first tab -->
                                <span></span>
                            {% endif %}

                            {% if not loop.last %}
                                <button type="button" class="btn btn-primary" data-target="{{ loop.nextitem[0]|replace(' ', '-')|replace('/', '-') }}-tab" onclick="navigateToTab(this.dataset.target)">Next</button>
                            {% else %}
                                <button type="button" class="btn btn-success" onclick="confirmSubmission(event)">Submit Assessment</button>
                            {% endif %}
                        </div>
                    </div>
                </div>
            {% endfor %}
        {% else %}
            <!-- Simple List View for non-domain-wise assessments -->
            {% for domain, questions_in_domain in questions_by_domain %}
                {% for question in questions_in_domain %}
                    <div class="card mb-3" data-domain="{{ domain }}">
                        <div class="card-body">
                            <h5 class="card-title">{{ loop.index }}. {{ question.text }}</h5>
                            {% if question.domain %}
                                <p class="card-subtitle mb-2 text-muted">Domain: {{ question.domain }}</p>
                            {% endif %}
                            {% if question.question_type == 'blank' %}
                                <div class="form-group">
                                    <input type="text" class="form-control" id="blank_text_{{ question.id }}" name="blank_text_{{ question.id }}" placeholder="Type your answer or use dictation" required>
                                    <input type="hidden" id="blank_audio_{{ question.id }}" name="blank_audio_{{ question.id }}">
                                </div>
                                <div class="btn-group mb-2" role="group">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" data-qid="{{ question.id }}" onclick="startDictationBtn(this)">Start Dictation</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" data-qid="{{ question.id }}" onclick="stopDictationBtn(this)">Stop Dictation</button>
                                </div>
                                <div class="btn-group mb-2 ml-2" role="group">
                                    <button type="button" class="btn btn-outline-primary btn-sm" data-qid="{{ question.id }}" onclick="startRecordingBtn(this)">Start Recording</button>
                                    <button type="button" class="btn btn-outline-danger btn-sm" data-qid="{{ question.id }}" onclick="stopRecordingBtn(this)">Stop Recording</button>
                                </div>
                                <div>
                                    <audio id="audio_preview_{{ question.id }}" controls style="display:none"></audio>
                                </div>
                            {% else %}
                                {% for choice in question.choices_unique %}
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="question_{{ question.id }}" id="choice_{{ choice.id }}" value="{{ choice.id }}" required>
                                        <label class="form-check-label" for="choice_{{ choice.id }}">
                                            {{ choice.text }}
                                        </label>
                                    </div>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </div>
                {% endfor %}
            {% endfor %}
            
            {% if 'cbcl' in assessment.name.lower() %}
            <div class="card mb-3">
                <div class="card-body">
                    <h5 class="card-title">Therapist Notes</h5>
                    <div class="form-group">
                        <textarea class="form-control" id="therapist_notes" name="therapist_notes" rows="3" placeholder="Enter any notes here..."></textarea>
                    </div>
                </div>
            </div>
            {% endif %}

            <button type="submit" class="btn btn-success mt-3">Submit Assessment</button>
        {% endif %}
        </div>
    </form>
{% endblock %}

{% block scripts %}
<script>
    const isISAA = "{{ assessment.name.lower().strip() }}" === "isaa";
    const assessmentName = "{{ assessment.name.lower() }}";
    const isDDSTorVSMS = assessmentName.includes("ddst") || assessmentName.includes("vsms") || assessmentName.includes("social maturity");
    const token = "{{ assignment.unique_token }}";
    const recognitionMap = {};
    const recorderMap = {};
    const chunksMap = {};

    function navigateToTab(tabId) {
        $(`#${tabId}`).tab('show');
    }

    function startDictation(qid) {
        const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
        if (!SR) {
            alert('Speech recognition not supported in this browser.');
            return;
        }
        const rec = new SR();
        rec.lang = 'en-US';
        rec.continuous = true;
        rec.interimResults = true;
        rec.onresult = (event) => {
            let text = '';
            for (let i = event.resultIndex; i < event.results.length; i++) {
                text += event.results[i][0].transcript;
            }
            const input = document.getElementById(`blank_text_${qid}`);
            if (input) {
                input.value = text;
            }
        };
        rec.onerror = () => {};
        rec.onend = () => {};
        rec.start();
        recognitionMap[qid] = rec;
    }
    function stopDictation(qid) {
        const rec = recognitionMap[qid];
        if (rec) {
            try { rec.stop(); } catch(e) {}
            delete recognitionMap[qid];
        }
    }
    async function startRecording(qid) {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            const rec = new MediaRecorder(stream);
            const chunks = [];
            rec.ondataavailable = e => { if (e.data.size > 0) chunks.push(e.data); };
            rec.onstop = async () => {
                const blob = new Blob(chunks, { type: 'audio/webm' });
                const fd = new FormData();
                fd.append('audio', blob, `recording_${qid}.webm`);
                fd.append('token', token);
                fd.append('question_id', qid);
                const resp = await fetch('{{ url_for("main.upload_audio") }}', { method: 'POST', body: fd });
                const data = await resp.json();
                if (data.url) {
                    const audioEl = document.getElementById(`audio_preview_${qid}`);
                    const hidden = document.getElementById(`blank_audio_${qid}`);
                    if (audioEl) {
                        audioEl.src = data.url;
                        audioEl.style.display = '';
                    }
                    if (hidden) {
                        hidden.value = data.relative;
                    }
                } else {
                    alert('Failed to upload audio.');
                }
            };
            rec.start();
            recorderMap[qid] = rec;
            chunksMap[qid] = chunks;
        } catch (e) {
            alert('Microphone access denied or not available.');
        }
    }
    function stopRecording(qid) {
        const rec = recorderMap[qid];
        if (rec) {
            try { rec.stop(); } catch(e) {}
            delete recorderMap[qid];
        }
    }
    function startDictationBtn(el) {
        const qid = parseInt(el.dataset.qid, 10);
        startDictation(qid);
    }
    function stopDictationBtn(el) {
        const qid = parseInt(el.dataset.qid, 10);
        stopDictation(qid);
    }
    function startRecordingBtn(el) {
        const qid = parseInt(el.dataset.qid, 10);
        startRecording(qid);
    }
    function stopRecordingBtn(el) {
        const qid = parseInt(el.dataset.qid, 10);
        stopRecording(qid);
    }
    function confirmSubmission(event) {
        event.preventDefault(); 
        const form = document.getElementById('assessmentForm');
        
        if (isISAA) {
            const questions = document.querySelectorAll('.card');
            let allAnswered = true;
            let firstUnansweredTab = null;

            document.querySelectorAll('.tab-pane').forEach(tabPane => {
                const questionsInTab = tabPane.querySelectorAll('.card');
                let answeredInTab = 0;
                questionsInTab.forEach(questionCard => {
                    const radios = questionCard.querySelectorAll('input[type="radio"]');
                    let isAnswered = false;
                    radios.forEach(radio => {
                        if (radio.checked) {
                            isAnswered = true;
                        }
                    });
                    if (isAnswered) {
                        answeredInTab++;
                    }
                });

                if (answeredInTab < questionsInTab.length) {
                    allAnswered = false;
                    if (!firstUnansweredTab) {
                        firstUnansweredTab = tabPane.id;
                    }
                }
            });

            if (!allAnswered) {
                alert('Please answer all questions in every domain before submitting.');
                const tabId = firstUnansweredTab.replace(/ /g, '-').replace(/\//g, '-') + '-tab';
                $(`#${tabId}`).tab('show');
                return;
            }
        }

        if (isDDSTorVSMS) {
            const domainCounts = {};
            // Select only cards that have data-domain attribute (questions)
            const cards = document.querySelectorAll('.card[data-domain]');
            
            cards.forEach(card => {
                const domain = card.getAttribute('data-domain');
                if (!domainCounts[domain]) {
                    domainCounts[domain] = { answered: 0, total: 0 };
                }
                domainCounts[domain].total++;
                
                const radios = card.querySelectorAll('input[type="radio"]');
                let isAnswered = false;
                radios.forEach(radio => {
                    if (radio.checked) {
                        isAnswered = true;
                    }
                });
                if (isAnswered) {
                    domainCounts[domain].answered++;
                }
            });

            const minQuestions = 3;
            let valid = true;
            let errorMsg = "";
            let firstInvalidDomain = null;

            for (const domain in domainCounts) {
                if (domainCounts[domain].answered < minQuestions) {
                    valid = false;
                    errorMsg += `Domain "${domain}" has only ${domainCounts[domain].answered} answered questions. Minimum required is ${minQuestions}.\n`;
                    if (!firstInvalidDomain) firstInvalidDomain = domain;
                }
            }

            if (!valid) {
                alert(errorMsg + "\nPlease answer more questions before submitting.");
                
                if (firstInvalidDomain) {
                     const allCards = document.querySelectorAll('.card[data-domain]');
                     let targetCard = null;
                     for(let i=0; i<allCards.length; i++) {
                         if(allCards[i].getAttribute('data-domain') === firstInvalidDomain) {
                             targetCard = allCards[i];
                             break;
                         }
                     }
                     
                     if (targetCard) {
                         const tabPane = targetCard.closest('.tab-pane');
                         if (tabPane) {
                             const tabId = tabPane.id;
                             $(`#${tabId}-tab`).tab('show');
                         }
                     }
                }
                return;
            }
        }

        const blankInputs = document.querySelectorAll('input[id^="blank_text_"]');
        if (blankInputs.length > 0) {
            for (const input of blankInputs) {
                if (!input.value || input.value.trim() === '') {
                    alert('Please fill all blank answers before submitting.');
                    input.focus();
                    return;
                }
            }
        }

        const userConfirmed = confirm("Are you sure you want to submit the assessment? You can review your answers before confirming.");
        if (userConfirmed) {
            form.submit();
        }
    }
</script>
{% endblock %}