/**
 * @name Inline Notes
 * @author Julien Bidoret
 * @author Julie Blanc <contact@julie-blanc.fr>
 * @see { @link https://gitlab.com/csspageweaver/plugins/inlineNotes }
 */

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

export default class inlineNotes extends Handler {

  constructor(chunker, polisher, caller) {
    super(chunker, polisher, caller);
    this.input = cssPageWeaver.features.inlineNotes.parameters?.input || ".footnote-ref"; // ← CSS selector of the call element 
    this.containerNotes = cssPageWeaver.features.inlineNotes.parameters?.containerNotes || "#footnotes"; // ← CSS selector of the container of the footnote
    this.newClass = cssPageWeaver.features.inlineNotes.parameters?.newClass || "inline-note"; // ← Class of the span create for the note
  }

  beforeParsed(content) {

    inlineNotesHandler({
        content: content,
        input: this.input,
        containerNotes: this.containerNotes,
        type: this.newClass
    });

  }
}



function inlineNotesHandler(params){

  let content = params.content;
  let input = params.input;
  let type = params.type;
  
  createNotes(content, input, type);

   let noteContainer = content.querySelector(params.containerNotes);
   if(noteContainer){
      noteContainer.remove();
   }

}


function getBlocks(element){
   return element.querySelectorAll('div,p,blockquote,section,article,h1,h2,h3,h4,h5,h6,figure');
}

// get only inline-level tags
function unwrapBlockChildren(element) {
   let blocks = getBlocks(element);
   
   blocks.forEach(block => {
       block.insertAdjacentHTML("beforebegin", block.innerHTML);
       block.remove();
   });
   let remainingblocks = getBlocks(element);
   if(remainingblocks.length) unwrapBlockChildren(element);
   return element;
}


function createNotes(content, input, type){

   let calls = content.querySelectorAll(input);
   calls.forEach( (call, index) => {

       let href = call.getAttribute('href');
       let hashIndex = href.indexOf('#');
       let selector = href.slice(hashIndex);

       let note = content.querySelector(selector);
       if (!note) {
         console.warn('Note non trouvée pour', selector);
         return;
       }

       let back = note.querySelector(".footnote-back");
       if(back){
          back.remove();
       }
      
       let inline_note = document.createElement('span');
       inline_note.className = type;
       let num = index + 1;
       inline_note.dataset.counterNote = num;

       inline_note.innerHTML = unwrapBlockChildren(note).innerHTML;
       call.after(inline_note);

       call.parentElement.removeChild(call);

   })
}
