// State Management
let cards = [];
let shuffledCards = [];
let currentCardIndex = 0;
let isShuffled = false;
let leitnerBoxes = [[], [], []];
let activeSessionCards = [];
let isSessionActive = false;

// DOM Elements
const leitnerSelector = document.getElementById('leitner-selector');
const input = document.getElementById('markdown-input');
const cardsGrid = document.getElementById('cards-grid');
const printGridWrapper = document.getElementById('print-grid-wrapper');
const revisionCard = document.getElementById('revision-card');
const cardCounter = document.getElementById('card-counter');
const views = {
    editor: document.getElementById('editor-container'),
    preview: document.getElementById('preview-container'),
    revision: document.getElementById('revision-container')
};
const buttons = {
    editor: document.getElementById('view-editor-btn'),
    preview: document.getElementById('view-preview-btn'),
    revision: document.getElementById('view-revision-btn'),
    shuffle: document.getElementById('shuffle-btn'),
    print: document.getElementById('print-btn'),
    copyLink: document.getElementById('copy-link-btn')
};

const DEFAULT_CONTENT = `fond: bleu
## Bienvenue sur FlashiX
C'est votre outil pour créer des flashcards en Markdown !
#### Intro
---
fond: vert
## Les formules mathématiques
Vous pouvez utiliser LaTeX : 

$x = \\\\frac{-b \\\\pm \\\\sqrt{b^2 - 4ac}}{2a}$
#### Math
---
fond: orange
## Les Images
![Logo](https://marked.js.org/img/logo-black.js.svg)
#### Médias
---
fond: violet
## Les étiquettes
Regardez en bas à droite de cette carte.
#### Étiquette`;

// Initialize
async function init() {
    input.addEventListener('input', () => {
        updateCards();
        saveToURL();
    });

    // Editor Toolbar
    document.getElementById('insert-image-btn').addEventListener('click', () => document.getElementById('image-input').click());
    document.getElementById('image-input').addEventListener('change', handleImageUpload);
    document.getElementById('insert-image-link-btn').addEventListener('click', insertImageLink);
    document.getElementById('insert-excalidraw-btn').addEventListener('click', openExcalidraw);
    document.getElementById('insert-math-btn').addEventListener('click', insertMath);

    // Excalidraw Modal
    document.getElementById('close-excalidraw').addEventListener('click', closeExcalidraw);
    document.getElementById('save-excalidraw-btn').addEventListener('click', saveExcalidraw);
    window.addEventListener('click', (e) => {
        if (e.target === document.getElementById('excalidraw-modal')) closeExcalidraw();
    });

    // Drag and Drop for Editor
    input.addEventListener('dragover', (e) => {
        e.preventDefault();
        input.classList.add('dragover');
    });
    input.addEventListener('dragleave', () => input.classList.remove('dragover'));
    input.addEventListener('drop', (e) => {
        e.preventDefault();
        input.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0 && files[0].type.startsWith('image/')) {
            processImageFile(files[0]);
        }
    });

    // Navigation
    buttons.editor.addEventListener('click', () => switchView('editor'));
    buttons.preview.addEventListener('click', () => switchView('preview'));
    buttons.revision.addEventListener('click', () => switchView('revision'));

    // Controls
    buttons.shuffle.addEventListener('click', toggleShuffle);
    buttons.print.addEventListener('click', printCards);
    buttons.copyLink.addEventListener('click', copyShareLink);
    document.getElementById('copy-revision-link-btn').addEventListener('click', copyRevisionLink);

    // About Modal Logic
    const aboutBtn = document.getElementById('about-btn');
    const aboutModal = document.getElementById('about-modal');
    const closeBtn = document.querySelector('.close-modal');

    aboutBtn.addEventListener('click', () => aboutModal.classList.remove('hidden'));
    closeBtn.addEventListener('click', () => aboutModal.classList.add('hidden'));
    window.addEventListener('click', (e) => {
        if (e.target === aboutModal) aboutModal.classList.add('hidden');
    });

    // Revision Controls
    document.getElementById('prev-card-btn').addEventListener('click', prevCard);
    document.getElementById('next-card-btn').addEventListener('click', nextCard);
    document.getElementById('start-session-btn').addEventListener('click', startSession);
    document.getElementById('leitner-fail-btn').addEventListener('click', () => handleLeitner(false));
    document.getElementById('leitner-success-btn').addEventListener('click', () => handleLeitner(true));
    document.getElementById('box1-sel').addEventListener('change', renderRevisionCard);
    document.getElementById('box2-sel').addEventListener('change', renderRevisionCard);
    document.getElementById('box3-sel').addEventListener('change', renderRevisionCard);
