let currentUser = null;
let allTasks = [];
let allCourses = [];
let currentFolderId = null;
let folderHistory = [];
let currentEditingCourseId = null;
let selectedItemForContext = null;
let onConfirmAction = null;
let lastSelectedImg = null;

// GESTION AGENDAS
let calendarCurrentDate = new Date();
let calendarViewMode = 'month';
let calendarEventsList = [];

// POMODORO STATE & CYCLES (Déclarés une seule fois ici)
let timerSeconds = 20 * 60;
let timerInterval = null;
let isWorkSession = true; 
let totalSessionMinutesTarget = 60; 
let elapsedWorkSeconds = 0;
let currentPomodoroMessage = "Bon travail ! C'est parti.";

// CALCULATEUR DE TEMPS RESTANT
function getRemainingTimeText(dueDateStr) {
    if (!dueDateStr) return null;
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const parts = dueDateStr.split('-');
    if (parts.length !== 3) return null;
    const due = new Date(parts[0], parts[1] - 1, parts[2]);

    const diffTime = due - today;
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    if (diffDays < 0) return { text: `En retard (${Math.abs(diffDays)}j)`, color: 'bg-rose-100 text-rose-700 border-rose-200' };
    if (diffDays === 0) return { text: `Urgent : Aujourd'hui !`, color: 'bg-rose-500 text-white font-bold' };
    if (diffDays === 1) return { text: `Demain`, color: 'bg-amber-500 text-white font-bold' };
    if (diffDays <= 3) return { text: `Dans ${diffDays} jours`, color: 'bg-amber-100 text-amber-800 border-amber-200' };
    return { text: `Dans ${diffDays} jours`, color: 'bg-slate-100 text-slate-600 border-slate-200' };
}

// DÉTECTION INTELLIGENTE DES LIENS DANS LES TEXTES
function formatDescriptionText(text) {
    if (!text) return 'Aucune consigne saisie.';
    const urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, (url) => {
        return `<a href="${url}" target="_blank" class="text-brand-600 underline font-semibold hover:text-brand-700 break-all"><i class="fa-solid fa-link mr-1"></i>${url}</a>`;
    });
}

// CTRL+S
document.addEventListener('keydown', (e) => {
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        const editorTab = document.getElementById('tab-course-editor');
        const moodboardTab = document.getElementById('tab-moodboard-editor');
        if (editorTab && editorTab.classList.contains('active')) saveCourseContent();
        if (moodboardTab && moodboardTab.classList.contains('active')) saveMoodboardContent();
    }
});

// TOASTS
function showToast(message, type = 'success') {
    const container = document.getElementById('toastContainer');
    if (!container) return;
    const toast = document.createElement('div');
    const bgClass = type === 'success' ? 'bg-emerald-600 text-white' : (type === 'error' ? 'bg-rose-600 text-white' : 'bg-slate-900 text-white');
    toast.className = `px-4 py-3 rounded-2xl shadow-xl border border-white/10 text-xs font-bold flex items-center gap-2.5 transition-all duration-300 transform translate-x-5 opacity-0 ${bgClass}`;
    toast.innerHTML = `<i class="fa-solid fa-circle-info"></i> <span>${message}</span>`;
    container.appendChild(toast);
    setTimeout(() => toast.classList.remove('translate-x-5', 'opacity-0'), 10);
    setTimeout(() => { toast.classList.add('translate-x-5', 'opacity-0'); setTimeout(() => toast.remove(), 300); }, 3000);
}

// CONFIRM MODAL
function showConfirmModal(message, actionCallback) {
    document.getElementById('confirmModalText').innerText = message;
    onConfirmAction = actionCallback;
    document.getElementById('confirmModal').classList.remove('hidden');
}

function closeConfirmModal(execute = false) {
    document.getElementById('confirmModal').classList.add('hidden');
    if (execute && typeof onConfirmAction === 'function') onConfirmAction();
    onConfirmAction = null;
}

const confirmBtnAction = document.getElementById('confirmModalBtnAction');
if (confirmBtnAction) confirmBtnAction.onclick = () => closeConfirmModal(true);

// MENU CONTEXTUEL CLIC DROIT
function showContextMenu(e, item) {
    e.preventDefault();
    selectedItemForContext = item;
    const menu = document.getElementById('contextMenu');
    menu.style.left = `${e.clientX}px`;
    menu.style.top = `${e.clientY}px`;
    menu.classList.remove('hidden');
}

function hideContextMenu() { 
    const menu = document.getElementById('contextMenu');
    if (menu) menu.classList.add('hidden'); 
}

function openEditItemModal() {
    if (!selectedItemForContext) return;
    if (selectedItemForContext.type === 'task') {
        openEventDetail(selectedItemForContext.id, selectedItemForContext.title, selectedItemForContext.due_date || selectedItemForContext.completed_at, 'task', selectedItemForContext.course_id, selectedItemForContext.description);
    } else {
        document.getElementById('courseEditId').value = selectedItemForContext.id;
        document.getElementById('courseTitle').value = selectedItemForContext.title;
        document.getElementById('courseModalTitle').innerHTML = `<i class="fa-solid fa-pen-to-square text-brand-600 mr-2"></i> Modifier l'élément`;
        document.getElementById('courseTypeContainer').classList.add('hidden');
        openCourseModal(true);
    }
}

function deleteSelectedItem() {
    if (!selectedItemForContext) return;
    showConfirmModal(`Supprimer "${selectedItemForContext.title}" ?`, async () => {
        if (selectedItemForContext.type === 'task') {
            await fetch('api/tasks.php', { method: 'DELETE', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ id: selectedItemForContext.id }) });
            loadTasks();
            loadCalendar();
        } else {
            await fetch('api/courses.php', { method: 'DELETE', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ id: selectedItemForContext.id }) });
            loadCourses();
        }
        showToast("Élément supprimé", "error");
    });
}

// WYSIWYG
function execCmd(cmd, val = null) { document.execCommand(cmd, false, val); }

document.addEventListener('click', (e) => {
    if (e.target.tagName === 'IMG' && e.target.closest('#richEditor')) {
        lastSelectedImg = e.target;
        showToast("Image sélectionnée.", "info");
    }
});

function setImageAlign(align) {
    if (!lastSelectedImg) { showToast("Cliquez sur une image d'abord.", "info"); return; }
    lastSelectedImg.classList.remove('img-left', 'img-right', 'img-center');
    if (align === 'left') lastSelectedImg.classList.add('img-left');
    if (align === 'right') lastSelectedImg.classList.add('img-right');
    if (align === 'center') lastSelectedImg.classList.add('img-center');
    showToast(`Alignement : ${align}`);
}

function openTableModal() { document.getElementById('tableModal').classList.remove('hidden'); }
function closeTableModal() { document.getElementById('tableModal').classList.add('hidden'); }

function confirmInsertTable() {
    const cols = parseInt(document.getElementById('tableCols').value) || 3;
    const rows = parseInt(document.getElementById('tableRows').value) || 3;
    let headerHtml = '<tr>';
    for (let c = 1; c <= cols; c++) headerHtml += `<th>Colonne ${c}</th>`;
    headerHtml += '</tr>';
    let rowsHtml = '';
    for (let r = 1; r <= rows; r++) {
        rowsHtml += '<tr>';
        for (let c = 1; c <= cols; c++) rowsHtml += `<td>Texte</td>`;
        rowsHtml += '</tr>';
    }
    execCmd('insertHTML', `<table><thead>${headerHtml}</thead><tbody>${rowsHtml}</tbody></table><p></p>`);
    closeTableModal();
    showToast("Tableau inséré !");
}

function setCustomCourseColor(hexColor) {
    let customRadio = document.getElementById('customColorRadio');
    if (!customRadio) {
        customRadio = document.createElement('input');
        customRadio.type = 'radio'; customRadio.name = 'courseColor'; customRadio.id = 'customColorRadio'; customRadio.className = 'hidden';
        document.getElementById('courseForm').appendChild(customRadio);
    }
    customRadio.value = hexColor; customRadio.checked = true;
    showToast("Couleur appliquée !");
}

// MOODBOARD ENGINE
function openMoodboardEditor(id) {
    const mb = allCourses.find(c => c.id == id);
    if (!mb) return;
    currentEditingCourseId = mb.id;
    document.getElementById('mbTitle').innerText = mb.title;
    document.getElementById('mbColorBadge').style.backgroundColor = mb.color || '#6366f1';
    
    const canvas = document.getElementById('moodboardCanvas');
    canvas.innerHTML = mb.content || '<p class="text-xs text-slate-400 p-8 text-center pointer-events-none">Moodboard vide. Colle des images (Ctrl+V) ou crée des blocs !</p>';
    
    enableMoodboardDragAndResize();
    switchTab('moodboard-editor');
}

