/* ==========================================
   BGNU Exam Lockdown - Fullscreen & Security
   Separate file for exam lockdown functionality
   ========================================== */

// ==================== FULLSCREEN LOCKDOWN ====================

/**
 * Request browser fullscreen mode using HTML5 Fullscreen API
 * This works within WebView2 without crashing like Flutter's window_manager
 */
function enterExamFullscreen() {
    const elem = document.documentElement;

    try {
        if (elem.requestFullscreen) {
            elem.requestFullscreen().then(() => {
                console.log('[BGNU Lockdown] Fullscreen activated via requestFullscreen');
            }).catch(err => {
                console.warn('[BGNU Lockdown] Fullscreen request failed:', err);
            });
        } else if (elem.webkitRequestFullscreen) { /* Safari */
            elem.webkitRequestFullscreen();
            console.log('[BGNU Lockdown] Fullscreen activated via webkitRequestFullscreen');
        } else if (elem.msRequestFullscreen) { /* IE11 */
            elem.msRequestFullscreen();
            console.log('[BGNU Lockdown] Fullscreen activated via msRequestFullscreen');
        } else {
            console.warn('[BGNU Lockdown] Fullscreen API not supported');
        }
    } catch (e) {
        console.error('[BGNU Lockdown] Fullscreen error:', e);
    }
}

/**
 * Exit fullscreen mode
 */
function exitExamFullscreen() {
    try {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
        console.log('[BGNU Lockdown] Fullscreen exited');
    } catch (e) {
        console.error('[BGNU Lockdown] Exit fullscreen error:', e);
    }
}

/**
 * Check if currently in fullscreen
 */
function isInFullscreen() {
    return !!(document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.msFullscreenElement);
}

/**
 * Monitor fullscreen changes - re-enter if user tries to escape
 */
function setupFullscreenMonitor() {
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
    document.addEventListener('msfullscreenchange', handleFullscreenChange);
}

function handleFullscreenChange() {
    // Only enforce during exam
    if (typeof examState !== 'undefined' && examState.examStarted && !examState.isTerminated) {
        if (!isInFullscreen()) {
            console.log('[BGNU Lockdown] User exited fullscreen - re-entering...');
            // Small delay then re-enter fullscreen
            setTimeout(() => {
                enterExamFullscreen();
            }, 100);
        }
    }
}

// ==================== KEYBOARD LOCKDOWN ====================

/**
 * Block F11 (toggle fullscreen) and Escape during exam
 */
function blockFullscreenEscape(e) {
    if (typeof examState !== 'undefined' && examState.examStarted && !examState.isTerminated) {
        if (e.key === 'F11' || e.key === 'Escape') {
            e.preventDefault();
            e.stopPropagation();
            console.log('[BGNU Lockdown] Blocked key:', e.key);
            return false;
        }
    }
}

// ==================== INITIALIZATION ====================

/**
 * Initialize lockdown when exam starts
 * Call this from exam.js when exam actually begins
 */
function initExamLockdown() {
    console.log('[BGNU Lockdown] Initializing exam lockdown...');

    // Setup fullscreen monitor
    setupFullscreenMonitor();

    // Add keyboard blocker for F11/Escape
    document.addEventListener('keydown', blockFullscreenEscape, true);

    // Enter fullscreen
    enterExamFullscreen();

    console.log('[BGNU Lockdown] Lockdown initialized');
}

/**
 * Cleanup lockdown when exam ends
 */
function cleanupExamLockdown() {
    console.log('[BGNU Lockdown] Cleaning up lockdown...');

    // Remove event listeners
    document.removeEventListener('keydown', blockFullscreenEscape, true);
    document.removeEventListener('fullscreenchange', handleFullscreenChange);
    document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
    document.removeEventListener('msfullscreenchange', handleFullscreenChange);

    // Exit fullscreen
    exitExamFullscreen();

    console.log('[BGNU Lockdown] Lockdown cleaned up');
}

// Export functions for use by exam.js
window.ExamLockdown = {
    init: initExamLockdown,
    cleanup: cleanupExamLockdown,
    enterFullscreen: enterExamFullscreen,
    exitFullscreen: exitExamFullscreen,
    isFullscreen: isInFullscreen
};

console.log('[BGNU Lockdown] Lockdown module loaded');
