// /**
//  * mkdocs-superquiz - Page de déblocage enseignant
//  */

// // Décoder les données du QR code
// const urlParams = new URLSearchParams(window.location.search);
// const encodedData = urlParams.get('data');

// /**
//  * Translation helper function with dot notation support
//  * Example: t('ui.unlock_title', 'Unlock Correction')
//  */
// function t(key, fallback = '') {
//     const keys = key.split('.');
//     let value = window.QUIZ_CONFIG?.i18n;
    
//     for (const k of keys) {
//         if (value && typeof value === 'object') {
//             value = value[k];
//         } else {
//             return fallback || key;
//         }
//     }
    
//     return value || fallback || key;
// }

// if (!encodedData) {
//     document.body.innerHTML = `<div style="text-align:center;padding:2rem;"><h1>❌ ${t('ui.error_no_data', 'Error')}</h1><p>${t('ui.error_no_data', 'Unlock data missing')}</p></div>`;
// } else {
//     initUnlockPage();
// }

// /**
//  * Initialise la page de déblocage
//  */
// function initUnlockPage() {
//     try {
//         console.log('🔍 Initializing unlock page...');
        
//         // Décoder base64 vers bytes (support UTF-8)
//         const binaryString = atob(encodedData);
//         const bytes = new Uint8Array(binaryString.length);
//         for (let i = 0; i < binaryString.length; i++) {
//             bytes[i] = binaryString.charCodeAt(i);
//         }
        
//         // Décoder UTF-8 vers string
//         const jsonString = new TextDecoder().decode(bytes);
//         console.log('📝 JSON decoded:', jsonString);
        
//         // Parser JSON
//         const unlockData = JSON.parse(jsonString);
//         console.log('✅ Data parsed:', unlockData);
        
//         // Afficher les informations
//         displayUnlockInfo(unlockData);
        
//         // Gérer le formulaire
//         const form = document.getElementById('teacher-form');
//         if (form) {
//             form.addEventListener('submit', async (e) => {
//                 e.preventDefault();
//                 console.log('📝 Form submitted');
//                 await handleTeacherSubmit(unlockData);
//             });
//         }
        
//     } catch (e) {
//         console.error('❌ Erreur de décodage:', e);
//         showError(t('ui.error_decoding', 'Error decoding data') + ': ' + e.message);
//     }
// }

// /**
//  * Affiche les informations de déblocage
//  */
// function displayUnlockInfo(data) {
//     console.log('📋 Displaying unlock info');
//     console.log('📋 Unlock data received:', data);  // ✅ ADD DEBUG
    
//     // Type de déblocage
//     const typeElement = document.getElementById('unlock-type');
//     if (typeElement) {
//         if (data.type === 'page') {
//             typeElement.textContent = t('ui.unlock_type_page', 'Entire page');
//         } else if (data.type === 'exercise') {
//             typeElement.textContent = t('ui.unlock_type_exercise', 'Exercise only');
//         } else if (data.type === 'question') {
//             typeElement.textContent = t('ui.unlock_type_question', 'Question only');
//         }
//         console.log('✅ Type set to:', typeElement.textContent);  // ✅ ADD DEBUG
//     }
    
//     // Titre de la page
//     const pageTitleElement = document.getElementById('page-title');
//     if (pageTitleElement && data.page_title) {
//         pageTitleElement.textContent = data.page_title;
//         console.log('✅ Page title set to:', data.page_title);  // ✅ ADD DEBUG
//     }
    
//     // Exercice (si applicable)
//     if (data.type === 'exercise' || data.type === 'question') {
//         const exerciseInfo = document.getElementById('exercise-info');
//         const exerciseTitle = document.getElementById('exercise-title');
        
//         if (exerciseInfo && exerciseTitle) {
//             exerciseInfo.style.display = 'block';
//             exerciseTitle.textContent = data.exercise_title || data.exercise_id;
//             console.log('✅ Exercise title set to:', exerciseTitle.textContent);  // ✅ ADD DEBUG
//         }
//     }
    