// Dans init(), modifier le comportement de retournement de carte pour afficher les boutons
    revisionCard.addEventListener('click', () => {
        revisionCard.classList.toggle('flipped');
        if (isSessionActive && revisionCard.classList.contains('flipped')) {
            document.getElementById('leitner-controls').style.display = 'flex';
        } else {
            document.getElementById('leitner-controls').style.display = 'none';
        }
    });

    // Keyboard Controls for Revision
    document.addEventListener('keydown', (e) => {
        if (!views.revision.classList.contains('hidden')) {
            if (isSessionActive) {
                // Bloquer les flèches pendant la série
                if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
                    e.preventDefault();
                    return;
                }
            }
            if (e.key === 'ArrowLeft') {
                prevCard();
            } else if (e.key === 'ArrowRight') {
                nextCard();
            } else if (e.key === ' ' || e.key === 'Enter') {
                e.preventDefault();
                revisionCard.classList.toggle('flipped');
                if (isSessionActive && revisionCard.classList.contains('flipped')) {
                    document.getElementById('leitner-controls').style.display = 'flex';
                } else {
                    document.getElementById('leitner-controls').style.display = 'none';
                }
            }
        }
    });

    // Handle Query Parameters
    const params = new URLSearchParams(window.location.search);
    if (params.has('e') && params.get('e') === '0') {
        document.getElementById('view-editor-btn').classList.add('hidden');
        switchView('preview');
    }
    if (params.has('r') && params.get('r') === '1') {
        document.getElementById('toolbar').style.display = 'none';
        switchView('revision');
    }
    if (params.has('aléatoire')) {
        toggleShuffle();
    }
    if (params.has('révision')) {
        switchView('revision');
    }

    // Load from URL or Set Default
    const loaded = await loadFromURL();
    if (!loaded) {
        input.value = DEFAULT_CONTENT;
    }
    updateCards();
    initLeitner();
}

// Card Parsing
function updateCards() {
    const text = input.value;
    cards = parseMarkdown(text);
    shuffledCards = [...cards];
    if (isShuffled) shuffleArray(shuffledCards);

    renderGrids();
    renderRevisionCard();
}

function parseMarkdown(text) {
    const parsedCards = [];
    // Découpage par séparateur --- OU par changement de couleur (fond:)
    // On utilise un lookahead pour découper sans perdre les séparateurs si nécessaire, 
    // mais ici un découpage simple par `---` est suffisant, 
    // et on va aussi découper au niveau des `fond:` si `---` est absent.
    const segments = text.split(/^---$/gm);

    let currentColor = 'gris';

    segments.forEach((seg) => {
        // Sous-découpage si on trouve plusieurs 'fond:' dans un segment (cas où --- était absent)
        const subSegments = seg.split(/(?=^fond:\s*\w+)/m);

        subSegments.forEach(s => {
            const trimmedS = s.trim();
            if (!trimmedS) return;

            // Détection de la couleur au sein du bloc
            const colorMatch = trimmedS.match(/^fond:\s*(\w+)/m);
            if (colorMatch) {
                currentColor = colorMatch[1].toLowerCase();
            }

            const lines = trimmedS.split('\n');
            let rectoText = null;
            let versoLines = [];
            let labelText = '';
            let foundRecto = false;

            for (let i = 0; i < lines.length; i++) {
                const line = lines[i];
                const trimmedLine = line.trim();

                // On saute la ligne de fond:
                if (trimmedLine.startsWith('fond:')) continue;

                if (!foundRecto && trimmedLine.startsWith('## ')) {
                    rectoText = trimmedLine.substring(3).trim();
                    foundRecto = true;
                    continue;
                }

                if (foundRecto) {
                    if (trimmedLine.startsWith('#### ')) {
                        labelText = trimmedLine.substring(5).trim();
                        break;
                    }
                    versoLines.push(line);
                }
            }

            if (rectoText !== null) {
                parsedCards.push({
                    recto: rectoText,
                    verso: versoLines.join('\n').trim(),
                    label: labelText,
                    color: currentColor
                });
            }
        });
    });
    return parsedCards;
}

