import { Handler } from '/csspageweaver/lib/paged.esm.js';

export default class SectionedFootnotes extends Handler {
    constructor(chunker, polisher, caller) {
        super(chunker, polisher, caller);
    }

    beforeParsed(content){

        const sectionContent = content.querySelector('#section__content');
        const footnotesSection = content.querySelector('#footnotes');

        if (!sectionContent || !footnotesSection) {
            console.warn("Section content ou footnotes non trouvé");
            return;
        }

        const originalOl = footnotesSection.querySelector('ol');
        if (!originalOl) {
            console.warn("Liste de footnotes non trouvée");
            return;
        }

        const allH1s = sectionContent.querySelectorAll('h1');

        const noteToPartMap = new Map();

        allH1s.forEach((h1, partIndex) => {
            // Trouver le prochain h1 ou la fin de la section
            const nextH1 = allH1s[partIndex + 1];

            // Récupérer tous les éléments entre ce h1 et le suivant
            let current = h1.nextElementSibling;
            while (current && current !== nextH1) {
                // Chercher les footnote-ref dans cet élément
                const refs = current.querySelectorAll('.footnote-ref');
                refs.forEach(ref => {
                    const href = ref.getAttribute('href');
                    if (href && href.startsWith('#fn')) {
                        const noteNum = href.replace('#fn', '');
                        noteToPartMap.set(noteNum, partIndex);
                    }
                });
                if (current.classList && current.classList.contains('footnote-ref')) {
                    const href = current.getAttribute('href');
                    if (href && href.startsWith('#fn')) {
                        const noteNum = href.replace('#fn', '');
                        noteToPartMap.set(noteNum, partIndex);
                    }
                }
                current = current.nextElementSibling;
            }
        });

        const notesByPart = new Map();
        const allNotes = originalOl.querySelectorAll('li[id^="fn"]');

        allNotes.forEach(note => {
            const noteId = note.getAttribute('id');
            const noteNum = noteId.replace('fn', '');
            const partIndex = noteToPartMap.get(noteNum);

            if (partIndex !== undefined) {
                if (!notesByPart.has(partIndex)) {
                    notesByPart.set(partIndex, []);
                }
                notesByPart.get(partIndex).push({
                    num: parseInt(noteNum),
                    element: note
                });
            }
        });

        const sortedParts = Array.from(notesByPart.keys()).sort((a, b) => a - b);

        // Vider la section footnotes (garder le hr s'il existe)
        const hr = footnotesSection.querySelector('hr');
        footnotesSection.innerHTML = '';
        if (hr) {
            footnotesSection.appendChild(hr);
        }

        // Add title section
        const mainTitle = document.createElement('h1');
        mainTitle.textContent = 'Notizen';
        footnotesSection.appendChild(mainTitle);

        sortedParts.forEach(partIndex => {
            const h1 = allH1s[partIndex];
            const notes = notesByPart.get(partIndex);

            notes.sort((a, b) => a.num - b.num);

            if (notes.length > 0) {
                // Upper-alpha counter
                const titlePart = document.createElement('h2');
                titlePart.className = 'title-part';
                const letter = String.fromCharCode(65 + partIndex); // 65 = 'A'
                titlePart.setAttribute('data-part-number', letter);
                titlePart.textContent = h1.textContent.trim();
                footnotesSection.appendChild(titlePart);

                // New ol with new start
                const newOl = document.createElement('ol');
                const firstNoteNum = notes[0].num;
                newOl.setAttribute('start', firstNoteNum);

                notes.forEach(noteData => {
                    newOl.appendChild(noteData.element.cloneNode(true));
                });

                footnotesSection.appendChild(newOl);
            }
        });

        sectionContent.parentNode.insertBefore(footnotesSection, sectionContent.nextSibling);

    }

    
  
}