//     // Question (si applicable)
//     if (data.type === 'question') {
//         const questionInfo = document.getElementById('question-info');
//         const questionText = document.getElementById('question-text');
        
//         if (questionInfo && questionText) {
//             questionInfo.style.display = 'block';
//             questionText.textContent = data.question_text || `Question ${data.question_id}`;
//             console.log('✅ Question text set to:', questionText.textContent);  // ✅ ADD DEBUG
//         }
//     }
// }


// /**
//  * Gère la soumission du formulaire enseignant
//  */
// async function handleTeacherSubmit(unlockData) {
//     console.log('🔑 Handling teacher submit');
    
//     const masterCode = document.getElementById('teacher-master-code').value;
    
//     if (!masterCode) {
//         showError(t('ui.teacher_code_label', 'Please enter your teacher code'));
//         return;
//     }
    
//     try {
//         // Hasher le code saisi
//         const masterHash = await sha256(masterCode);
//         console.log('🔍 Master hash computed');
        
//         // ✅ FIX: Use QUIZ_CONFIG instead of TEACHER_CODE_HASH
//         const expectedHash = window.QUIZ_CONFIG?.teacher_code_hash || '';
//         console.log('🔍 Expected hash:', expectedHash);
        
//         if (masterHash !== expectedHash) {
//             showError('❌ ' + t('ui.error_teacher_code', 'Incorrect teacher code'));
//             return;
//         }
        
//         console.log('✅ Teacher code verified');
        
//         // Générer le code de déblocage
//         const unlockCode = await generateUnlockCode(masterHash, unlockData);
//         console.log('🔓 Unlock code generated:', unlockCode);
        
//         // Afficher le code
//         displayUnlockCode(unlockCode);
        
//     } catch (error) {
//         console.error('❌ Error:', error);
//         showError(t('ui.error_decoding', 'Error') + ': ' + error.message);
//     }
// }


// /**
//  * Génère le code de déblocage
//  */
// async function generateUnlockCode(teacherCodeHash, data) {
//     // Construire le payload
//     let payload = teacherCodeHash + data.page_id + data.type;
    
//     console.log('🔍 TEACHER - Generating unlock code:');
//     console.log('   Teacher hash:', teacherCodeHash);
//     console.log('   Page ID:', data.page_id);
//     console.log('   Type:', data.type);
    
//     if (data.type === 'exercise' || data.type === 'question') {
//         payload += data.exercise_id || '';
//         console.log('   Exercise ID:', data.exercise_id);
//     }
    
//     if (data.type === 'question') {
//         payload += data.question_id || '';
//         console.log('   Question ID:', data.question_id);
//     }
    
//     console.log('   Full payload:', payload);
    
//     // Hasher
//     const hash = await sha256(payload);
//     console.log('   Full hash:', hash);
    
//     // Retourner les 8 premiers caractères en majuscules
//     const code = hash.substring(0, 8).toUpperCase();
//     console.log('   Final code:', code);
    
//     return code;
// }

// /**
//  * Affiche le code de déblocage généré
//  */
// function displayUnlockCode(code) {
//     const codeSection = document.getElementById('generated-code-section');
//     const codeValue = document.getElementById('unlock-code-value');
//     const form = document.getElementById('teacher-form');
    
//     if (codeValue) {
//         codeValue.textContent = code;
//     }
    
//     if (codeSection) {
//         codeSection.style.display = 'block';
//     }
    
//     if (form) {
//         form.style.display = 'none';
//     }
// }

// /**
//  * Copie le code dans le presse-papier
//  */
// function copyCode(event) {
//     const code = document.getElementById('unlock-code-value').textContent;
    
//     navigator.clipboard.writeText(code).then(() => {
//         const btn = event ? event.target : document.querySelector('button[onclick*="copyCode"]');
//         if (btn) {
//             const originalText = btn.textContent;
//             btn.textContent = '✓ ' + t('ui.code_copied', 'Copied!');
            
//             setTimeout(() => {
//                 btn.textContent = originalText;
//             }, 2000);
//         }
//     }).catch(err => {
//         console.error('Erreur de copie:', err);
//         alert(t('ui.copy_code', 'Code') + ' : ' + code);
//     });
// }

