'use strict';

$(function () { // jQuery document ready

  // --- Global Variables & Selectors ---
  const lessonsListContainer = $('#lessonsListContainer');
  const noLessonsMessage = $('#noLessonsMessage');
  let sortableLessonsInstance = null;
  let sortableChecklistInstance = null;

  // Offcanvas & Form Elements
  const lessonOffcanvasElement = $('#lessonOffcanvas');
  const lessonOffcanvas = lessonOffcanvasElement.length ? new bootstrap.Offcanvas(lessonOffcanvasElement[0]) : null;
  const lessonForm = $('#lessonForm');
  const lessonOffcanvasLabel = $('#lessonOffcanvasLabel');
  const submitLessonBtn = $('#submitLessonBtn');
  const lessonIdInput = $('#lesson_id');
  const lessonMethodInput = $('#lessonMethod');

  // Form Fields
  const lessonTitleInput = $('#lessonTitle');
  const contentTypeSelect = $('#content_type');
  const contentTextGroup = $('#contentTextGroup');
  const contentTextInput = $('#content_text');
  const contentFileGroup = $('#contentFileGroup');
  const lessonFileInput = $('#lesson_file');
  const currentFileDisplay = $('#currentLessonFileDisplay');
  const removeFileCheckArea = $('#removeFileCheckArea');
  const removeFileCheckbox = $('#remove_file');
  const generalErrorDiv = $('#general-error');

  // Buttons
  const addLessonBtn = $('#addLessonBtn');

  // --- CSRF Setup ---
  $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': pageData.csrfToken } });

  // --- Initialize Plugins ---

  // Select2 for Content Type in Offcanvas
  if (contentTypeSelect.length) {
    contentTypeSelect.select2({
      placeholder: pageData.labels.selectContentType,
      dropdownParent: $(lessonOffcanvasElement).find('.offcanvas-body'),
      minimumResultsForSearch: Infinity
    });
  }

  // --- Helper Functions ---

  // Show/Hide specific content input group based on selected type
  function toggleContentInputs(selectedType) {
    contentTextGroup.hide();
    contentFileGroup.hide();
    contentTextInput.removeClass('is-invalid').siblings('.invalid-feedback').text('');
    lessonFileInput.removeClass('is-invalid').siblings('.invalid-feedback').text('');

    if (!selectedType) return;

    if (['text', 'video_embed', 'link'].includes(selectedType)) {
      contentTextGroup.show();
      let placeholder = 'Enter text content...';
      let label = 'Content';
      if (selectedType === 'video_embed') { placeholder = 'Paste YouTube/Vimeo embed code...'; label = 'Embed Code';}
      else if (selectedType === 'link') { placeholder = 'Enter full URL starting with https://...'; label = 'External Link URL';}
      contentTextGroup.find('label').text(`${label} *`);
      contentTextInput.attr('placeholder', placeholder);

    } else if (['file', 'video_file'].includes(selectedType)) {
      contentFileGroup.show();
    }
  }

  // Reset Validation
  function resetLessonFormValidation() {
    lessonForm.find('.is-invalid').removeClass('is-invalid');
    lessonForm.find('.invalid-feedback').text('').hide();
    lessonForm.find('.select2-container').removeClass('is-invalid');
    generalErrorDiv.text('').hide();
  }

  // Reset Form Content
  function resetLessonForm() {
    resetLessonFormValidation();
    lessonForm[0]?.reset();
    lessonIdInput.val('');
    lessonMethodInput.val('POST');
    contentTypeSelect.val(null).trigger('change');
    toggleContentInputs('');
    currentFileDisplay.text('').hide();
    removeFileCheckArea.hide();
    lessonOffcanvasLabel.text(pageData.labels.addNewLesson);
    submitLessonBtn.text(pageData.labels.submit).prop('disabled', false);
  }

  // Set Button Loading State
  function setLessonButtonLoading(isLoading) {
    const buttonText = lessonIdInput.val() ? pageData.labels.update : pageData.labels.submit;
    submitLessonBtn.prop('disabled', isLoading);
    submitLessonBtn.html(isLoading ? '<span class="spinner-border spinner-border-sm"></span> ' + pageData.labels.processing : buttonText);
  }

  // Display Validation Errors
  function displayLessonValidationErrors(errors) {
    resetLessonFormValidation();
    let firstErrorElement = null;
    console.log("Validation Errors:", errors);
    for (const fieldName in errors) {
      let inputName = fieldName;
      let errorMessage = errors[fieldName][0];
      if (inputName === 'lesson_file') inputName = 'lesson_file';

      const inputElement = lessonForm.find(`[name="${inputName}"]`);
      let targetElement = inputElement;
      let feedbackElement = targetElement.closest('.mb-3').find('.invalid-feedback');

      if (!inputElement.length) { generalErrorDiv.append(`<div>${escapeHtml(inputName)}: ${escapeHtml(errorMessage)}</div>`).show(); if (!firstErrorElement) firstErrorElement = generalErrorDiv; continue; }
      if (inputElement.hasClass('select2-hidden-accessible')) { targetElement = inputElement.siblings('.select2-container'); }
      else if (inputElement.attr('type') === 'file') { targetElement = inputElement; }

      if (targetElement.length) {
        targetElement.addClass('is-invalid');
        if(feedbackElement.length) { feedbackElement.text(errorMessage).show(); }
        else { targetElement.after(`<div class="invalid-feedback d-block">${errorMessage}</div>`); }
        if (!firstErrorElement) firstErrorElement = targetElement;
      }
    }
    firstErrorElement?.focus();
    if (firstErrorElement?.hasClass('select2-container')) { firstErrorElement.prev('select').select2('open'); }
  }

  // Basic HTML escaping helper
  function escapeHtml(unsafe) {
    if (typeof unsafe !== 'string') return '';
    return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
  }

  // --- Initialize SortableJS for Lesson List ---
  function initLessonSortable() {
    if (sortableChecklistInstance) { sortableChecklistInstance.destroy(); }
    if (lessonsListContainer.length && typeof Sortable !== 'undefined') {
      sortableChecklistInstance = new Sortable(lessonsListContainer[0], {
        handle: '.lesson-handle',
        animation: 150,
        ghostClass: 'sortable-ghost',
        onEnd: function (evt) {
          const itemElements = lessonsListContainer.find('.lesson-item');
          const newOrderIds = itemElements.map(function() {
            return $(this).data('lesson-id');
          }).get();

          saveLessonOrder(newOrderIds);
        }
      });
    } else if (typeof Sortable === 'undefined') {
      console.warn("SortableJS library not found. Lesson reordering disabled.");
    }
  }
  initLessonSortable();

  // --- Save Lesson Order ---
  function saveLessonOrder(orderedIds) {
    $.ajax({
      url: pageData.urls.reorder,
      method: 'POST',
      data: {
        orderedLessonIds: orderedIds,
      },
      dataType: 'json',
      success: function(response) {
        if (response.success) {
          showSuccessToast(response.message || pageData.labels.orderSaved);
        } else {
          showErrorToast(response.message || pageData.labels.failedToSaveOrder);
          location.reload();
        }
      },
      error: function(jqXHR) {
        console.error('Error saving lesson order:', jqXHR);
        showErrorToast(pageData.labels.couldNotSaveOrder);
        location.reload();
      }
    });
  }

  // --- Offcanvas Handling ---
  if(lessonOffcanvasElement.length) { lessonOffcanvasElement.on('hidden.bs.offcanvas', resetLessonForm); }

  // Add Lesson Button Click
  $('#addLessonBtn').on('click', function () {
    resetLessonForm();
    lessonOffcanvasLabel.text(pageData.labels.addNewLesson);
    contentTypeSelect.val('').trigger('change');
    toggleContentInputs('');
    lessonOffcanvas?.show();
  });

  // Edit Lesson Button Click (Event Delegation)
  lessonsListContainer.on('click', '.edit-lesson', function () {
    const lessonId = $(this).data('id');
    const editUrl = `${pageData.urls.base}/${lessonId}/edit`;

    resetLessonForm();
    lessonOffcanvasLabel.text(pageData.labels.loadingData);
    lessonOffcanvas?.show();

    $.ajax({
      url: editUrl, type: 'GET', dataType: 'json',
      success: function (response) {
        if (response.success && response.lesson) {
          const data = response.lesson;
          lessonOffcanvasLabel.text(pageData.labels.editLesson + ': ' + (data.title || `#${data.id}`));
          lessonIdInput.val(data.id);
          lessonMethodInput.val('PUT');

          lessonTitleInput.val(data.title || '');
          contentTypeSelect.val(data.content_type || '').trigger('change');
          contentTextInput.val(data.content_text || '');
          if(data.current_file_name) {
            currentFileDisplay.text(`${pageData.labels.currentFile}: ${data.current_file_name}`).show();
            removeFileCheckArea.show();
            removeFileCheckbox.prop('checked', false);
          } else {
            currentFileDisplay.text('').hide();
            removeFileCheckArea.hide();
          }
          toggleContentInputs(data.content_type);

        } else { lessonOffcanvas?.hide(); showErrorToast(response.message || pageData.labels.failedToLoadData); }
      },
      error: function (jqXHR) { console.error("Edit error:", jqXHR); lessonOffcanvas?.hide(); showErrorToast(pageData.labels.couldNotLoadData); }
    });
  });

  // --- Conditional Input Display based on Content Type ---
  contentTypeSelect.on('change', function() {
    toggleContentInputs($(this).val());
  });

  // --- Form Submission (Add/Edit) ---
  if (lessonForm.length) {
    lessonForm.on('submit', function(e) {
      e.preventDefault();
      resetLessonFormValidation();

      const isUpdate = !!lessonIdInput.val();
      const url = isUpdate ? `${pageData.urls.base}/${lessonIdInput.val()}` : pageData.urls.store;
      const method = 'POST';
      let formData = new FormData(lessonForm[0]);

      if (isUpdate) {
        formData.append('_method', 'PUT');
        if (!removeFileCheckbox.is(':checked')) { formData.delete('remove_file'); }
        else { formData.set('remove_file', '1'); }
      } else {
        formData.delete('remove_file');
      }

      const selectedType = contentTypeSelect.val();
      if (['text', 'video_embed', 'link'].includes(selectedType)) {
        formData.delete('lesson_file');
      } else if (['file', 'video_file'].includes(selectedType)) {
        if(formData.get('content_text') === '') formData.delete('content_text');
        if (isUpdate && lessonFileInput[0].files.length === 0 && !removeFileCheckbox.is(':checked')) {
          formData.delete('lesson_file');
        }
      } else {
        formData.delete('content_text');
        formData.delete('lesson_file');
      }


      setLessonButtonLoading(true);

      $.ajax({
        url: url, method: method, data: formData,
        processData: false, contentType: false, dataType: 'json',
        success: function (response) {
          if (response.success) {
            lessonOffcanvas?.hide();
            showSuccessToast(response.message);
            location.reload();
          } else { showErrorToast(response.message || pageData.labels.operationFailed); }
        },
        error: function (jqXHR) {
          if (jqXHR.status === 422 && jqXHR.responseJSON?.errors) { displayLessonValidationErrors(jqXHR.responseJSON.errors); showErrorToast(pageData.labels.validationFailed);}
          else { showErrorToast(jqXHR.responseJSON?.message || pageData.labels.anErrorOccurred); }
        },
        complete: function () { setLessonButtonLoading(false); }
      });
    });
  }

  // --- Delete Lesson Handling ---
  lessonsListContainer.on('click', '.delete-lesson', function () {
    const button = $(this);
    const lessonId = button.data('id');
    const deleteUrl = `${pageData.urls.base}/${lessonId}`;

    Swal.fire({
      title: pageData.labels.areYouSure, text: pageData.labels.deleteLessonWarning, icon: 'warning',
      showCancelButton: true, confirmButtonText: pageData.labels.yesDeleteIt,
      customClass: { confirmButton: 'btn btn-danger me-3', cancelButton: 'btn btn-label-secondary' }, buttonsStyling: false
    }).then(function (result) {
      if (result.isConfirmed) {
        $.ajax({
          url: deleteUrl, method: 'POST', data: { _method: 'DELETE' }, dataType: 'json',
          success: function(response) {
            if (response.success) {
              showSuccessToast(response.message);
              button.closest('.lesson-item').remove();
              if (lessonsListContainer.find('.lesson-item').length === 0) {
                lessonsListContainer.html(`<div id="noLessonsMessage" class="text-center text-muted p-4">${pageData.labels.noLessonsYet}</div>`);
              }
            } else { showErrorToast(response.message || pageData.labels.failedToDelete); }
          },
          error: function(jqXHR) { showErrorToast(jqXHR.responseJSON?.message || pageData.labels.failedToDelete); }
        });
      }
    });
  });


}); // End Document Ready