function addMoodboardBlock() {
    const canvas = document.getElementById('moodboardCanvas');
    const block = document.createElement('div');
    block.className = 'mb-item absolute bg-amber-100 border border-amber-200 p-4 rounded-2xl shadow-md w-64 min-h-[100px] text-xs font-medium text-slate-800 resize overflow-auto z-10';
    block.style.left = '60px'; 
    block.style.top = '60px';
    
    block.innerHTML = `
        <div class="flex justify-between items-center mb-2 pb-1 border-b border-amber-200/60 drag-handle cursor-move select-none">
            <span class="text-[10px] font-bold uppercase text-slate-500">Bloc Note</span>
            <div class="flex items-center gap-1.5">
                <input type="color" value="#fef3c7" onchange="this.closest('.mb-item').style.backgroundColor = this.value" class="w-4 h-4 border-0 p-0 cursor-pointer rounded bg-transparent" title="Changer la couleur">
                <button onclick="this.closest('.mb-item').remove()" class="text-slate-400 hover:text-rose-600 text-xs"><i class="fa-solid fa-xmark"></i></button>
            </div>
        </div>
        <div contenteditable="true" class="outline-none min-h-[50px]">Ton texte ici...</div>
    `;
    canvas.appendChild(block);
    enableMoodboardDragAndResize();
    showToast("Bloc modifiable ajouté !");
}

function enableMoodboardDragAndResize() {
    const items = document.querySelectorAll('.mb-item');
    items.forEach(item => {
        const handle = item.querySelector('.drag-handle') || item;
        let isDragging = false, offsetKeyX = 0, offsetKeyY = 0;
        
        handle.onmousedown = (e) => {
            if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.isContentEditable) return;
            isDragging = true;
            offsetKeyX = e.clientX - item.offsetLeft;
            offsetKeyY = e.clientY - item.offsetTop;
        };
        
        document.addEventListener('mousemove', (e) => {
            if (isDragging) {
                item.style.left = `${e.clientX - offsetKeyX}px`;
                item.style.top = `${e.clientY - offsetKeyY}px`;
            }
        });
        
        document.addEventListener('mouseup', () => { isDragging = false; });
    });
}

async function saveMoodboardContent() {
    if (!currentEditingCourseId) return;
    const canvas = document.getElementById('moodboardCanvas');
    await fetch('api/courses.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ id: currentEditingCourseId, title: document.getElementById('mbTitle').innerText, content: canvas.innerHTML })
    });
    showToast("Moodboard sauvegardé !⚡");
}

// COURS & DOSSIERS
function selectCourseType(isFolder) {
    document.getElementById('courseIsFolder').value = isFolder;
    const btnF = document.getElementById('btnTypeFolder');
    const btnD = document.getElementById('btnTypeFile');
    const btnM = document.getElementById('btnTypeMoodboard');
    if (btnF) btnF.className = "py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold text-slate-600";
    if (btnD) btnD.className = "py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold text-slate-600";
    if (btnM) btnM.className = "py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold text-slate-600";

    if (isFolder === 1 && btnF) btnF.className = "py-2.5 bg-brand-50 border border-brand-200 rounded-xl text-xs font-bold text-brand-700";
    if (isFolder === 0 && btnD) btnD.className = "py-2.5 bg-brand-50 border border-brand-200 rounded-xl text-xs font-bold text-brand-700";
    if (isFolder === 2 && btnM) btnM.className = "py-2.5 bg-brand-50 border border-brand-200 rounded-xl text-xs font-bold text-brand-700";
}

function navigateToFolder(folderId) {
    if (folderId !== currentFolderId) {
        if (currentFolderId !== null && folderId !== null) folderHistory.push(currentFolderId);
        else if (folderId === null) folderHistory = [];
        currentFolderId = folderId;
    }
    loadCourses();
}

function navigateBack() {
    currentFolderId = folderHistory.length > 0 ? folderHistory.pop() : null;
    loadCourses();
}

function updateBreadcrumb() {
    const trail = document.getElementById('breadcrumbTrail');
    const btnBack = document.getElementById('btnGoBack');
    if (!trail) return;
    trail.innerHTML = '';
    if (currentFolderId === null) { if (btnBack) btnBack.classList.add('hidden'); return; }
    if (btnBack) btnBack.classList.remove('hidden');
    const currentFolder = allCourses.find(c => c.id == currentFolderId);
    if (currentFolder) trail.innerHTML = `<span class="text-slate-300">/</span> <span class="font-bold text-slate-800">${currentFolder.title}</span>`;
}

async function loadCourses() {
    try {
        const res = await fetch('api/courses.php');
        const data = await res.json();
        if (!data.success) return;

        allCourses = data.courses || [];
        updateBreadcrumb();
        populateTaskCourseSelect();
        renderCoursesGrid();
    } catch (err) { console.error("Erreur loadCourses:", err); }
}

function showCourseContextMenu(e, courseId) {
    e.preventDefault();
    e.stopPropagation();
    
    let oldMenu = document.getElementById('customCourseContextMenu');
    if (oldMenu) oldMenu.remove();

    const course = allCourses.find(c => c.id == courseId);
    if (!course) return;

    const menu = document.createElement('div');
    menu.id = 'customCourseContextMenu';
    menu.className = 'fixed bg-white border border-slate-200 shadow-xl rounded-2xl p-2 z-50 text-xs w-48 space-y-1';
    menu.style.left = `${e.clientX}px`;
    menu.style.top = `${e.clientY}px`;

    menu.innerHTML = `
        <div class="px-3 py-1.5 font-extrabold text-slate-400 text-[10px] uppercase border-b border-slate-100 truncate">${course.title}</div>
        <button onclick="openRenameCourseModal(${course.id})" class="w-full text-left px-3 py-2 hover:bg-slate-50 rounded-xl font-semibold text-slate-700 flex items-center gap-2"><i class="fa-solid fa-pen text-brand-600"></i> Renommer</button>
        <button onclick="openColorPickerModal(${course.id})" class="w-full text-left px-3 py-2 hover:bg-slate-50 rounded-xl font-semibold text-slate-700 flex items-center gap-2"><i class="fa-solid fa-palette text-purple-500"></i> Changer la couleur</button>
        <button onclick="deleteCourseItem(${course.id})" class="w-full text-left px-3 py-2 hover:bg-rose-50 hover:text-rose-600 rounded-xl font-semibold text-rose-500 flex items-center gap-2"><i class="fa-solid fa-trash"></i> Supprimer</button>
    `;

    document.body.appendChild(menu);

    const closeMenu = (evt) => {
        if (!menu.contains(evt.target)) {
            menu.remove();
            document.removeEventListener('click', closeMenu);
        }
    };
    setTimeout(() => document.addEventListener('click', closeMenu), 10);
}

function openRenameCourseModal(id) {
    const course = allCourses.find(c => c.id == id);
    if (!course) return;
    const newTitle = prompt("Nouveau nom :", course.title);
    if (newTitle && newTitle.trim() !== '') {
        fetch('api/courses.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ id: course.id, title: newTitle.trim() })
        }).then(() => {
            showToast("Renommé avec succès !");
            loadCourses();
        });
    }
}

function openColorPickerModal(id) {
    const course = allCourses.find(c => c.id == id);
    if (!course) return;
    const newColor = prompt("Code couleur HEX (ex: #6366f1 ou #10b981) :", course.color || '#6366f1');
    if (newColor) {
        fetch('api/courses.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ id: course.id, color: newColor.trim() })
        }).then(() => {
            showToast("Couleur mise à jour !");
            loadCourses();
        });
    }
}

function deleteCourseItem(id) {
    showConfirmModal("Supprimer cet élément ?", async () => {
        await fetch('api/courses.php', {
            method: 'DELETE',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ id })
        });
        showToast("Supprimé avec succès", "error");
        loadCourses();
    });
}

