/* CIX Orbit Academy - Main JavaScript */
document.addEventListener('DOMContentLoaded', function() {
    // Sidebar toggle
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebar = document.getElementById('sidebar');
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() { sidebar.classList.toggle('show'); });
    }
    
    // Flash messages auto-dismiss
    document.querySelectorAll('.alert-cix').forEach(function(alert) {
        setTimeout(function() { alert.style.opacity = '0'; setTimeout(function() { alert.remove(); }, 300); }, 5000);
    });
    
    // PWA install prompt
    let deferredPrompt;
    window.addEventListener('beforeinstallprompt', function(e) {
        e.preventDefault();
        deferredPrompt = e;
        const installBtn = document.getElementById('pwaInstallBtn');
        if (installBtn) { installBtn.style.display = 'flex'; installBtn.addEventListener('click', function() { deferredPrompt.prompt(); deferredPrompt.userChoice.then(function(choice) { deferredPrompt = null; installBtn.style.display = 'none'; }); }); }
    });
    
    // Service worker registration
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/public/assets/js/service-worker.js').catch(function() {});
    }
    
    // Confirm delete actions
    document.querySelectorAll('[data-confirm]').forEach(function(el) {
        el.addEventListener('click', function(e) {
            if (!confirm(this.dataset.confirm)) { e.preventDefault(); }
        });
    });
});

/* CBT Test Engine */
var CBT = {
    timer: null,
    timeRemaining: 0,
    tabSwitches: 0,
    attemptId: 0,
    
    startTest: function(attemptId, durationMinutes) {
        this.attemptId = attemptId;
        this.timeRemaining = durationMinutes * 60;
        this.tabSwitches = 0;
        this.startTimer();
        this.startAntiCheat();
    },
    
    startTimer: function() {
        var self = this;
        var timerEl = document.getElementById('testTimer');
        this.timer = setInterval(function() {
            self.timeRemaining--;
            var mins = Math.floor(self.timeRemaining / 60);
            var secs = self.timeRemaining % 60;
            if (timerEl) {
                timerEl.textContent = String(mins).padStart(2, '0') + ':' + String(secs).padStart(2, '0');
                if (self.timeRemaining <= 300) timerEl.classList.add('warning');
            }
            if (self.timeRemaining <= 0) {
                clearInterval(self.timer);
                self.submitTest(true);
            }
        }, 1000);
    },
    
    startAntiCheat: function() {
        var self = this;
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                self.tabSwitches++;
                fetch('/api/tab-switch/' + self.attemptId, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': self.csrfToken() } });
                var warning = document.getElementById('tabWarning');
                if (warning) warning.style.display = 'block';
            }
        });
        if (document.fullscreenEnabled) {
            document.documentElement.requestFullscreen().catch(function() {});
        }
    },
    
    loadQuestions: function() {
        var self = this;
        fetch('/api/test-questions/' + this.attemptId)
            .then(function(r) { return r.json(); })
            .then(function(data) {
                var container = document.getElementById('questionsContainer');
                if (!container || !data.questions) return;
                var html = '';
                data.questions.forEach(function(q, i) {
                    html += '<div class="question-card"><div class="question-number">Question ' + (i + 1) + ' of ' + data.questions.length + '</div><p class="mb-2">' + q.question_text + '</p>';
                    if (q.question_type === 'multiple_choice' || q.question_type === 'true_false') {
                        (q.options || []).forEach(function(opt) {
                            html += '<label class="option-label"><input type="radio" name="q_' + q.id + '" value="' + opt.id + '"><span>' + opt.option_text + '</span></label>';
                        });
                    } else {
                        html += '<textarea class="form-control-cix" name="q_' + q.id + '" rows="3" placeholder="Type your answer..."></textarea>';
                    }
                    html += '</div>';
                });
                container.innerHTML = html;
            });
    },
    
    submitTest: function(autoSubmit) {
        clearInterval(this.timer);
        var self = this;
        var answers = [];
        document.querySelectorAll('[name^="q_"], [name^="answers["]').forEach(function(el) {
            var qId = el.name.indexOf('answers[') === 0 ? el.name.replace('answers[', '').replace(']', '') : el.name.replace('q_', '');
            var answer = { question_id: parseInt(qId) };
            if (el.type === 'radio') {
                if (el.checked) answer.selected_option_id = parseInt(el.value);
            } else {
                answer.answer_text = el.value;
            }
            if (answer.selected_option_id || answer.answer_text) answers.push(answer);
        });
        
        fetch('/api/submit-test', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': self.csrfToken() },
            body: JSON.stringify({ attempt_id: self.attemptId, answers: answers })
        }).then(function(r) { return r.json(); }).then(function(data) {
            if (data.success) {
                var resultEl = document.getElementById('testResult');
                if (resultEl) {
                    resultEl.innerHTML = '<div class="text-center"><h3>' + (data.passed ? 'PASSED!' : 'FAILED') + '</h3><p class="fs-1 fw-bold ' + (data.passed ? 'text-green' : 'text-orange') + '">' + data.percentage + '%</p><p>Score: ' + data.score + ' / ' + data.max_score + '</p><p>Pass Mark: ' + data.pass_mark + '%</p><a href="/student/tests" class="btn-cix btn-cix-primary mt-2">View All Tests</a></div>';
                    resultEl.style.display = 'block';
                }
                var formEl = document.getElementById('testForm');
                if (formEl) formEl.style.display = 'none';
            }
        });
    },
    
    saveProgress: function() {
        var answers = [];
        document.querySelectorAll('[name^="q_"], [name^="answers["]').forEach(function(el) {
            var qId = el.name.indexOf('answers[') === 0 ? el.name.replace('answers[', '').replace(']', '') : el.name.replace('q_', '');
            var answer = { question_id: parseInt(qId) };
            if (el.type === 'radio') { if (el.checked) answer.selected_option_id = parseInt(el.value); }
            else { answer.answer_text = el.value; }
            if (answer.selected_option_id || answer.answer_text) answers.push(answer);
        });
        fetch('/api/save-progress', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': this.csrfToken() },
            body: JSON.stringify({ attempt_id: this.attemptId, answers: answers, tab_switches: this.tabSwitches })
        });
    },

    csrfToken: function() {
        var token = document.querySelector('[name="csrf_token"]');
        return token ? token.value : '';
    }
};