// /**
//  * Affiche un message d'erreur
//  */
// function showError(message) {
//     const errorDiv = document.getElementById('error-message');
//     if (!errorDiv) {
//         console.error(message);
//         alert(message);
//         return;
//     }
    
//     errorDiv.textContent = message;
//     errorDiv.style.display = 'block';
    
//     setTimeout(() => {
//         errorDiv.style.display = 'none';
//     }, 5000);
// }

// /**
//  * Fonction SHA256
//  */
// async function sha256(str) {
//     const buffer = new TextEncoder().encode(str);
//     const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
//     const hashArray = Array.from(new Uint8Array(hashBuffer));
//     return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
// }

/**
 * mkdocs-superquiz - Page de déblocage enseignant
 * Ce script ne s'exécute QUE sur la page quiz-unlock.html
 */

/**
 * Translation helper function with dot notation support
 */
function t(key, fallback = '') {
    const keys = key.split('.');
    let value = window.QUIZ_CONFIG?.i18n;
    
    for (const k of keys) {
        if (value && typeof value === 'object') {
            value = value[k];
        } else {
            return fallback || key;
        }
    }
    
    return value || fallback || key;
}

// ← GUARD : ne s'exécute que sur la page quiz-unlock.html
if (!window.location.pathname.includes('quiz-unlock')) {
    // Pas sur la page de déblocage → on ne fait rien
} else {
    const urlParams = new URLSearchParams(window.location.search);
    const encodedData = urlParams.get('data');

    if (!encodedData) {
        document.body.innerHTML = `<div style="text-align:center;padding:2rem;"><h1>❌ ${t('ui.error_no_data', 'Error')}</h1><p>${t('ui.error_no_data', 'Unlock data missing')}</p></div>`;
    } else {
        initUnlockPage();
    }
}

/**
 * Initialise la page de déblocage
 */
function initUnlockPage() {
    const urlParams = new URLSearchParams(window.location.search);
    const encodedData = urlParams.get('data');

    try {
        console.log('🔍 Initializing unlock page...');
        
        const binaryString = atob(encodedData);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        
        const jsonString = new TextDecoder().decode(bytes);
        console.log('📝 JSON decoded:', jsonString);
        
        const unlockData = JSON.parse(jsonString);
        console.log('✅ Data parsed:', unlockData);
        
        displayUnlockInfo(unlockData);
        
        const form = document.getElementById('teacher-form');
        if (form) {
            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                console.log('📝 Form submitted');
                await handleTeacherSubmit(unlockData);
            });
        }
        
    } catch (e) {
        console.error('❌ Erreur de décodage:', e);
        showError(t('ui.error_decoding', 'Error decoding data') + ': ' + e.message);
    }
}

/**
 * Affiche les informations de déblocage
 */
function displayUnlockInfo(data) {
    console.log('📋 Displaying unlock info');
    console.log('📋 Unlock data received:', data);
    
    const typeElement = document.getElementById('unlock-type');
    if (typeElement) {
        if (data.type === 'page') {
            typeElement.textContent = t('ui.unlock_type_page', 'Entire page');
        } else if (data.type === 'exercise') {
            typeElement.textContent = t('ui.unlock_type_exercise', 'Exercise only');
        } else if (data.type === 'question') {
            typeElement.textContent = t('ui.unlock_type_question', 'Question only');
        }
        console.log('✅ Type set to:', typeElement.textContent);
    }
    
    const pageTitleElement = document.getElementById('page-title');
    if (pageTitleElement && data.page_title) {
        pageTitleElement.textContent = data.page_title;
        console.log('✅ Page title set to:', data.page_title);
    }
    
    if (data.type === 'exercise' || data.type === 'question') {
        const exerciseInfo = document.getElementById('exercise-info');
        const exerciseTitle = document.getElementById('exercise-title');
        
        if (exerciseInfo && exerciseTitle) {
            exerciseInfo.style.display = 'block';
            exerciseTitle.textContent = data.exercise_title || data.exercise_id;
            console.log('✅ Exercise title set to:', exerciseTitle.textContent);
        }
    }
    
    if (data.type === 'question') {
        const questionInfo = document.getElementById('question-info');
        const questionText = document.getElementById('question-text');
        
        if (questionInfo && questionText) {
            questionInfo.style.display = 'block';
            questionText.textContent = data.question_text || `Question ${data.question_id}`;
            console.log('✅ Question text set to:', questionText.textContent);
        }
    }
}