// Rendering
function renderGrids() {
    cardsGrid.innerHTML = '';
    printGridWrapper.innerHTML = '';

    const displayCards = isShuffled ? shuffledCards : cards;

    displayCards.forEach(card => {
        cardsGrid.appendChild(createCardElement(card, 'recto'));
        cardsGrid.appendChild(createCardElement(card, 'verso'));
    });

    const printList = [...displayCards];
    while (printList.length % 8 !== 0) {
        printList.push({
            recto: '',
            verso: '',
            label: '',
            color: ''
        });
    }

    for (let i = 0; i < printList.length; i += 8) {
        const chunk = printList.slice(i, i + 8);

        const pageRecto = document.createElement('div');
        pageRecto.className = 'grid print-page';
        chunk.forEach(card => pageRecto.appendChild(createCardElement(card, 'recto')));
        printGridWrapper.appendChild(pageRecto);

        const pageVerso = document.createElement('div');
        pageVerso.className = 'grid print-page';
        const swappedChunk = [];
        for (let j = 0; j < 8; j += 2) {
            swappedChunk.push(chunk[j + 1]);
            swappedChunk.push(chunk[j]);
        }
        swappedChunk.forEach(card => pageVerso.appendChild(createCardElement(card, 'verso')));
        printGridWrapper.appendChild(pageVerso);
    }

    if (typeof renderMathInElement !== 'undefined') {
        // Centralise la configuration pour éviter de te répéter
        const mathConfig = {
            delimiters: [{
                left: "$$",
                right: "$$",
                display: true
            }, {
                left: "$",
                right: "$",
                display: false
            }]
        };

        // Rendu pour l'aperçu écran actuel
        renderMathInElement(document.getElementById('preview-container'), mathConfig);

        // AJOUT : Rendu pour le conteneur d'impression caché
        renderMathInElement(document.getElementById('print-grid-wrapper'), mathConfig);
    }

    if (!views.preview.classList.contains('hidden')) {
        autoScaleText(document.getElementById('preview-container'));
    }
}

function createCardElement(card, side) {
    const cardDiv = document.createElement('div');
    cardDiv.className = 'card';
    if (card.color) cardDiv.classList.add(`fond-${card.color}`);
    if (!card.recto && !card.verso) cardDiv.style.visibility = 'hidden';

    // Étiquette automatique de côté (Haut Gauche)
    const sideLabel = document.createElement('div');
    sideLabel.className = 'card-label label-top-left';
    sideLabel.textContent = side === 'recto' ? 'Q' : 'R';
    cardDiv.appendChild(sideLabel);

    const contentDiv = document.createElement('div');
    contentDiv.className = 'card-content';

    const rawContent = side === 'recto' ? card.recto : card.verso;
    contentDiv.innerHTML = marked.parse(rawContent);

    if (side === 'recto' && card.label) {
        const labelBottom = document.createElement('div');
        labelBottom.className = 'card-label label-bottom-right';
        labelBottom.textContent = card.label;
        cardDiv.appendChild(labelBottom);
    }

    cardDiv.appendChild(contentDiv);
    return cardDiv;
}