function renderCoursesGrid() {
    const grid = document.getElementById('coursesGrid');
    if (!grid) return;
    grid.innerHTML = '';

    const currentItems = allCourses.filter(c => c.parent_id == currentFolderId);

    if (currentItems.length === 0) {
        grid.innerHTML = '<p class="text-xs text-slate-400 py-6 text-center col-span-3">Dossier vide. Glisse des éléments ici ou clique sur "+ Créer Nouveau".</p>';
        return;
    }

    currentItems.forEach((c) => {
        const type = parseInt(c.is_folder);
        const color = c.color || '#6366f1';
        const linkedTasks = allTasks.filter(t => t.course_id == c.id && parseInt(t.is_completed) === 0);
        const taskBadge = linkedTasks.length > 0 ? `<span class="text-[9px] bg-rose-100 text-rose-600 font-extrabold px-2 py-0.5 rounded-full border border-rose-200">${linkedTasks.length} quête(s)</span>` : '';

        const card = document.createElement('div');
        card.className = `bg-white border border-slate-200 rounded-3xl p-5 shadow-sm hover:shadow-md transition flex flex-col justify-between cursor-pointer border-t-4 select-none relative`;
        card.style.borderTopColor = color;
        card.draggable = true;

        card.ondragstart = (e) => {
            e.dataTransfer.setData('text/plain', c.id);
        };

        card.ondragover = (e) => {
            e.preventDefault();
        };

        card.ondrop = async (e) => {
            e.preventDefault();
            e.stopPropagation();
            const draggedId = e.dataTransfer.getData('text/plain');

            if (draggedId && draggedId != c.id) {
                let targetParentId = currentFolderId;
                
                if (type === 1) {
                    targetParentId = c.id;
                }

                await fetch('api/courses.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ id: draggedId, parent_id: targetParentId })
                });

                showToast("Élément déplacé avec succès ! 📦");
                loadCourses();
            }
        };

        card.oncontextmenu = (e) => showCourseContextMenu(e, c.id);

        if (type === 1) {
            card.onclick = () => navigateToFolder(c.id);
            card.innerHTML = `<div class="flex items-center justify-between"><div class="flex items-center gap-3"><i class="fa-solid fa-folder text-2xl" style="color: ${color}"></i><div><h3 class="font-bold text-slate-900 text-sm">${c.title}</h3><span class="text-[10px] text-slate-400 font-semibold">Dossier</span></div></div><div class="flex items-center gap-2">${taskBadge}</div></div>`;
        } else if (type === 2) {
            card.onclick = () => openMoodboardEditor(c.id);
            card.innerHTML = `<div class="flex items-center justify-between"><div class="flex items-center gap-3"><i class="fa-solid fa-palette text-2xl text-purple-500"></i><div><h3 class="font-bold text-slate-900 text-sm">${c.title}</h3><span class="text-[10px] text-purple-600 font-bold bg-purple-50 px-2 py-0.5 rounded">Moodboard</span></div></div><div class="flex items-center gap-2">${taskBadge}</div></div>`;
        } else {
            card.onclick = () => openCourseEditor(c.id);
            card.innerHTML = `<div class="flex items-center justify-between"><div class="flex items-center gap-3"><i class="fa-regular fa-file-lines text-2xl text-slate-400"></i><div><h3 class="font-bold text-slate-900 text-sm">${c.title}</h3><span class="text-[10px] text-slate-400 font-semibold">Fiche de cours</span></div></div><div class="flex items-center gap-2">${taskBadge}</div></div>`;
        }
        grid.appendChild(card);
    });
}

function populateTaskCourseSelect() {
    const select = document.getElementById('newTaskCourse');
    if (!select) return;
    select.innerHTML = '<option value="">Lier un module (Optionnel)</option>';
    allCourses.forEach(c => {
        select.innerHTML += `<option value="${c.id}">${c.title}</option>`;
    });
}

function openCourseModal(isEdit = false) { 
    const form = document.getElementById('courseForm');
    if (form && !isEdit) {
        form.reset();
        document.getElementById('courseEditId').value = '';
        document.getElementById('courseModalTitle').innerHTML = `<i class="fa-solid fa-folder-plus text-brand-600 mr-2"></i> Nouvel Élément`;
        document.getElementById('courseTypeContainer').classList.remove('hidden');
    }
    document.getElementById('courseModal').classList.remove('hidden'); 
}
function closeCourseModal() { document.getElementById('courseModal').classList.add('hidden'); }

const courseForm = document.getElementById('courseForm');
if (courseForm) {
    courseForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const payload = {
            id: document.getElementById('courseEditId').value || null,
            title: document.getElementById('courseTitle').value,
            is_folder: parseInt(document.getElementById('courseIsFolder').value),
            parent_id: currentFolderId,
            color: document.querySelector('input[name="courseColor"]:checked')?.value || '#6366f1'
        };

        const res = await fetch('api/courses.php', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) });
        const data = await res.json();
        if (data.success) { closeCourseModal(); showToast("Enregistré avec succès !"); loadCourses(); }
    });
}

function openCourseEditor(id) {
    const course = allCourses.find(c => c.id == id);
    if (!course) return;
    currentEditingCourseId = course.id;
    document.getElementById('editorCourseTitle').innerText = course.title;
    document.getElementById('editorColorBadge').style.backgroundColor = course.color || '#6366f1';
    document.getElementById('richEditor').innerHTML = course.content || '<p>Écris tes notes de cours ici...</p>';
    switchTab('course-editor');
}

async function saveCourseContent() {
    if (!currentEditingCourseId) return;
    await fetch('api/courses.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ id: currentEditingCourseId, title: document.getElementById('editorCourseTitle').innerText, content: document.getElementById('richEditor').innerHTML })
    });
    showToast("Fiche sauvegardée avec succès !⚡");
}

// PASTE IMAGES
document.addEventListener('paste', (e) => {
    const items = (e.clipboardData || e.originalEvent.clipboardData).items;
    for (let item of items) {
        if (item.kind === 'file' && item.type.startsWith('image/')) {
            e.preventDefault();
            const blob = item.getAsFile();
            const reader = new FileReader();
            reader.onload = (event) => {
                const editorTab = document.getElementById('tab-course-editor');
                const moodboardTab = document.getElementById('tab-moodboard-editor');
                if (editorTab && editorTab.classList.contains('active')) {
                    execCmd('insertImage', event.target.result);
                    showToast("Image insérée dans la fiche !");
                } else if (moodboardTab && moodboardTab.classList.contains('active')) {
                    const canvas = document.getElementById('moodboardCanvas');
                    const imgContainer = document.createElement('div');
                    imgContainer.className = 'mb-item bg-white border border-slate-200 p-2 rounded-2xl shadow-md';
                    imgContainer.style.left = '120px'; imgContainer.style.top = '120px';
                    imgContainer.innerHTML = `<img src="${event.target.result}" class="max-w-[250px] rounded-xl pointer-events-none">`;
                    canvas.appendChild(imgContainer);
                    enableMoodboardDragAndResize();
                    showToast("Image collée dans le Moodboard !");
                }
            };
            reader.readAsDataURL(blob);
            break;
        }
    }
});

// HELPER COULEUR XP
function getXpBadgeStyle(xp) {
    const xpVal = parseInt(xp);
    if (xpVal >= 175) return { bg: 'bg-rose-50 text-rose-600 border-rose-200', label: 'Urgent' };
    if (xpVal >= 100) return { bg: 'bg-amber-50 text-amber-600 border-amber-200', label: 'Important' };
    return { bg: 'bg-emerald-50 text-emerald-600 border-emerald-200', label: 'Tranquille' };
}

// OUVRIR UN MODULE LIÉ À UNE QUÊTE
function openLinkedCourse(courseId) {
    if (!courseId) return;
    switchTab('courses');
    const course = allCourses.find(c => c.id == courseId);
    if (!course) return;

    if (parseInt(course.is_folder) === 1) {
        navigateToFolder(course.id);
    } else if (parseInt(course.is_folder) === 2) {
        openMoodboardEditor(course.id);
    } else {
        openCourseEditor(course.id);
    }
}

