// Function to handle the file drop
let pages = [];
var current_pos = 0;
function handleFileDrop(event) {
    event.preventDefault();
    const files = event.dataTransfer.files || event.target.files;
    if(files.length > 0){
      proces_pdf(files[0]);
    }else{
      proces_pdf(files);
    }
}
function addfilehandler(){
    document.getElementById('add_file_btn').addEventListener('change', function(event) {
    const files = event.target.files;
    if(files.length > 0){
      proces_pdf(files[0]);
    }else{
      proces_pdf(files);
    }
  });
}
function proces_pdf(pdf){
  const file = pdf;
  if (file.type === 'application/pdf') {
    // Read PDF file
    const reader = new FileReader();
    reader.onload = function (e) {
      const arrayBuffer = e.target.result;

      // Initialize PDF.js
      const PDFJS = window.pdfjsLib;
      PDFJS.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js';

      // Load PDF document
      PDFJS.getDocument({ data: arrayBuffer }).promise.then(function (pdf) {
        // Read text from each page
        
        function GetPageContent(pageNum) {
          if(pageNum > pdf.numPages){
            document.getElementById('page_options').style.display = 'flex';
            load_page(pages[current_pos]);
          }else{
            var page_content = '';
            pdf.getPage(pageNum).then(function (page) {
              return page.getTextContent();
            }).then(function (textContent) {
              const pageText = textContent.items.map(item => item.str).join('').trim();

              if (pageText !== '') {
                page_content += `\n${pageText}\n`;
                pages.push(page_content.toLowerCase());
                //console.log(page_content);
                //console.log(`Text from page ${pageNum}:\n`, pageText);
              } else {
                console.log(`No visible text on page ${pageNum}.`);
              }

            // Continue to the next page
            GetPageContent(pageNum + 1);
          });
          }
        }
        // Start loading pages from the first one
        GetPageContent(1);
    }).catch(function (error) {
      console.error('Error loading PDF:', error);
    });
  };
  reader.readAsArrayBuffer(file);
  } else {
    alert('Please drop a valid PDF file.');
  }
}

  function get_pages(){
    return pages;
  }
  function get_curent_pos(){
    return current_pos;
  }
  function load_page(pagecontent){
    const output = document.getElementById('input_holder');    
    output.value = pagecontent;
    output.scrollTop = '0';
    document.getElementById('page_count').innerText = 'Pagina: '+(current_pos+1)+'/'+pages.length;
    
  }
  function next_page(){
    if(current_pos < pages.length-1){
      current_pos++;
      load_page(pages[current_pos]);
    }else{
      console.log('last page reached');
      return 0;
    }
    
  }
  function previous_page(){
    if(current_pos >= 1){
      current_pos--;
      load_page(pages[current_pos]);
    }else{
      console.log('first page reached');
      return 0;
    }
    
  }
  // Set up the drop event listener
  const dropArea = document.body;
  if (dropArea) {
    dropArea.addEventListener('dragover', function (event) {
      event.preventDefault();
      dropArea.style.border = '2px dashed #aaa';
    });
  
    dropArea.addEventListener('dragleave', function () {
      dropArea.style.border = '2px dashed #ccc';
    });
  
    dropArea.addEventListener('drop', handleFileDrop);
  } else {
    console.error("Element with ID 'main_holder' not found.");
  }

  // Define a function to replace Romanian characters with their Unicode equivalents


  