function renderRevisionCard() {
    // Filtrage des cartes par boîtes sélectionnées
    const selectedBoxes = [];
    if (document.getElementById('box1-sel').checked) selectedBoxes.push(0);
    if (document.getElementById('box2-sel').checked) selectedBoxes.push(1);
    if (document.getElementById('box3-sel').checked) selectedBoxes.push(2);

    let filteredIndices = [];
    selectedBoxes.forEach(boxIdx => {
        filteredIndices.push(...leitnerBoxes[boxIdx]);
    });

    // Si aucune boîte sélectionnée, on affiche rien
    if (filteredIndices.length === 0) {
        cardCounter.textContent = '0 / 0';
        revisionCard.querySelector('.card-front').innerHTML = 'Sélectionnez au moins une boîte';
        revisionCard.querySelector('.card-back').innerHTML = '';
        return;
    }

    // Mélange ou ordre original
    if (isShuffled) shuffleArray(filteredIndices);

    if (currentCardIndex >= filteredIndices.length) currentCardIndex = 0;

    const originalIndex = filteredIndices[currentCardIndex];
    const card = cards[originalIndex];
    const front = revisionCard.querySelector('.card-front');
    const back = revisionCard.querySelector('.card-back');

    front.innerHTML = '';
    back.innerHTML = '';
    revisionCard.classList.remove('flipped');

    const frontEl = createCardElement(card, 'recto');
    const backEl = createCardElement(card, 'verso');

    front.appendChild(frontEl);
    back.appendChild(backEl);

    cardCounter.textContent = `${currentCardIndex + 1} / ${filteredIndices.length}`;

    if (typeof renderMathInElement !== 'undefined') {
        renderMathInElement(revisionCard, {
            delimiters: [{
                left: "$$",
                right: "$$",
                display: true
            }, {
                left: "$",
                right: "$",
                display: false
            }]
        });
    }

    if (!views.revision.classList.contains('hidden')) {
        autoScaleText(revisionCard);
    }
}

function nextCard() {
    const displayCards = isShuffled ? shuffledCards : cards;
    if (displayCards.length === 0) return;
    currentCardIndex = (currentCardIndex + 1) % displayCards.length;
    renderRevisionCard();
}

function prevCard() {
    const displayCards = isShuffled ? shuffledCards : cards;
    if (displayCards.length === 0) return;
    currentCardIndex = (currentCardIndex - 1 + displayCards.length) % displayCards.length;
    renderRevisionCard();
}

function switchView(viewName) {
    Object.keys(views).forEach(v => {
        views[v].classList.toggle('hidden', v !== viewName);
        buttons[v].classList.toggle('active', v === viewName);
    });

    if (viewName === 'preview') {
        autoScaleText(document.getElementById('preview-container'));
    } else if (viewName === 'revision') {
        renderRevisionCard(); // Refléter les boîtes sélectionnées
        autoScaleText(revisionCard);
    }
}

function toggleShuffle() {
    isShuffled = !isShuffled;
    buttons.shuffle.classList.toggle('active', isShuffled);
    if (isShuffled) {
        shuffleArray(shuffledCards);
    }
    currentCardIndex = 0;
    renderGrids();
    renderRevisionCard();
}

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

function autoScaleText(container) {
    const contents = container.querySelectorAll('.card-content');
    if (contents.length === 0) return;

    const isVisible = container.offsetWidth > 0 || container.offsetHeight > 0;
    if (!isVisible) return;

    contents.forEach(content => {
        let min = 8;
        let max = 60;
        let lastBest = min;

        while (min <= max) {
            let mid = Math.floor((min + max) / 2);
            content.style.fontSize = mid + 'px';
            if (content.scrollHeight <= content.offsetHeight && content.scrollWidth <= content.offsetWidth) {
                lastBest = mid;
                min = mid + 1;
            } else {
                max = mid - 1;
            }
        }
        content.style.fontSize = lastBest + 'px';
    });
}