// QUÊTES MANAGEMENT
async function loadTasks() {
    try {
        const res = await fetch('api/tasks.php');
        allTasks = await res.json();
        
        const fullContainer = document.getElementById('fullTasksList');
        const dashContainer = document.getElementById('dashTasksList');
        if (fullContainer) fullContainer.innerHTML = '';
        if (dashContainer) dashContainer.innerHTML = '';

        if (!Array.isArray(allTasks) || allTasks.length === 0) {
            if (fullContainer) fullContainer.innerHTML = '<p class="text-xs text-slate-400 py-4 text-center">Aucune quête créée.</p>';
            if (dashContainer) dashContainer.innerHTML = '<p class="text-xs text-slate-400 py-2">Aucune quête en cours.</p>';
            return;
        }

        allTasks.forEach((t, index) => {
            const isDone = parseInt(t.is_completed) === 1;
            const style = getXpBadgeStyle(t.xp_reward);
            const item = document.createElement('div');
            item.className = `p-3.5 rounded-2xl border flex justify-between items-center transition cursor-pointer select-none ${isDone ? 'bg-slate-50 border-slate-200 opacity-60' : 'bg-white border-slate-200 shadow-sm'}`;

            item.oncontextmenu = (e) => showContextMenu(e, { ...t, type: 'task' });

            const dateLimit = t.due_date || t.completed_at;
            let dateTag = '';
            if (dateLimit && !isDone) {
                const remainingInfo = getRemainingTimeText(dateLimit);
                if (remainingInfo) {
                    dateTag = `<span class="text-[10px] px-2 py-0.5 rounded-md border font-extrabold ${remainingInfo.color}"><i class="fa-regular fa-clock mr-1"></i>${remainingInfo.text} (${dateLimit})</span>`;
                } else {
                    dateTag = `<span class="text-[10px] text-amber-600 bg-amber-50 border border-amber-200 px-2 py-0.5 rounded-md font-semibold"><i class="fa-regular fa-calendar mr-1"></i>${dateLimit}</span>`;
                }
            }

            let courseTag = t.course_title ? `<button onclick="event.stopPropagation(); openLinkedCourse(${t.course_id})" class="text-[10px] text-brand-600 bg-brand-50 hover:bg-brand-100 border border-brand-200 px-2 py-0.5 rounded-md font-bold transition"><i class="fa-solid fa-folder mr-1"></i>${t.course_title}</button>` : '';
            let proofBtn = isDone && t.proof_data ? `<a href="${t.proof_data}" target="_blank" class="text-[10px] text-brand-600 underline font-semibold ml-2">Voir le rendu</a>` : '';

            item.innerHTML = `
                <div class="flex items-center gap-3" onclick="openEventDetail(${t.id}, '${t.title.replace(/'/g, "\\'")}', '${t.due_date || ''}', 'task', ${t.course_id || 'null'}, '${(t.description || '').replace(/'/g, "\\'")}')">
                    <div>
                        <span class="text-xs font-bold ${isDone ? 'line-through text-slate-400' : 'text-slate-800'} hover:text-brand-600">${t.title}</span>
                        <div class="flex flex-wrap gap-1.5 mt-1 items-center">
                            ${dateTag}
                            ${courseTag}
                            ${proofBtn}
                        </div>
                    </div>
                </div>
                <div class="flex items-center gap-2">
                    <span class="text-[10px] font-extrabold px-2.5 py-1 rounded-lg border ${isDone ? 'bg-slate-100 text-slate-400 border-slate-200' : style.bg}">+${t.xp_reward} XP</span>
                    ${isDone ? '<span class="text-xs text-emerald-600 font-bold px-2"><i class="fa-solid fa-check"></i> Validé</span>' : `<button onclick="openProofModal(${t.id})" class="px-3 py-1 bg-brand-50 border border-brand-200 text-brand-600 rounded-lg text-xs font-bold hover:bg-brand-600 hover:text-white transition">Valider</button>`}
                    <button onclick="event.stopPropagation(); openEventDetail(${t.id}, '${t.title.replace(/'/g, "\\'")}', '${t.due_date || ''}', 'task', ${t.course_id || 'null'}, '${(t.description || '').replace(/'/g, "\\'")}')" class="text-slate-400 hover:text-brand-600 text-xs p-1.5 transition" title="Modifier la quête"><i class="fa-solid fa-pen"></i></button>
                    <button onclick="deleteTask(${t.id})" class="text-slate-400 hover:text-rose-600 text-xs p-1.5 transition" title="Supprimer"><i class="fa-solid fa-trash"></i></button>
                </div>
            `;

            if (fullContainer) fullContainer.appendChild(item);
            if (index < 3 && dashContainer) dashContainer.appendChild(item.cloneNode(true));
        });
    } catch(e) { console.error("Erreur loadTasks:", e); }
}

function deleteTask(id) {
    showConfirmModal("Supprimer cette quête ?", async () => {
        try {
            await fetch('api/tasks.php', { method: 'DELETE', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ id }) });
            showToast("Quête supprimée", "error");
            loadTasks();
            loadCalendar();
        } catch(e) { console.error(e); }
    });
}

const addTaskForm = document.getElementById('addTaskForm');
if (addTaskForm) {
    addTaskForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        await fetch('api/tasks.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                title: document.getElementById('newTaskTitle').value,
                description: document.getElementById('newTaskDesc').value,
                due_date: document.getElementById('newTaskDate').value,
                course_id: document.getElementById('newTaskCourse').value || null,
                xp_reward: parseInt(document.getElementById('newTaskXp').value) || 50
            })
        });
        document.getElementById('newTaskTitle').value = '';
        document.getElementById('newTaskDesc').value = '';
        document.getElementById('newTaskDate').value = '';
        showToast("Quête créée !");
        loadTasks();
        loadCalendar();
    });
}

// BASCULEMENT PREUVE (IMAGE / LIEN)
function openProofModal(id) {
    document.getElementById('proofTaskId').value = id;
    selectProofType('image');
    document.getElementById('proofModal').classList.remove('hidden');
}

function closeProofModal() { document.getElementById('proofModal').classList.add('hidden'); }

function selectProofType(type) {
    document.getElementById('proofTypeInput').value = type;
    const btnImg = document.getElementById('btnProofImage');
    const btnLink = document.getElementById('btnProofLink');
    const fieldImg = document.getElementById('fieldProofImage');
    const fieldLink = document.getElementById('fieldProofLink');

    if (type === 'image') {
        btnImg.className = "py-2.5 bg-brand-50 border border-brand-200 rounded-xl text-xs font-bold text-brand-700";
        btnLink.className = "py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold text-slate-600";
        fieldImg.classList.remove('hidden');
        fieldLink.classList.add('hidden');
    } else {
        btnLink.className = "py-2.5 bg-brand-50 border border-brand-200 rounded-xl text-xs font-bold text-brand-700";
        btnImg.className = "py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold text-slate-600";
        fieldLink.classList.remove('hidden');
        fieldImg.classList.add('hidden');
    }
}

const proofForm = document.getElementById('proofForm');
if (proofForm) {
    proofForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const taskId = document.getElementById('proofTaskId').value;
        const proofType = document.getElementById('proofTypeInput').value;

        let newXpTotal = null;

        if (proofType === 'link') {
            const linkVal = document.querySelector('#fieldProofLink input').value;
            if (!linkVal) { showToast("Saisis un lien valide.", "error"); return; }
            
            const res = await fetch('api/tasks.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ id: taskId, is_completed: 1, proof_data: linkVal })
            });
            const data = await res.json();
            if (data.success && data.new_xp !== undefined) newXpTotal = data.new_xp;
        } else {
            const formData = new FormData(e.target);
            const res = await fetch('api/upload_proof.php', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.success && data.new_xp !== undefined) newXpTotal = data.new_xp;
        }

        closeProofModal();
        showToast("Quête validée ! (+XP)");
        
        if (newXpTotal !== null) updateXpUI(newXpTotal);
        else await checkAuth();

        loadTasks();
        loadCalendar();
    });
}

function updateXpUI(totalXp) {
    const xp = parseInt(totalXp || 0);
    const level = Math.floor(xp / 1000) + 1;
    const currentLevelXp = xp % 1000;
    const xpPercent = Math.min(100, Math.floor((currentLevelXp / 1000) * 100));

    if (document.getElementById('userLevel')) document.getElementById('userLevel').innerText = `Lvl ${level}`;
    if (document.getElementById('xpText')) document.getElementById('xpText').innerText = `${currentLevelXp} / 1000 XP`;

    if (document.getElementById('userSidebarLvl')) document.getElementById('userSidebarLvl').innerText = `Niveau ${level}`;
    if (document.getElementById('userSidebarXpText')) document.getElementById('userSidebarXpText').innerText = `${currentLevelXp} / 1000 XP`;
    if (document.getElementById('userSidebarXpBar')) document.getElementById('userSidebarXpBar').style.width = `${xpPercent}%`;
}

// NOTES & BULLETIN
function openNoteModal() { document.getElementById('noteModal').classList.remove('hidden'); }
function closeNoteModal() { document.getElementById('noteModal').classList.add('hidden'); }

async function loadNotes() {
    try {
        const res = await fetch('api/notes.php');
        const data = await res.json();
        if (!data.success) return;

        const globalAvg = data.global_average !== null ? `${data.global_average} / 20` : '-- / 20';
        const avgEl = document.getElementById('dashGlobalAvg');
        if (avgEl) avgEl.innerText = globalAvg;

        const comps = ['Concevoir', 'Développer', 'Exprimer', 'Entreprendre', 'Comprendre'];
        const dashGrid = document.getElementById('dashCompetencesGrid');
        const fullGrid = document.getElementById('fullCompetencesGrid');
        if (dashGrid) dashGrid.innerHTML = '';
        if (fullGrid) fullGrid.innerHTML = '';

        comps.forEach(c => {
            const score = data.competence_averages[c];
            const val = score !== null ? `${score}/20` : '--';
            const cardHtml = `
                <div class="bg-slate-50 border border-slate-200 p-2.5 rounded-2xl">
                    <span class="text-[9px] font-bold uppercase text-slate-400 block">${c}</span>
                    <span class="font-extrabold text-xs text-brand-600">${val}</span>
                </div>
            `;
            if (dashGrid) dashGrid.innerHTML += cardHtml;
            if (fullGrid) fullGrid.innerHTML += cardHtml;
        });

        const fullNotesList = document.getElementById('fullNotesList');
        if (fullNotesList) {
            fullNotesList.innerHTML = '';
            if (!data.notes || data.notes.length === 0) {
                fullNotesList.innerHTML = '<p class="text-xs text-slate-400 py-4 text-center">Aucune note enregistrée.</p>';
                return;
            }

            data.notes.forEach(n => {
                const item = document.createElement('div');
                item.className = "p-3.5 bg-slate-50 border border-slate-200 rounded-2xl flex justify-between items-center text-xs";
                item.innerHTML = `
                    <div>
                        <span class="font-bold text-slate-900">${n.title}</span>
                        <span class="text-[10px] text-brand-600 font-semibold ml-2">(${n.subject_name})</span>
                        ${n.lesson_learned ? `<p class="text-[11px] text-amber-600 italic mt-0.5">💡 Leçon : ${n.lesson_learned}</p>` : ''}
                    </div>
                    <div class="flex items-center gap-3">
                        <span class="font-extrabold text-xs text-brand-600 bg-white border border-slate-200 px-2.5 py-1 rounded-lg">${n.score} / 20</span>
                        <button onclick="deleteNote(${n.id})" class="text-slate-400 hover:text-rose-600 text-xs"><i class="fa-solid fa-trash"></i></button>
                    </div>
                `;
                fullNotesList.appendChild(item);
            });
        }
    } catch(e) { console.error(e); }
}

