'use strict';

$(function () {

  // --- Selectors ---
  const lessonListContainer = document.getElementById('lesson-list-container');
  const lessonContentArea = document.getElementById('lesson-content-area');
  // Specific content divs
  const textContentDiv = document.getElementById('lesson-text-content');
  const videoPlayerContainer = document.getElementById('lesson-video-player-container');
  const videoPlayerElement = document.getElementById('lesson-video-player');
  const pdfContentDiv = document.getElementById('lesson-pdf-content');
  const pdfLink = document.getElementById('lesson-pdf-link');
  const linkContentDiv = document.getElementById('lesson-external-link-content');
  const externalLink = document.getElementById('lesson-external-link');
  const quizContentDiv = document.getElementById('lesson-quiz-content');
  const initialMessageDiv = document.getElementById('lesson-initial-message');
  // Progress indicator
  const progressIndicator = document.getElementById('lesson-progress-indicator');

  let plyrInstance = null;

  // --- Initialize Plyr ---
  if (videoPlayerElement && typeof Plyr !== 'undefined') {
    try {
      plyrInstance = new Plyr(videoPlayerElement);
    } catch (e) { console.error("Plyr initialization error:", e); }
  } else if (typeof Plyr === 'undefined'){
    console.warn("Plyr library not found.");
  }

  // --- Helper: Update Progress Display ---
  function updateProgressIndicator() {
    if (!progressIndicator || !lessonListContainer) return;
    const totalLessons = lessonListContainer.querySelectorAll('.lesson-item').length;
    const completedLessons = lessonListContainer.querySelectorAll('.lesson-complete-toggle:checked').length;
    progressIndicator.textContent = `${completedLessons} / ${totalLessons} ${pageData.labels.lessonsCompleted}`;
  }
  updateProgressIndicator();


  // --- Helper: Show Active Content Area ---
  function showContentArea(areaToShow) {
    [initialMessageDiv, textContentDiv, videoPlayerContainer, pdfContentDiv, linkContentDiv, quizContentDiv].forEach(div => {
      if (div) div.style.display = 'none';
    });
    if (areaToShow !== videoPlayerContainer && plyrInstance && !plyrInstance.isDestroyed) {
      try {plyrInstance.stop(); plyrInstance.source = null;} catch(e){}
    }

    if (areaToShow) areaToShow.style.display = 'block';
  }


  // --- Event Listener: Lesson Link Click ---
  if (lessonListContainer) {
    lessonListContainer.addEventListener('click', function (event) {
      const lessonLink = event.target.closest('.lesson-link');
      if (!lessonLink) return;

      event.preventDefault();

      const lessonItem = lessonLink.closest('.lesson-item');
      if (!lessonItem) return;

      const lessonId = lessonItem.dataset.lessonId;
      const contentType = lessonItem.dataset.contentType;
      const contentData = lessonItem.dataset.contentData;
      const lessonTitle = lessonItem.dataset.lessonTitle;

      // Highlight active lesson
      lessonListContainer.querySelectorAll('.lesson-item.active').forEach(el => el.classList.remove('active'));
      lessonItem.classList.add('active');

      // --- Display Content Based on Type ---
      showContentArea(null);

      switch (contentType) {
        case 'text':
        case 'video_embed':
          if (textContentDiv) {
            textContentDiv.innerHTML = contentData || `<p>${pageData.labels.noContentAvailable}</p>`;
            showContentArea(textContentDiv);
          }
          break;

        case 'video_file':
          if (videoPlayerContainer && plyrInstance && contentData) {
            try {
              plyrInstance.source = {
                type: 'video',
                sources: [{ src: contentData, type: 'video/mp4' }],
              };
              showContentArea(videoPlayerContainer);
            } catch (e) {
              console.error("Error setting Plyr source:", e);
              showContentArea(initialMessageDiv);
              showErrorToast(pageData.labels.couldNotLoadVideo);
            }
          } else {
            showContentArea(initialMessageDiv);
            showErrorToast(pageData.labels.videoPlayerNotReady);
          }
          break;

        case 'file_upload':
        case 'file':
          if (pdfContentDiv && pdfLink && contentData) {
            pdfLink.href = contentData;
            pdfLink.innerHTML = `${pageData.labels.viewDownloadFile} <i class="bx bx-link-external ms-1"></i>`;
            showContentArea(pdfContentDiv);
          }
          break;
        case 'link':
          const targetDiv = (contentType === 'file_upload') ? pdfContentDiv : linkContentDiv;
          const targetLink = (contentType === 'file_upload') ? pdfLink : externalLink;
          const linkText = (contentType === 'file_upload') ? pageData.labels.downloadViewFile : pageData.labels.openLink;

          if (targetDiv && targetLink && contentData) {
            targetLink.href = contentData;
            targetLink.innerHTML = `${linkText} <i class="bx bx-link-external ms-1"></i>`;
            showContentArea(targetDiv);
          } else {
            showContentArea(initialMessageDiv);
            showErrorToast(pageData.labels.linkFileMissing);
          }
          break;

        case 'quiz':
          if (quizContentDiv) showContentArea(quizContentDiv);
          break;

        default:
          if (initialMessageDiv) showContentArea(initialMessageDiv);
          console.warn(`Unknown or unhandled content type: ${contentType}`);
      }
    });
  }


  // --- Event Listener: Mark Lesson Complete Checkbox ---
  if (lessonListContainer) {
    lessonListContainer.addEventListener('change', async function (event) {
      const checkbox = event.target;
      if (!checkbox || !checkbox.classList.contains('lesson-complete-toggle')) {
        return;
      }

      const lessonId = checkbox.dataset.lessonId;
      const isChecked = checkbox.checked;
      const lessonItem = checkbox.closest('.lesson-item');

      if (!lessonId) return;

      checkbox.disabled = true;
      const originalState = !isChecked;

      const url = pageData.urls.markCompleteTemplate.replace(':lessonId', lessonId);

      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'X-CSRF-TOKEN': pageData.csrfToken,
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
        });

        const data = await response.json();

        if (!response.ok || !data.success) {
          throw new Error(data.message || pageData.labels.couldNotSaveProgress);
        }

        lessonItem?.classList.toggle('completed', isChecked);
        updateProgressIndicator();

      } catch (error) {
        console.error("Error marking lesson complete:", error);
        showErrorToast(error.message || pageData.labels.couldNotSaveProgress);
        checkbox.checked = originalState;
        lessonItem?.classList.toggle('completed', originalState);
      } finally {
        checkbox.disabled = false;
      }
    });
  }

}); // End DOMContentLoaded
