// File: public/js/home.js

$(document).ready(function() {
  // Variables to keep track of added translations
  var maxTranslations = 3;
  var addedTranslations = ['modern']; // Modern English is added by default

  // Function to update columns based on checkboxes
  function updateColumns() {
    // Iterate over each available translation
    ['original', 'modern', 'dutch'].forEach(function(translation) {
      var isChecked = $('#toggle-' + translation).is(':checked');

      if (isChecked) {
        $('.column-' + translation).removeClass('hidden');
      } else {
        $('.column-' + translation).addClass('hidden');
      }
    });

    // Ensure at least one column is visible
    var visibleColumns = $('.flex-item').not('.hidden').length;

    if (visibleColumns === 0) {
      // If no columns are visible, prompt the user and reset to default
      alert(alertMsgSelectColumn);
      // Re-check the modern column
      $('#toggle-modern').prop('checked', true);
      $('.column-modern').removeClass('hidden');
    }

    // Update cookies with the checked state
    var checkedTranslations = [];
    ['original', 'modern', 'dutch'].forEach(function(translation) {
      var isChecked = $('#toggle-' + translation).is(':checked');
      if (isChecked) {
        checkedTranslations.push(translation);
      }
    });
    // Store the checked translations in cookies
    document.cookie = "checkedTranslations=" + JSON.stringify(checkedTranslations) + "; path=/";
  }

  // On page load, adjust columns
  updateColumns();

  // Handle checkbox changes
  $(document).on('change', 'input[type="checkbox"][id^="toggle-"]', function() {
    var translation = $(this).attr('id').replace('toggle-', '');
    var isChecked = $(this).is(':checked');

    if (!isChecked && translation !== 'modern') {
      // Show confirmation modal
      var translationName = '';
      switch (translation) {
        case 'original':
          translationName = language === 'Dutch' ? 'Originele Engelse Vertaling' : 'Original English Translation';
          break;
        case 'dutch':
          translationName = language === 'Dutch' ? 'Nederlandse Vertaling' : 'Dutch Translation';
          break;
      }
      $('#removeTranslationModalBody').html(
        (language === 'Dutch' ? 'Weet u zeker dat u de ' : 'Are you sure you would like to remove the ') +
        '<strong>' + translationName + '</strong>?'
      );
      $('#removeTranslationModal').data('translation', translation).modal('show');
      // Uncheck the checkbox temporarily
      $(this).prop('checked', true);
    } else {
      updateColumns();
    }
  });

  // Handle confirmation of removal
  $('#confirmRemoveTranslation').click(function() {
    var translation = $('#removeTranslationModal').data('translation');
    // Remove the checkbox
    $('#toggle-' + translation).closest('label').remove();
    // Remove the translation from the addedTranslations array
    addedTranslations = addedTranslations.filter(function(item) {
      return item !== translation;
    });
    // Hide the column
    $('.column-' + translation).addClass('hidden');
    // Hide the modal
    $('#removeTranslationModal').modal('hide');

    // Update the columns
    updateColumns();
  });

  // Handle cancellation of removal
  $('#cancelRemoveTranslation').click(function() {
    $('#removeTranslationModal').modal('hide');
  });

  // Show the scroll-to-top button when scrolling down
  window.onscroll = function() {
    const scrollTopBtn = document.getElementById("scrollTopBtn");
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
      scrollTopBtn.style.display = "flex"; // Show button when scrolled down
    } else {
      scrollTopBtn.style.display = "none"; // Hide button when at the top
    }
  };

  // Smooth scroll to top
  document.getElementById("scrollTopBtn").onclick = function() {
    window.scrollTo({
      top: 0,
      behavior: "smooth"
    });
  };

  // Open the Add Translation modal
  $('#addTranslationBtn').click(function() {
    // Reset checkboxes in the modal
    $('#add-original').prop('checked', false);
    $('#add-dutch').prop('checked', false);

    // Hide the max translations alert
    $('#maxTranslationsAlert').hide();

    // Show the modal
    $('#addTranslationModal').modal('show');
  });

  // Handle adding translations
  $('#confirmAddTranslation').click(function() {
    var translationsToAdd = [];
    if ($('#add-original').is(':checked')) {
      translationsToAdd.push('original');
    }
    if ($('#add-dutch').is(':checked')) {
      translationsToAdd.push('dutch');
    }

    // Check if adding these translations would exceed max allowed
    if (addedTranslations.length + translationsToAdd.length > maxTranslations) {
      $('#maxTranslationsAlert').show();
      return;
    }

    translationsToAdd.forEach(function(translation) {
      if (!addedTranslations.includes(translation)) {
        addedTranslations.push(translation);

        // Add the checkbox
        var translationName = '';
        switch (translation) {
          case 'original':
            translationName = language === 'Dutch' ? 'Originele Engelse Vertaling' : 'Original English Translation';
            break;
          case 'dutch':
            translationName = language === 'Dutch' ? 'Nederlandse Vertaling' : 'Dutch Translation';
            break;
        }
        var checkboxHtml = '<label class="checkbox-inline mr-3">' +
          '<input type="checkbox" id="toggle-' + translation + '" checked> ' +
          translationName +
          '</label>';
        $('#translationCheckboxes').append(checkboxHtml);

        // Show the column
        $('.column-' + translation).removeClass('hidden');
      }
    });

    // Close the modal
    $('#addTranslationModal').modal('hide');

    // Update the columns
    updateColumns();
  });

  // Open the modal when the download button is clicked
  $('#downloadPdfBtn').click(function() {
    $('#translationModal').modal('show');
  });

  // Handle translation selection in the download modal
  $('#translationModal button[data-translation]').click(function() {
    var translation = $(this).data('translation');
    if (workId) {
      // Redirect to the download PDF URL
      window.location.href = baseUrl + '/home/downloadPdf/' + workId + '/' + translation + '?lang=' + language;
    }
  });

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

  // Handle the 'Listen Now' button click
  $('#listenNowBtn').click(function() {
    if (workId) {
      // Show loading indication
      $('#listenNowBtn').prop('disabled', true).text('Loading...');

      // Make AJAX request to get the combined audio URL
      $.ajax({
        url: baseUrl + '/home/playAudio/' + workId,
        method: 'GET',
        dataType: 'json',
        success: function(response) {
          // Enable the button and reset text
          $('#listenNowBtn').prop('disabled', false).text(language === 'Dutch' ? 'Luister Nu' : 'Listen Now');

          if (response.error) {
            alert(response.error);
          } else if (response.audioUrl) {
            // Set the audio source
            audioPlayer.src = response.audioUrl;

            // Show the audio control
            audioControl.removeClass('hidden');

            // Start playing the audio
            audioPlayer.play();

            // Update the play/pause icon to 'pause'
            playPauseButton.removeClass('fa-play').addClass('fa-pause');
          }
        },
        error: function(xhr, status, error) {
          // Enable the button and reset text
          $('#listenNowBtn').prop('disabled', false).text(language === 'Dutch' ? 'Luister Nu' : 'Listen Now');
          alert('An error occurred while processing your request.');
        }
      });
    }
  });

  // Handle the play button click next to each chapter using event delegation
  $(document).on('click', '.play-chapter-btn', function() {
    var chapterId = $(this).data('chapter-id');
    if (workId && chapterId) {
      // Show loading indication on the button
      $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');

      var button = $(this); // To reference the button later

      // Make AJAX request to get the combined audio URL starting from the chapter
      $.ajax({
        url: baseUrl + '/home/playAudioFromChapter/' + workId + '/' + chapterId,
        method: 'GET',
        dataType: 'json',
        success: function(response) {
          // Enable the button and reset text
          button.prop('disabled', false).html('<i class="fas fa-play"></i>');

          if (response.error) {
            alert(response.error);
          } else if (response.audioUrl) {
            // Set the audio source
            audioPlayer.src = response.audioUrl;

            // Show the audio control
            audioControl.removeClass('hidden');

            // Start playing the audio
            audioPlayer.play();

            // Update the play/pause icon to 'pause'
            playPauseButton.removeClass('fa-play').addClass('fa-pause');
          }
        },
        error: function(xhr, status, error) {
          // Enable the button and reset text
          button.prop('disabled', false).html('<i class="fas fa-play"></i>');
          alert('An error occurred while processing your request.');
        }
      });
    }
  });

  // Handle play/pause button click
  $('#playPauseButton').click(function() {
    if (audioPlayer.paused) {
      audioPlayer.play();
      // Update icon to 'pause'
      playPauseButton.removeClass('fa-play').addClass('fa-pause');
    } else {
      audioPlayer.pause();
      // Update icon to 'play'
      playPauseButton.removeClass('fa-pause').addClass('fa-play');
    }
  });

  // Hide the audio control when the audio ends
  audioPlayer.addEventListener('ended', function() {
    audioControl.addClass('hidden');
    // Reset the audio to the beginning (optional)
    audioPlayer.currentTime = 0;
    // Update icon to 'play'
    playPauseButton.removeClass('fa-pause').addClass('fa-play');
  });

  // Restore checked state from cookies
  function getCookie(name) {
    var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
    return match ? match[1] : null;
  }

  var checkedTranslations = getCookie('checkedTranslations');
  checkedTranslations = checkedTranslations ? JSON.parse(checkedTranslations) : [];

  // Set the checked state of checkboxes based on cookies
  ['original', 'dutch'].forEach(function(translation) {
    if (checkedTranslations.includes(translation.toString())) {
      $('#toggle-' + translation).prop('checked', true);
      if (!addedTranslations.includes(translation)) {
        addedTranslations.push(translation);
      }
    } else {
      $('#toggle-' + translation).prop('checked', false);
    }
  });

  // Update columns based on restored checked state
  updateColumns();

  // Handle click on note icon
  $(document).on('click', '.note-icon', function() {
    var paragraphId = $(this).data('paragraph-id');

    if (paragraphData[paragraphId]) {
      // Get the paragraph_cleaned and v2_notes
      var originalText = paragraphData[paragraphId].paragraph_cleaned;
      var aiNotes = paragraphData[paragraphId].v2_notes;

      // Process 'originalText' to preserve line breaks and escape HTML
var originalTextHtml = $('<div/>').text(originalText).html().replace(/\n/g, '<br>');
$('#originalTranslationContent').html(originalTextHtml);

// Process 'aiNotes' with Marked.js and sanitize with DOMPurify
var aiNotesHtml = DOMPurify.sanitize(marked.parse(aiNotes));
$('#aiNotesContent').html(aiNotesHtml);
      // Show the modal
      $('#translationNotesModal').modal('show');
    }
  });

}); // End of document ready function