function deleteNote(id) {
    showConfirmModal("Supprimer cette note ?", async () => {
        await fetch('api/notes.php', { method: 'DELETE', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ id }) });
        showToast("Note supprimée", "error");
        loadNotes();
    });
}

const noteForm = document.getElementById('noteForm');
if (noteForm) {
    noteForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const checkedComps = Array.from(document.querySelectorAll('input[name="competencies[]"]:checked')).map(el => el.value);
        if (checkedComps.length === 0) {
            showToast("Sélectionne au moins une compétence MMI.", "error");
            return;
        }

        const payload = {
            subject_name: document.getElementById('noteSubject').value,
            competencies: checkedComps,
            title: document.getElementById('noteTitle').value,
            score: parseFloat(document.getElementById('noteScore').value),
            coefficient: parseFloat(document.getElementById('noteCoef').value) || 1.0,
            teacher_comment: document.getElementById('noteComment').value,
            lesson_learned: document.getElementById('noteLesson').value
        };

        try {
            const res = await fetch('api/notes.php', { 
                method: 'POST', 
                headers: {'Content-Type': 'application/json'}, 
                body: JSON.stringify(payload) 
            });
            const data = await res.json();
            
            if (data.success) { 
                closeNoteModal(); 
                noteForm.reset(); 
                showToast("Note ajoutée avec succès !"); 
                loadNotes(); 
            } else { 
                showToast(data.message || "Erreur", 'error'); 
            }
        } catch (err) {
            showToast("Erreur de communication", "error");
        }
    });
}

// ABSENCES MANAGEMENT
async function loadAbsences() {
    try {
        const res = await fetch('api/absences.php');
        const data = await res.json();
        
        const list = Array.isArray(data) ? data : (data.list || []);
        const stats = data.stats || null;

        if (stats) {
            if (document.getElementById('statAbsencesCount')) document.getElementById('statAbsencesCount').innerText = stats.total_absences || 0;
            if (document.getElementById('statRetardsCount')) document.getElementById('statRetardsCount').innerText = stats.total_retards || 0;
            if (document.getElementById('statJustifiedCount')) document.getElementById('statJustifiedCount').innerText = stats.justified || 0;
            if (document.getElementById('statUnjustifiedCount')) document.getElementById('statUnjustifiedCount').innerText = stats.unjustified || 0;
        }

        const container = document.getElementById('absencesList');
        if (!container) return;
        container.innerHTML = '';

        if (!Array.isArray(list) || list.length === 0) {
            container.innerHTML = '<p class="text-xs text-slate-400 py-4 text-center">Aucune absence ou retard enregistré.</p>';
            return;
        }

        list.forEach(a => {
            const isJustified = a.is_justified == 1;
            const item = document.createElement('div');
            item.className = "p-3.5 bg-slate-50 border border-slate-200 rounded-2xl flex justify-between items-center text-xs";
            item.innerHTML = `
                <div>
                    <span class="font-bold text-slate-900 uppercase">${a.type}</span>
                    <span class="text-slate-500 font-semibold ml-2">(${a.duration === 'half_day' ? 'Demi-journée' : 'Journée entière'})</span>
                    <span class="text-slate-400 ml-2">• ${a.date}</span>
                    ${a.reason ? `<p class="text-slate-500 italic mt-0.5">Motif : ${a.reason}</p>` : ''}
                </div>
                <div class="flex items-center gap-3">
                    <span class="text-[10px] font-extrabold px-2.5 py-1 rounded-lg border ${isJustified ? 'bg-emerald-50 text-emerald-600 border-emerald-200' : 'bg-rose-50 text-rose-600 border-rose-200'}">
                        ${isJustified ? 'Justifié' : 'Non justifié'}
                    </span>
                    <button onclick="deleteAbsence(${a.id})" class="text-slate-400 hover:text-rose-600 text-xs"><i class="fa-solid fa-trash"></i></button>
                </div>
            `;
            container.appendChild(item);
        });
    } catch(e) { console.error("Erreur loadAbsences:", e); }
}

function deleteAbsence(id) {
    showConfirmModal("Supprimer ce registre ?", async () => {
        await fetch('api/absences.php', { method: 'DELETE', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ id }) });
        showToast("Registre supprimé", "error");
        loadAbsences();
    });
}

const addAbsenceForm = document.getElementById('addAbsenceForm');
if (addAbsenceForm) {
    addAbsenceForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        try {
            const res = await fetch('api/absences.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    type: document.getElementById('absType').value,
                    duration: document.getElementById('absDuration').value,
                    date: document.getElementById('absDate').value,
                    reason: document.getElementById('absReason').value,
                    is_justified: document.getElementById('absJustified')?.checked ? 1 : 0
                })
            });
            const data = await res.json();
            if (data.success) {
                document.getElementById('absReason').value = '';
                if (document.getElementById('absJustified')) document.getElementById('absJustified').checked = false;
                showToast("Déclaration enregistrée ! Quête urgente générée ⚠️");
                
                loadAbsences();
                loadTasks();
                loadCalendar();
            } else {
                showToast(data.message || "Erreur", "error");
            }
        } catch (err) {
            console.error("Erreur absence:", err);
            showToast("Erreur serveur", "error");
        }
    });
}

// --- TIMER POMODORO & CYCLES & HISTORIQUE XP ---
document.addEventListener('DOMContentLoaded', () => {
    const startBtn = document.getElementById('startTimer');
    const resetBtn = document.getElementById('resetTimer');

    if (startBtn) {
        startBtn.addEventListener('click', () => {
            toggleTimer();
        });
    }

    if (resetBtn) {
        resetBtn.addEventListener('click', () => {
            if (timerInterval) {
                clearInterval(timerInterval);
                timerInterval = null;
            }
            isWorkSession = true;
            timerSeconds = 20 * 60;
            elapsedWorkSeconds = 0;
            currentPomodoroMessage = "Bon travail ! C'est parti.";
            setPomodoroTheme('space');
            updateTimerDisplay();
            if (startBtn) startBtn.innerText = "Démarrer";
            showToast("Chrono réinitialisé");
        });
    }
});

function toggleTimer() {
    const startBtn = document.getElementById('startTimer');
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
        if (startBtn) startBtn.innerText = "Démarrer";
        showToast("Session en pause");
    } else {
        if (startBtn) startBtn.innerText = "Pause";
        showToast(isWorkSession ? "🌙 Session de Focus démarrée !" : "☀️ Pause démarrée !", "info");
        
        timerInterval = setInterval(() => {
            if (timerSeconds > 0) {
                timerSeconds--;
                if (isWorkSession) elapsedWorkSeconds++;
                updateTimerDisplay();
            } else {
                clearInterval(timerInterval);
                timerInterval = null;

                if (isWorkSession) {
                    // Fin du travail -> Ajout des XP
                    awardPomodoroXp();
                    showToast("🎉 Session de travail terminée ! +50 XP gagnés !", "success");
                    
                    // Bascule auto sur la pause de 10 minutes
                    isWorkSession = false;
                    timerSeconds = 10 * 60; 
                    setPomodoroTheme('sunrise');
                    showToast("☕ C'est l'heure de la pause de 10 minutes !", "info");
                    toggleTimer(); // Relance auto de la pause
                } else {
                    // Fin de la pause -> Retour au travail
                    isWorkSession = true;
                    timerSeconds = 20 * 60; 
                    setPomodoroTheme('space');
                    showToast("🌙 Fin de la pause ! Reprise du travail.", "info");
                    toggleTimer(); // Relance auto du travail
                }
            }
        }, 1000);
    }
}