/**
 * Gère la soumission du formulaire enseignant
 */
async function handleTeacherSubmit(unlockData) {
    console.log('🔑 Handling teacher submit');
    
    const masterCode = document.getElementById('teacher-master-code').value;
    
    if (!masterCode) {
        showError(t('ui.teacher_code_label', 'Please enter your teacher code'));
        return;
    }
    
    try {
        const masterHash = await sha256(masterCode);
        console.log('🔍 Master hash computed');
        
        const expectedHash = window.QUIZ_CONFIG?.teacher_code_hash || '';
        console.log('🔍 Expected hash:', expectedHash);
        
        if (masterHash !== expectedHash) {
            showError('❌ ' + t('ui.error_teacher_code', 'Incorrect teacher code'));
            return;
        }
        
        console.log('✅ Teacher code verified');
        
        const unlockCode = await generateUnlockCode(masterHash, unlockData);
        console.log('🔓 Unlock code generated:', unlockCode);
        
        displayUnlockCode(unlockCode);
        
    } catch (error) {
        console.error('❌ Error:', error);
        showError(t('ui.error_decoding', 'Error') + ': ' + error.message);
    }
}

/**
 * Génère le code de déblocage
 */
async function generateUnlockCode(teacherCodeHash, data) {
    let payload = teacherCodeHash + data.page_id + data.type;
    
    console.log('🔍 TEACHER - Generating unlock code:');
    console.log('   Teacher hash:', teacherCodeHash);
    console.log('   Page ID:', data.page_id);
    console.log('   Type:', data.type);
    
    if (data.type === 'exercise' || data.type === 'question') {
        payload += data.exercise_id || '';
        console.log('   Exercise ID:', data.exercise_id);
    }
    
    if (data.type === 'question') {
        payload += data.question_id || '';
        console.log('   Question ID:', data.question_id);
    }
    
    console.log('   Full payload:', payload);
    
    const hash = await sha256(payload);
    console.log('   Full hash:', hash);
    
    const code = hash.substring(0, 8).toUpperCase();
    console.log('   Final code:', code);
    
    return code;
}

/**
 * Affiche le code de déblocage généré
 */
function displayUnlockCode(code) {
    const codeSection = document.getElementById('generated-code-section');
    const codeValue = document.getElementById('unlock-code-value');
    const form = document.getElementById('teacher-form');
    
    if (codeValue) codeValue.textContent = code;
    if (codeSection) codeSection.style.display = 'block';
    if (form) form.style.display = 'none';
}

/**
 * Copie le code dans le presse-papier
 */
function copyCode(event) {
    const code = document.getElementById('unlock-code-value').textContent;
    
    navigator.clipboard.writeText(code).then(() => {
        const btn = event ? event.target : document.querySelector('button[onclick*="copyCode"]');
        if (btn) {
            const originalText = btn.textContent;
            btn.textContent = '✓ ' + t('ui.code_copied', 'Copied!');
            setTimeout(() => { btn.textContent = originalText; }, 2000);
        }
    }).catch(err => {
        console.error('Erreur de copie:', err);
        alert(t('ui.copy_code', 'Code') + ' : ' + code);
    });
}

/**
 * Affiche un message d'erreur
 */
function showError(message) {
    const errorDiv = document.getElementById('error-message');
    if (!errorDiv) {
        console.error(message);
        alert(message);
        return;
    }
    
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
    
    setTimeout(() => { errorDiv.style.display = 'none'; }, 5000);
}

/**
 * Fonction SHA256
 */
async function sha256(str) {
    const buffer = new TextEncoder().encode(str);
    const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}