function printCards() {
    const printGridWrapper = document.getElementById('print-grid-wrapper');
    const previewContainer = document.getElementById('preview-container');

    const wasPreviewHidden = previewContainer.classList.contains('hidden');
    const wasPrintHidden = printGridWrapper.classList.contains('hidden');

    const tempStyle = document.createElement('style');
    tempStyle.innerHTML = `
        #preview-container.measure-mode {
            display: block !important;
            visibility: visible !important;
            position: absolute !important;
            left: -9999px !important;
            top: 0 !important;
            height: auto !important;
            width: 210mm !important;
        }
        #print-grid-wrapper.measure-mode {
            display: block !important;
            visibility: visible !important;
        }
    `;
    document.head.appendChild(tempStyle);

    previewContainer.classList.add('measure-mode');
    printGridWrapper.classList.add('measure-mode');

    const cards = printGridWrapper.querySelectorAll('.card');
    cards.forEach(card => {
        card.style.width = '90mm';
        card.style.height = '60mm';
    });

    setTimeout(() => {
        autoScaleText(printGridWrapper);
        document.head.removeChild(tempStyle);
        previewContainer.classList.remove('measure-mode');
        printGridWrapper.classList.remove('measure-mode');

        window.print();

        if (wasPreviewHidden) previewContainer.classList.add('hidden');
        if (wasPrintHidden) printGridWrapper.classList.add('hidden');

        cards.forEach(card => {
            card.style.width = '';
            card.style.height = '';
        });
    }, 200);
}

function saveToURL() {
    const text = input.value;
    const compressed = LZString.compressToEncodedURIComponent(text);
    window.location.hash = compressed;
}

async function loadFromURL() {
    // Check for ?f= parameter
    const params = new URLSearchParams(window.location.search);
    if (params.has('f')) {
        const url = params.get('f');
        try {
            const response = await fetch(url);
            const text = await response.text();
            if (text) {
                input.value = text;
                updateCards();
                return true;
            }
        } catch (e) {
            console.error('Failed to fetch from external file URL', e);
        }
    }

    if (window.location.hash) {
        const hash = window.location.hash.substring(1);
        if (!hash) return false;

        if (hash.startsWith('http')) {
            try {
                const response = await fetch(hash);
                const text = await response.text();
                if (text) {
                    input.value = text;
                    updateCards();
                    return true;
                }
            } catch (e) {
                console.error('Failed to fetch from external URL', e);
            }
        }

        try {
            const decompressed = LZString.decompressFromEncodedURIComponent(hash);
            if (decompressed) {
                input.value = decompressed;
                updateCards();
                return true;
            }
        } catch (e) {
            console.log("Not LZ-String, trying Base64 fallback...");
        }

        try {
            const decoded = decodeURIComponent(escape(atob(hash)));
            if (decoded) {
                input.value = decoded;
                updateCards();
                return true;
            }
        } catch (e) {
            console.error('Failed to decode from hash', e);
        }
    }
    return false;
}

function copyShareLink() {
    saveToURL();
    const url = window.location.href;
    navigator.clipboard.writeText(url).then(() => {
        const originalText = buttons.copyLink.textContent;
        buttons.copyLink.textContent = 'Lien copié ! ✓';
        buttons.copyLink.classList.add('active');
        setTimeout(() => {
            buttons.copyLink.textContent = originalText;
            buttons.copyLink.classList.remove('active');
        }, 2000);
    }).catch(err => {
        console.error('Erreur lors de la copie : ', err);
        alert("Impossible de copier le lien.");
    });
}

function copyRevisionLink() {
    saveToURL();
    const baseUrl = window.location.origin + window.location.pathname;
    const hash = window.location.hash;
    const revisionUrl = `${baseUrl}?r=1${hash}`;

    const btn = document.getElementById('copy-revision-link-btn');
    navigator.clipboard.writeText(revisionUrl).then(() => {
        const originalText = btn.textContent;
        btn.textContent = 'Lien Révision copié ! ✓';
        btn.classList.add('active');

        setTimeout(() => {
            btn.textContent = originalText;
            btn.classList.remove('active');
        }, 2000);
    }).catch(err => {
        console.error('Erreur lors de la copie : ', err);
        alert("Impossible de copier le lien.");
    });
}

function insertAtCursor(text) {
    const start = input.selectionStart;
    const end = input.selectionEnd;
    const val = input.value;
    input.value = val.substring(0, start) + text + val.substring(end);
    input.selectionStart = input.selectionEnd = start + text.length;
    input.focus();
    updateCards();
    saveToURL();
}

function insertMath() {
    insertAtCursor('$ E= {1 \\over 2} \\times m \\times v^2 $');
}

// Excalidraw Integration
let excalidrawAPI = null;
let excalidrawRoot = null;