function checkEncouragementMessages() {
    const currentMin = Math.floor(timerSeconds / 60);
    const badgeEl = document.getElementById('immersiveStatusBadge');
    const msgEl = document.getElementById('immersiveMessage');

    if (isWorkSession) {
        if (badgeEl) badgeEl.innerText = "SESSION DE FOCUS • TRAVAIL";
        if (currentMin >= 15) {
            currentPomodoroMessage = "💪 Bon travail ! Reste concentré.";
        } else if (currentMin >= 10) {
            currentPomodoroMessage = "🔥 Encore 10 minutes, lâche rien !";
        } else if (currentMin >= 5) {
            currentPomodoroMessage = "⚡ Plus que 5 minutes avant la pause !";
        } else {
            currentPomodoroMessage = "🎯 Presque fini, donne tout !";
        }
    } else {
        if (badgeEl) badgeEl.innerText = "TEMPS DE PAUSE • REPOS";
        if (currentMin >= 5) {
            currentPomodoroMessage = "☕ Profite de ta pause, détends-toi.";
        } else {
            currentPomodoroMessage = "🧘 Bientôt la reprise, prépare-toi !";
        }
    }

    if (msgEl) msgEl.innerText = currentPomodoroMessage;
}

function updateTimerDisplay() {
    const m = Math.floor(timerSeconds / 60).toString().padStart(2, '0');
    const s = (timerSeconds % 60).toString().padStart(2, '0');
    const timeStr = `${m}:${s}`;
    
    if (document.getElementById('timerDisplay')) document.getElementById('timerDisplay').innerText = timeStr;
    if (document.getElementById('immersiveTimerDisplay')) document.getElementById('immersiveTimerDisplay').innerText = timeStr;
    
    checkEncouragementMessages();
    drawPipCanvas(timeStr);
}

function setPomodoroTheme(themeType) {
    const immersiveOverlay = document.getElementById('pomodoroImmersiveOverlay');
    if (!immersiveOverlay) return;

    if (themeType === 'sunrise') {
        immersiveOverlay.className = "fixed inset-0 z-50 flex flex-col items-center justify-center p-6 space-y-6 hidden sunrise-bg text-slate-900";
    } else {
        immersiveOverlay.className = "fixed inset-0 z-50 flex flex-col items-center justify-center p-6 space-y-6 hidden space-bg text-white";
    }
}

async function awardPomodoroXp() {
    try {
        const res = await fetch('api/tasks.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                title: 'Session Pomodoro validée (+50 XP)',
                xp_reward: 50,
                is_completed: 1,
                proof_data: 'Focus Pomodoro'
            })
        });
        const data = await res.json();
        if (data.new_xp !== undefined) {
            updateXpUI(data.new_xp);
        }
        loadXpHistory();
    } catch (e) {
        console.error("Erreur attribution XP Pomodoro:", e);
    }
}

async function loadXpHistory() {
    try {
        const res = await fetch('api/tasks.php');
        const tasks = await res.json();
        const container = document.getElementById('xpHistoryList');
        if (!container) return;

        container.innerHTML = '';
        const completedTasks = tasks.filter(t => parseInt(t.is_completed) === 1);

        if (completedTasks.length === 0) {
            container.innerHTML = '<p class="text-xs text-slate-400 py-2">Aucun historique d\'XP pour le moment.</p>';
            return;
        }

        completedTasks.forEach(t => {
            const item = document.createElement('div');
            item.className = "flex justify-between items-center p-2.5 bg-slate-50 border border-slate-100 rounded-xl text-xs";
            item.innerHTML = `
                <div>
                    <span class="font-bold text-slate-800">${t.title}</span>
                    <span class="text-[10px] text-slate-400 block">${t.completed_at || t.due_date || 'Aujourd\'hui'}</span>
                </div>
                <span class="font-extrabold text-emerald-600 bg-emerald-50 border border-emerald-100 px-2.5 py-1 rounded-lg">+${t.xp_reward} XP</span>
            `;
            container.appendChild(item);
        });
    } catch (e) {
        console.error("Erreur historique XP:", e);
    }
}

function openPomodoroImmersive() {
    const overlay = document.getElementById('pomodoroImmersiveOverlay');
    if (!overlay) return;
    overlay.classList.remove('hidden'); // S'ouvre uniquement au clic sur l'icône grand écran
    generateStars();
}

function closePomodoroImmersive() {
    const overlay = document.getElementById('pomodoroImmersiveOverlay');
    if (overlay) overlay.classList.add('hidden');
}

function generateStars() {
    const overlay = document.getElementById('pomodoroImmersiveOverlay');
    if (!overlay) return;
    
    document.querySelectorAll('.star').forEach(s => s.remove());
    for (let i = 0; i < 20; i++) {
        const star = document.createElement('div');
        star.className = 'star';
        star.style.left = `${Math.random() * 100}%`;
        star.style.top = `${Math.random() * 50}%`;
        star.style.animationDelay = `${Math.random() * 5}s`;
        overlay.appendChild(star);
    }
}

function drawPipCanvas(timeStr) {
    const canvas = document.getElementById('pipCanvas');
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    
    ctx.fillStyle = isWorkSession ? '#0f172a' : '#fef3c7';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.fillStyle = isWorkSession ? '#818cf8' : '#d97706';
    ctx.font = 'bold 14px sans-serif';
    ctx.fillText(isWorkSession ? 'SESSION FOCUS' : 'PAUSE / REPOS', 20, 35);

    ctx.fillStyle = isWorkSession ? '#ffffff' : '#1e293b';
    ctx.font = 'bold 48px monospace';
    ctx.fillText(timeStr, 20, 105);
}

async function triggerPictureInPicture() {
    try {
        const canvas = document.getElementById('pipCanvas');
        const video = document.getElementById('pipVideo');
        if (!canvas || !video) return;

        const stream = canvas.captureStream(10);
        video.srcObject = stream;
        await video.play();

        if (document.pictureInPictureElement) {
            await document.exitPictureInPicture();
        } else {
            await video.requestPictureInPicture();
            showToast("Chrono ancré au-dessus de tes fenêtres !", "info");
        }
    } catch (e) {
        showToast("Picture-in-Picture non supporté sur ce navigateur.", "error");
    }
}

// GESTION DU CALENDRIER & VUES
async function loadCalendar() {
    try {
        const res = await fetch('api/calendar.php');
        const data = await res.json();
        if (!data.success) return;

        calendarEventsList = data.events || [];
        if (document.getElementById('icalUrlInput')) {
            document.getElementById('icalUrlInput').value = data.ical_url || '';
        }
        renderCalendarGrid();
    } catch (e) { console.error("Erreur loadCalendar:", e); }
}

function setCalendarView(mode) {
    calendarViewMode = mode;
    const btnM = document.getElementById('btnViewMonth');
    const btnW = document.getElementById('btnViewWeek');
    if (mode === 'month') {
        if (btnM) btnM.className = "px-3 py-1.5 bg-brand-600 text-white rounded-xl text-xs font-bold transition shadow-sm";
        if (btnW) btnW.className = "px-3 py-1.5 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-xl text-xs font-bold transition";
    } else {
        if (btnW) btnW.className = "px-3 py-1.5 bg-brand-600 text-white rounded-xl text-xs font-bold transition shadow-sm";
        if (btnM) btnM.className = "px-3 py-1.5 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-xl text-xs font-bold transition";
    }
    renderCalendarGrid();
}

function goToToday() {
    calendarCurrentDate = new Date();
    renderCalendarGrid();
    showToast("Retour à aujourd'hui !");
}

function changeMonth(delta) {
    if (calendarViewMode === 'month') {
        calendarCurrentDate.setMonth(calendarCurrentDate.getMonth() + delta);
    } else {
        calendarCurrentDate.setDate(calendarCurrentDate.getDate() + (delta * 7));
    }
    renderCalendarGrid();
}

