$(document).ready(function() {
  // ========================
  //   Paragraph Data Setup
  // ========================

  // Gather all paragraph elements on the page
  var $paragraphElems = $('.paragraph-content[data-audio-url]');
  // Build an array of paragraph info so we can jump from one to the next
  var paragraphList = [];
  $paragraphElems.each(function() {
    var $el = $(this);
    var pId = parseInt($el.data('paragraph-id'), 10);
    var cId = parseInt($el.data('chapter-id'), 10);
    var audioUrl = $el.data('audio-url');

    paragraphList.push({
      paragraphId: pId,
      chapterId: cId,
      audioUrl: audioUrl
    });
  });

  // This will let us know which paragraph index is currently playing
  var currentParagraphIndex = -1;

  // ========================
  //   Audio Player Setup
  // ========================
  var audioPlayer     = document.getElementById('audioPlayer');
  var $audioControl   = $('#audioControl');
  var $playPauseIcon  = $('#playPauseButton i'); // The icon inside the play/pause button

  // Show/hide the audio controls
  function showAudioControls() {
    $audioControl.removeClass('hidden');
  }
  function hideAudioControls() {
    $audioControl.addClass('hidden');
  }

  // Toggle play/pause icon
  function setPlayIcon(isPlaying) {
    if (isPlaying) {
      $playPauseIcon.removeClass('fa-play').addClass('fa-pause');
    } else {
      $playPauseIcon.removeClass('fa-pause').addClass('fa-play');
    }
  }

  // Smooth scroll to the given paragraph index
  function scrollToParagraph(index) {
    if (index < 0 || index >= paragraphList.length) return;
    var pId = paragraphList[index].paragraphId;
    var $paragraphDiv = $('#paragraph-' + pId);
    if ($paragraphDiv.length) {
      $('html, body').animate({
        scrollTop: $paragraphDiv.offset().top
      }, 500);
    }
  }

  // Play a specific paragraph by index
  function playParagraph(index) {
    if (index < 0 || index >= paragraphList.length) {
      // Out of range => stop playback, hide controls
      audioPlayer.pause();
      audioPlayer.currentTime = 0;
      hideAudioControls();
      setPlayIcon(false);
      currentParagraphIndex = -1;
      return;
    }

    currentParagraphIndex = index;
    var paragraphData = paragraphList[index];
    audioPlayer.src = paragraphData.audioUrl;
    showAudioControls();
    audioPlayer.play();
    setPlayIcon(true);

    // Scroll to that paragraph
    scrollToParagraph(index);
  }

  // When the audio ends, automatically go to the next paragraph
  audioPlayer.addEventListener('ended', function() {
    var nextIndex = currentParagraphIndex + 1;
    playParagraph(nextIndex);
  });

  // ========================
  //   Listen Now Button
  // ========================
  // Start from the very first paragraph (index 0)
  $('#listenNowBtn').click(function() {
    // Enable audio since the user explicitly clicked Listen Now
    window.audioEnabled = true;

    if (paragraphList.length > 0) {
      playParagraph(0);
    }
  });

  // ========================
  //   Chapter "Play" Button
  // ========================
  // Start from the first paragraph that belongs to that chapter
  $(document).on('click', '.play-chapter-btn', function(e) {
    e.stopPropagation();  // Prevent the parent item from also firing
    var chapterId = $(this).data('chapter-id');

    // Enable audio because the user clicked a Play Chapter button
    window.audioEnabled = true;

    // Find the first paragraph in paragraphList that matches this chapter
    var indexToPlay = paragraphList.findIndex(function(item) {
      return item.chapterId === chapterId;
    });
    if (indexToPlay !== -1) {
      playParagraph(indexToPlay);
    }
  });

  // ========================
  //   Clicking Paragraph Directly
  // ========================
  $('.paragraph-content').click(function(e) {
    // Only play audio if audioEnabled is true
    if (!window.audioEnabled) {
      return; // do nothing if user hasn't enabled audio
    }

    // Otherwise, proceed with paragraph playback
    var pId = $(this).data('paragraph-id');
    var indexToPlay = paragraphList.findIndex(function(item) {
      return item.paragraphId === pId;
    });
    if (indexToPlay !== -1) {
      playParagraph(indexToPlay);
    }
  });

  // ========================
  //   Play/Pause Button
  // ========================
  $('#playPauseButton').click(function() {
    if (audioPlayer.paused) {
      audioPlayer.play();
      setPlayIcon(true);
    } else {
      audioPlayer.pause();
      setPlayIcon(false);
    }
  });

  // ========================
  //   Scroll to Chapter on list item click (if not pressing play-chapter-btn)
  // ========================
  $(document).on('click', '.chapter-list-item', function(e) {
    // If the click target is the "Play Chapter" button or within it, do nothing
    if (
      $(e.target).hasClass('play-chapter-btn') ||
      $(e.target).closest('.play-chapter-btn').length
    ) {
      return;
    }
    // Otherwise, just scroll
    var chapterId = $(this).data('chapter-id');
    var indexOfChapter = paragraphList.findIndex(function(item) {
      return item.chapterId === chapterId;
    });
    if (indexOfChapter !== -1) {
      scrollToParagraph(indexOfChapter);
    }
  });

  // ========================
  //   Scroll to Top
  // ========================
  window.onscroll = function() {
    const scrollTopBtn = document.getElementById('scrollTopBtn');
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
      scrollTopBtn.style.display = "flex";
    } else {
      scrollTopBtn.style.display = "none";
    }
  };

  // Smooth scroll to top
  $('#scrollTopBtn').click(function() {
    $('html, body').animate({ scrollTop: 0 }, 'smooth');
  });


  // ========================
  //   3-dot Paragraph Menu (NEW)
  // ========================
  // Toggle the menu on clicking the 3-dot icon
  $(document).on('click', '.paragraph-menu-icon', function(e) {
    e.stopPropagation();

    // Hide any other open paragraph menus before toggling
    $('.paragraph-menu').not($(this).siblings('.paragraph-menu')).addClass('d-none');

    // Toggle the menu next to the icon
    $(this).siblings('.paragraph-menu').toggleClass('d-none');
  });

  // Close the 3-dot menu if clicking anywhere outside it
  $(document).on('click', function(e) {
    if (!$(e.target).closest('.paragraph-menu, .paragraph-menu-icon').length) {
      $('.paragraph-menu').addClass('d-none');
    }
  });
});