function openExcalidraw() {
    const modal = document.getElementById('excalidraw-modal');
    modal.classList.remove('hidden');

    if (typeof ExcalidrawLib === 'undefined') {
        alert("La bibliothèque Excalidraw n'est pas encore chargée. Veuillez patienter ou rafraîchir la page.");
        return;
    }

    if (!excalidrawRoot) {
        const {
            Excalidraw
        } = ExcalidrawLib;
        const container = document.getElementById('excalidraw-container');
        excalidrawRoot = ReactDOM.createRoot(container);

        const App = () => {
            return React.createElement(
                "div", {
                    style: {
                        height: "100%"
                    }
                },
                React.createElement(Excalidraw, {
                    excalidrawAPI: (api) => {
                        excalidrawAPI = api;
                    },
                    langCode: "fr-FR",
                    scrollToContent: true,
                    UIOptions: {
                        canvasActions: {
                            loadScene: false,
                            saveToActiveFile: false,
                            export: false,
                            saveAsImage: false
                        }
                    }
                })
            );
        };
        excalidrawRoot.render(React.createElement(App));
    }
}

function closeExcalidraw() {
    document.getElementById('excalidraw-modal').classList.add('hidden');
}

async function saveExcalidraw() {
    if (!excalidrawAPI) {
        alert("L'éditeur n'est pas prêt.");
        return;
    }

    const elements = excalidrawAPI.getSceneElements();
    if (!elements || elements.length === 0) {
        alert("Le dessin est vide !");
        return;
    }

    const {
        exportToBlob
    } = ExcalidrawLib;

    try {
        const blob = await exportToBlob({
            elements: elements,
            appState: excalidrawAPI.getAppState(),
            files: excalidrawAPI.getFiles(),
            mimeType: "image/webp",
            quality: 0.8
        });

        const reader = new FileReader();
        reader.onloadend = function() {
            const img = new Image();
            img.onload = function() {
                const resizedBase64 = resizeImage(img);
                insertAtCursor(`![dessin](${resizedBase64})`);
                closeExcalidraw();
                excalidrawAPI.updateScene({
                    elements: []
                });
            };
            img.src = reader.result;
        }
        reader.readAsDataURL(blob);
    } catch (error) {
        console.error("Erreur lors de l'export Excalidraw:", error);
        alert("Erreur lors de la génération de l'image.");
    }
}

function resizeImage(img) {
    const canvas = document.createElement('canvas');
    const maxWidth = 400;
    const maxHeight = 300;

    let scale = Math.min(maxWidth / img.width, maxHeight / img.height, 1);

    canvas.width = img.width * scale;
    canvas.height = img.height * scale;

    const ctx = canvas.getContext('2d');
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

    let base64 = canvas.toDataURL('image/webp', 0.65);
    if (!base64.startsWith('data:image/webp')) {
        base64 = canvas.toDataURL('image/jpeg', 0.7);
    }
    return base64;
}

// Leitner Logic
function initLeitner() {
    const key = 'leitner_' + window.location.hash;
    const saved = localStorage.getItem(key);
    if (saved) {
        leitnerBoxes = JSON.parse(saved);
    } else {
        leitnerBoxes = [cards.map((_, i) => i), [], []];
        saveLeitner();
    }
    updateLeitnerUI();
}

function saveLeitner() {
    const key = 'leitner_' + window.location.hash;
    localStorage.setItem(key, JSON.stringify(leitnerBoxes));
    updateLeitnerUI();
}

function updateLeitnerUI() {
    const c1 = document.getElementById('count-b1');
    const c2 = document.getElementById('count-b2');
    const c3 = document.getElementById('count-b3');
    if (c1) c1.textContent = leitnerBoxes[0].length;
    if (c2) c2.textContent = leitnerBoxes[1].length;
    if (c3) c3.textContent = leitnerBoxes[2].length;
}