function renderCalendarGrid() {
    const grid = document.getElementById('calendarDaysGrid');
    const monthYearText = document.getElementById('currentMonthYear');
    if (!grid || !monthYearText) return;

    grid.innerHTML = '';
    const todayStr = new Date().toISOString().split('T')[0];

    if (calendarViewMode === 'month') {
        const year = calendarCurrentDate.getFullYear();
        const month = calendarCurrentDate.getMonth();
        const monthNames = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"];
        monthYearText.innerText = `${monthNames[month]} ${year}`;

        const firstDayIndex = new Date(year, month, 1).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        const paddingDays = firstDayIndex === 0 ? 6 : firstDayIndex - 1;

        for (let i = 0; i < paddingDays; i++) {
            const emptyCell = document.createElement('div');
            emptyCell.className = "min-h-[90px] bg-slate-50/50 rounded-2xl border border-dashed border-slate-100";
            grid.appendChild(emptyCell);
        }

        for (let day = 1; day <= daysInMonth; day++) {
            const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            const isToday = dateStr === todayStr;
            const dayCell = document.createElement('div');
            dayCell.className = `min-h-[90px] border rounded-2xl p-2 flex flex-col justify-between space-y-1 shadow-sm ${isToday ? 'bg-indigo-50/50 border-brand-500 ring-2 ring-brand-200' : 'bg-white border-slate-200'}`;

            const dayNum = document.createElement('span');
            dayNum.className = `text-xs font-bold ${isToday ? 'text-brand-600' : 'text-slate-700'}`;
            dayNum.innerText = day + (isToday ? ' (Auj.)' : '');
            dayCell.appendChild(dayNum);

            const dayEvents = calendarEventsList.filter(e => e.event_date === dateStr);
            const dayTasks = allTasks.filter(t => t.due_date === dateStr && parseInt(t.is_completed) === 0);

            const eventsContainer = document.createElement('div');
            eventsContainer.className = "space-y-1 overflow-hidden";

            dayEvents.forEach(ev => {
                const tag = document.createElement('div');
                tag.className = "text-[9px] font-bold px-1.5 py-0.5 rounded-md truncate text-white cursor-pointer";
                tag.style.backgroundColor = ev.color || '#6366f1';
                tag.innerText = ev.title;
                tag.onclick = () => openEventDetail(ev.id, ev.title, ev.event_date, 'event');
                eventsContainer.appendChild(tag);
            });

            dayTasks.forEach(task => {
                const taskTag = document.createElement('div');
                taskTag.className = "text-[9px] font-bold px-1.5 py-0.5 rounded-lg text-white bg-rose-500 truncate cursor-pointer flex items-center gap-1";
                taskTag.innerHTML = `<i class="fa-solid fa-flag"></i> ${task.title}`;
                taskTag.onclick = () => openEventDetail(task.id, task.title, task.due_date, 'task', task.course_id, task.description);
                eventsContainer.appendChild(taskTag);
            });

            dayCell.appendChild(eventsContainer);
            grid.appendChild(dayCell);
        }
    } else {
        const curr = new Date(calendarCurrentDate);
        const first = curr.getDate() - (curr.getDay() === 0 ? 6 : curr.getDay() - 1);
        const monday = new Date(curr.setDate(first));

        const monthNames = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"];
        monthYearText.innerText = `Semaine du ${monday.getDate()} ${monthNames[monday.getMonth()]} ${monday.getFullYear()}`;

        for (let i = 0; i < 7; i++) {
            const dayDate = new Date(monday);
            dayDate.setDate(monday.getDate() + i);
            const dateStr = dayDate.toISOString().split('T')[0];
            const isToday = dateStr === todayStr;

            const dayCell = document.createElement('div');
            dayCell.className = `min-h-[220px] border rounded-2xl p-3 flex flex-col justify-start space-y-2 shadow-sm ${isToday ? 'bg-indigo-50/50 border-brand-500 ring-2 ring-brand-200' : 'bg-white border-slate-200'}`;

            const dayHeader = document.createElement('div');
            dayHeader.className = "flex justify-between items-center border-b border-slate-100 pb-1";
            dayHeader.innerHTML = `<span class="text-xs font-bold ${isToday ? 'text-brand-600' : 'text-slate-700'}">${dayDate.getDate()}</span> ${isToday ? '<span class="text-[9px] bg-brand-600 text-white px-1.5 py-0.5 rounded-md font-bold">Auj.</span>' : ''}`;
            dayCell.appendChild(dayHeader);

            const dayEvents = calendarEventsList.filter(e => e.event_date === dateStr);
            const dayTasks = allTasks.filter(t => t.due_date === dateStr && parseInt(t.is_completed) === 0);

            const eventsContainer = document.createElement('div');
            eventsContainer.className = "space-y-1.5 overflow-y-auto max-h-[170px]";

            if (dayEvents.length === 0 && dayTasks.length === 0) {
                eventsContainer.innerHTML = '<span class="text-[10px] text-slate-300 italic block pt-2">Aucun événement</span>';
            } else {
                dayEvents.forEach(ev => {
                    const tag = document.createElement('div');
                    tag.className = "text-[10px] font-bold p-2 rounded-xl text-white shadow-xs cursor-pointer truncate";
                    tag.style.backgroundColor = ev.color || '#6366f1';
                    tag.innerText = ev.title;
                    tag.onclick = () => openEventDetail(ev.id, ev.title, ev.event_date, 'event');
                    eventsContainer.appendChild(tag);
                });

                dayTasks.forEach(task => {
                    const taskTag = document.createElement('div');
                    taskTag.className = "text-[10px] font-bold p-2 rounded-xl text-white bg-rose-500 shadow-xs cursor-pointer truncate flex items-center gap-1";
                    taskTag.innerHTML = `<i class="fa-solid fa-flag"></i> ${task.title}`;
                    taskTag.onclick = () => openEventDetail(task.id, task.title, task.due_date, 'task', task.course_id, task.description);
                    eventsContainer.appendChild(taskTag);
                });
            }

            dayCell.appendChild(eventsContainer);
            grid.appendChild(dayCell);
        }
    }
}

// GESTION MODALE AGENDA / ÉVÉNEMENT / QUÊTE
let activeEventId = null;
let activeEventType = null;

function openEventDetail(id, title, date, type = 'event', courseId = null, description = '') {
    activeEventId = id;
    activeEventType = type;
    
    populateModalCourseSelect();

    const titleEl = document.getElementById('modalEventTitle');
    const titleInput = document.getElementById('modalEventTitleInput');
    const dateInput = document.getElementById('modalEventDateInput');
    const courseSelect = document.getElementById('modalEventCourseSelect');
    const descInput = document.getElementById('modalEventDescInput');
    const modal = document.getElementById('eventDetailModal');

    if (titleEl) titleEl.innerText = type === 'task' ? 'Modifier la Quête' : "Modifier l'événement";
    if (titleInput) titleInput.value = title;
    if (dateInput) dateInput.value = date;
    if (descInput) descInput.value = description || '';

    if (courseSelect && courseId) {
        courseSelect.value = courseId;
    }
    
    if (modal) modal.classList.remove('hidden');
}

function closeEventDetailModal() {
    const modal = document.getElementById('eventDetailModal');
    if (modal) modal.classList.add('hidden');
}

async function updateCalendarEvent() {
    const title = document.getElementById('modalEventTitleInput')?.value;
    const date = document.getElementById('modalEventDateInput')?.value;
    const courseId = document.getElementById('modalEventCourseSelect')?.value || null;
    const description = document.getElementById('modalEventDescInput')?.value || '';

    if (!activeEventId) {
        showToast("Erreur : ID introuvable", "error");
        return;
    }

    try {
        let endpoint = 'api/calendar.php';
        let payload = { action: 'update', id: activeEventId, title: title, event_date: date };

        if (activeEventType === 'task') {
            endpoint = 'api/tasks.php';
            payload = { id: activeEventId, title: title, due_date: date, course_id: courseId, description: description };
        }

        const res = await fetch(endpoint, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload)
        });
        const data = await res.json();
        
        if (data.success !== false) {
            closeEventDetailModal();
            showToast("Mis à jour avec succès ! ✨");
            loadCalendar();
            loadTasks();
        } else {
            showToast(data.message || "Erreur", "error");
        }
    } catch (err) {
        showToast("Erreur serveur", "error");
    }
}

async function deleteCalendarEvent() {
    showConfirmModal("Supprimer cet élément ?", async () => {
        try {
            let endpoint = 'api/calendar.php';
            let payload = { id: activeEventId };

            if (activeEventType === 'task') {
                endpoint = 'api/tasks.php';
                payload = { id: activeEventId };
            }

            const res = await fetch(endpoint, {
                method: 'DELETE',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(payload)
            });
            const data = await res.json();
            
            if (data.success !== false) {
                closeEventDetailModal();
                showToast("Supprimé avec succès", "error");
                loadCalendar();
                loadTasks();
            } else {
                showToast(data.message || "Erreur", "error");
            }
        } catch (err) {
            showToast("Erreur serveur", "error");
        }
    });
}

function populateModalCourseSelect() {
    const select = document.getElementById('modalEventCourseSelect');
    if (!select) return;
    select.innerHTML = '<option value="">Aucun module</option>';
    allCourses.forEach(c => {
        select.innerHTML += `<option value="${c.id}">${c.title}</option>`;
    });
}

function openEventModal() { document.getElementById('eventModal').classList.remove('hidden'); }
function closeEventModal() { document.getElementById('eventModal').classList.add('hidden'); }

