let audio_files = ["40_Matthew_01.mp3", "40_Matthew_02.mp3", ...]; // your audio files
let audio_folder = "ENGWEB_FCBH_NT_D";
let book_number = "40"; // Set default book number

function debounce(func, wait) {
  let timeout;
  return function() {
    const context = this, args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

const processScroll = () => {
  const audio = document.querySelector('audio');
  const waypoints = document.querySelectorAll('.c');
  const currentChapterDisplay = document.getElementById('currentChapter');
  const autoplayCheckbox = document.getElementById('autoplayCheck');

  console.log(`Current book number: ${book_number}`); // Debugging line

  waypoints.forEach(waypoint => {
    const waypointTop = waypoint.offsetTop;
    const viewportTop = window.scrollY;

    // Check if the waypoint top is at or near the top of the viewport
    if (waypointTop <= viewportTop + 150) {
      const waypointId = waypoint.id.slice(1);
      let waypointChapter = "";

      const found = audio_files.some(chapterFile => {
        if(chapterFile.startsWith(book_number)) {
            let chapterParts = chapterFile.split("_");
            let chapterNumber = chapterParts[chapterParts.length - 1].split('.')[0];
            chapterNumber = chapterNumber.replace(/^0+/, '');

            if(chapterNumber == waypointId) {
                waypointChapter = chapterFile;
                return true; 
            }
        }
        return false; 
      });

      if (found) {
        const newSource = `https://content.dbs.org/audio/${audio_folder}/${waypointChapter}`;
        currentChapterDisplay.textContent = waypointId;

        if (audio.src !== newSource) {
          audio.src = newSource;
          if (autoplayCheckbox.checked) {
            audio.play();
          }
        }
      }
    }
  });
};

window.addEventListener('scroll', debounce(processScroll, 100));

// Function to update book number
function updateBookNumber(selectedBookNumber) {
    book_number = selectedBookNumber;
    console.log(`Current book number set to: ${book_number}`);
}