function startSession() {
    const selectedBoxes = [];
    if (document.getElementById('box1-sel').checked) selectedBoxes.push(0);
    if (document.getElementById('box2-sel').checked) selectedBoxes.push(1);
    if (document.getElementById('box3-sel').checked) selectedBoxes.push(2);

    activeSessionCards = [];
    selectedBoxes.forEach(boxIdx => {
        activeSessionCards.push(...leitnerBoxes[boxIdx]);
    });

    if (activeSessionCards.length === 0) {
        revisionCard.querySelector('.card-front').innerHTML = '<div class="card"><div class="card-content">Aucune carte à réviser !</div></div>';
        revisionCard.querySelector('.card-back').innerHTML = '';
        cardCounter.textContent = '0 / 0';
        return;
    }

    if (isShuffled) shuffleArray(activeSessionCards);
    isSessionActive = true;
    currentCardIndex = 0;
    
    document.getElementById('prev-card-btn').disabled = true;
    document.getElementById('next-card-btn').disabled = true;
    document.getElementById('revision-controls').classList.add('hidden');
    leitnerSelector.classList.add('hidden');
    renderSessionCard();
}

function renderSessionCard() {
    const originalIndex = activeSessionCards[currentCardIndex];
    const card = cards[originalIndex];
    
    const front = revisionCard.querySelector('.card-front');
    const back = revisionCard.querySelector('.card-back');

    front.innerHTML = '';
    back.innerHTML = '';
    revisionCard.classList.remove('flipped');

    const frontEl = createCardElement(card, 'recto');
    const backEl = createCardElement(card, 'verso');

    front.appendChild(frontEl);
    back.appendChild(backEl);

    cardCounter.textContent = `${currentCardIndex + 1} / ${activeSessionCards.length}`;

    if (typeof renderMathInElement !== 'undefined') {
        renderMathInElement(revisionCard, {
            delimiters: [{ left: "$$", right: "$$", display: true }, { left: "$", right: "$", display: false }]
        });
    }
    autoScaleText(revisionCard);
}

function handleLeitner(success) {
    if (!isSessionActive) {
        alert("Veuillez cliquer sur 'Lancer la série' pour commencer.");
        return;
    }

    // Cacher les boutons
    document.getElementById('leitner-controls').style.display = 'none';

    const originalIndex = activeSessionCards[currentCardIndex];
    
    let sourceBox = -1;
    for (let i = 0; i < 3; i++) {
        if (leitnerBoxes[i].includes(originalIndex)) {
            sourceBox = i;
            break;
        }
    }

    leitnerBoxes[sourceBox].splice(leitnerBoxes[sourceBox].indexOf(originalIndex), 1);
    
    if (success) {
        let nextBox = Math.min(sourceBox + 1, 2);
        leitnerBoxes[nextBox].push(originalIndex);
    } else {
        let prevBox = Math.max(sourceBox - 1, 0);
        leitnerBoxes[prevBox].push(originalIndex);
    }

    saveLeitner();

    currentCardIndex++;
    if (currentCardIndex >= activeSessionCards.length) {
        endSession();
    } else {
        renderSessionCard();
    }
}

function endSession() {
    isSessionActive = false;
    document.getElementById('prev-card-btn').disabled = false;
    document.getElementById('next-card-btn').disabled = false;
    document.getElementById('revision-controls').classList.remove('hidden');
    document.getElementById('leitner-controls').style.display = 'none';
    leitnerSelector.classList.remove('hidden');
    revisionCard.querySelector('.card-front').innerHTML = 'Série terminée !';
    revisionCard.querySelector('.card-back').innerHTML = '';
    cardCounter.textContent = '0 / 0';
}

function insertImageLink() {
    const url = prompt("Entrez l'URL de l'image :");
    if (url) {
        insertAtCursor(`![image](${url})`);
    }
}

function handleImageUpload(e) {
    const file = e.target.files[0];
    if (!file) return;
    processImageFile(file);
    e.target.value = '';
}

function processImageFile(file) {
    const reader = new FileReader();
    reader.onload = function(event) {
        const img = new Image();
        img.onload = function() {
            const base64 = resizeImage(img);
            insertAtCursor(`![image](${base64})`);
        };
        img.src = event.target.result;
    };
    reader.readAsDataURL(file);
}

window.addEventListener('load', () => {
    init();
});