const eventForm = document.getElementById('eventForm');
if (eventForm) {
    eventForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const payload = {
            title: document.getElementById('eventTitle').value,
            event_date: document.getElementById('eventDate').value,
            color: document.getElementById('eventColor').value
        };

        const res = await fetch('api/calendar.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ title: payload.title, event_date: payload.event_date, color: payload.color })
        });
        const data = await res.json();
        if (data.success) {
            closeEventModal();
            document.getElementById('eventTitle').value = '';
            showToast("Événement ajouté au planning !");
            loadCalendar();
        }
    });
}

async function saveIcalUrl() {
    const url = document.getElementById('icalUrlInput').value;
    const res = await fetch('api/calendar.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ action: 'save_ical', ical_url: url })
    });
    const data = await res.json();
    if (data.success) {
        showToast("Lien iCal sauvegardé !");
        loadCalendar();
    }
}

// NAVIGATION ONGLETS
function switchTab(tabName) {
    document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
    document.querySelectorAll('nav button').forEach(el => el.className = "w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold text-slate-500 hover:bg-slate-50 transition");
    
    const target = document.getElementById(`tab-${tabName}`);
    const btn = document.getElementById(`nav-${tabName}`);
    
    if (target) target.classList.add('active');
    if (btn) btn.className = "w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold text-brand-600 bg-brand-50 border border-brand-100 transition";

    if (tabName === 'calendar') loadCalendar();
    if (tabName === 'absences') loadAbsences();
    if (tabName === 'grades') loadNotes();
}

// GESTION AUTHENTIFICATION & PROFIL
// --- GESTION AUTHENTIFICATION (CONNEXION & INSCRIPTION) ---
const authForm = document.getElementById('authForm');
const toggleAuthModeBtn = document.getElementById('toggleAuthMode');
let isRegisterMode = false;

if (toggleAuthModeBtn) {
    toggleAuthModeBtn.addEventListener('click', () => {
        isRegisterMode = !isRegisterMode;
        const authTitle = document.getElementById('authTitle');
        const usernameGroup = document.getElementById('usernameGroup');
        const identifierLabel = document.getElementById('identifierLabel');
        
        if (isRegisterMode) {
            authTitle.innerText = "Créer un compte";
            toggleAuthModeBtn.innerText = "Déjà un compte ? Connexion";
            usernameGroup.classList.remove('hidden');
            identifierLabel.innerText = "Email";
        } else {
            authTitle.innerText = "Connexion";
            toggleAuthModeBtn.innerText = "Créer un compte";
            usernameGroup.classList.add('hidden');
            identifierLabel.innerText = "Identifiant (Email / Pseudo)";
        }
    });
}

if (authForm) {
    authForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const errorEl = document.getElementById('authError');
        if (errorEl) errorEl.classList.add('hidden');

        const identifier = document.getElementById('authIdentifier').value;
        const password = document.getElementById('authPassword').value;
        const username = document.getElementById('authUsername')?.value || '';

        const endpoint = isRegisterMode ? 'api/register.php' : 'api/login.php';
        const payload = isRegisterMode ? { username, email: identifier, password } : { identifier, password };

        try {
            const res = await fetch(endpoint, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(payload)
            });
            const data = await res.json();

            if (data.success) {
                showToast(isRegisterMode ? "Compte créé avec succès !" : "Connexion réussie !");
                document.getElementById('authModal').classList.add('hidden');
                checkAuth();
            } else {
                if (errorEl) {
                    errorEl.innerText = data.message || "Erreur d'authentification.";
                    errorEl.classList.remove('hidden');
                }
                showToast(data.message || "Erreur", "error");
            }
        } catch (err) {
            console.error("Erreur auth:", err);
            showToast("Erreur de connexion au serveur.", "error");
        }
    });
}

async function checkAuth() {
    try {
        const res = await fetch('api/me.php');
        const data = await res.json();
        if (data.authenticated) {
            currentUser = data.user;
            document.getElementById('authModal').classList.add('hidden');
            
            if (document.getElementById('userNameDisplay')) {
                document.getElementById('userNameDisplay').innerText = currentUser.username;
            }
            
            const avatarContainer = document.getElementById('userAvatarContainer');
            if (avatarContainer) {
                if (currentUser.avatar) {
                    avatarContainer.innerHTML = `<img src="${currentUser.avatar}">`;
                } else {
                    avatarContainer.innerHTML = `👤`;
                }
            }

            applyUserPreferences(currentUser);
            
            const userXp = parseInt(currentUser.stats?.current_xp || 0);
            updateXpUI(userXp);

            loadTasks(); loadCourses(); loadNotes(); loadAbsences(); loadCalendar(); loadXpHistory();
        } else {
            document.getElementById('authModal').classList.remove('hidden');
        }
    } catch (e) { console.error(e); }
}

const logoutBtn = document.getElementById('logoutBtn');
if (logoutBtn) {
    logoutBtn.addEventListener('click', async () => {
        try {
            await fetch('api/logout.php');
            showToast("Déconnexion réussie");
            setTimeout(() => window.location.reload(), 1000);
        } catch (e) {
            window.location.reload();
        }
    });
}

function applyUserPreferences(user) {
    if (!user) return;
    
    const theme = user.theme_color || 'indigo';
    document.body.setAttribute('data-theme', theme);

    if (user.dyslexia_mode == 1) {
        document.body.style.fontFamily = '"Comic Sans MS", "Arial", sans-serif';
        document.body.style.letterSpacing = '0.5px';
        document.body.style.lineHeight = '1.7';
    } else {
        document.body.style.fontFamily = '';
        document.body.style.letterSpacing = '';
        document.body.style.lineHeight = '';
    }

    if (user.dark_mode == 1) {
        document.body.classList.add('dark-deep');
    } else {
        document.body.classList.remove('dark-deep');
    }
}

function openProfileModal() {
    const input = document.getElementById('profileUsernameInput');
    const preview = document.getElementById('modalAvatarPreview');
    const darkModeCheck = document.getElementById('profileDarkMode');
    const dyslexiaCheck = document.getElementById('profileDyslexia');
    
    if (currentUser && input) {
        input.value = currentUser.username || '';
        if (darkModeCheck) darkModeCheck.checked = currentUser.dark_mode == 1;
        if (dyslexiaCheck) dyslexiaCheck.checked = currentUser.dyslexia_mode == 1;
        
        const themeRadio = document.querySelector(`input[name="theme_color"][value="${currentUser.theme_color || 'indigo'}"]`);
        if (themeRadio) themeRadio.checked = true;

        if (preview) {
            if (currentUser.avatar) {
                preview.innerHTML = `<img src="${currentUser.avatar}" class="w-full h-full object-cover">`;
            } else {
                preview.innerHTML = `👤`;
            }
        }
    }
    const modal = document.getElementById('profileModal');
    if (modal) modal.classList.remove('hidden');
}

function closeProfileModal() {
    const modal = document.getElementById('profileModal');
    if (modal) modal.classList.add('hidden');
}

document.addEventListener('DOMContentLoaded', () => {
    const profileForm = document.getElementById('profileForm');
    if (profileForm) {
        profileForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(profileForm);
            
            formData.set('dark_mode', document.getElementById('profileDarkMode')?.checked ? '1' : '0');
            formData.set('dyslexia_mode', document.getElementById('profileDyslexia')?.checked ? '1' : '0');
            
            const selectedTheme = document.querySelector('input[name="theme_color"]:checked');
            if (selectedTheme) {
                formData.set('theme_color', selectedTheme.value);
            }

            const newUsername = document.getElementById('profileUsernameInput')?.value;
            if (newUsername) {
                formData.set('username', newUsername);
            }

            try {
                const res = await fetch('api/profile.php', { 
                    method: 'POST', 
                    body: formData 
                });
                const data = await res.json();

                if (data.success) {
                    showToast("Paramètres mis à jour ! ✨");
                    closeProfileModal();
                    await checkAuth();
                } else {
                    showToast(data.message || "Erreur lors de la mise à jour", "error");
                }
            } catch (err) {
                console.error("Erreur profile:", err);
                showToast("Erreur de communication avec le serveur.", "error");
            }
        });
    }

    const sidebarProfileArea = document.querySelector('aside .border-t');
    if (sidebarProfileArea) {
        sidebarProfileArea.style.cursor = 'pointer';
        sidebarProfileArea.title = "Modifier mon profil";
        sidebarProfileArea.addEventListener('click', (e) => {
            if (!e.target.closest('#logoutBtn')) {
                openProfileModal();
            }
        });
    }
});

function deleteAccount() {
    showConfirmModal("Attention : Voulez-vous vraiment supprimer votre compte ? Cette action est irréversible.", async () => {
        try {
            const res = await fetch('api/profile.php', { method: 'DELETE' });
            const data = await res.json();
            if (data.success) {
                showToast("Compte supprimé.", "error");
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showToast(data.message || "Erreur", "error");
            }
        } catch (e) {
            showToast("Erreur lors de la suppression.", "error");
        }
    });
}

// Appel unique de vérification au chargement
checkAuth();