'use strict';

$(function () { // jQuery document ready

  // --- Selectors ---
  const categoryFilter = $('#filter-category');
  const hideCompletedSwitch = $('#filter-hide-completed');
  const courseGrid = $('#my-courses-grid');
  const courseCards = $('.course-card-wrapper');
  const noCoursesMessage = $('#noCoursesMessage');

  // --- Initialize Plugins ---
  if (categoryFilter.length) {
    categoryFilter.select2({
      placeholder: pageData.labels.allCategories,
      allowClear: true,
    });
  }

  // --- Filtering Function ---
  function filterCourses() {
    const selectedCategory = categoryFilter.val();
    const hideCompleted = hideCompletedSwitch.is(':checked');

    let visibleCount = 0;

    courseCards.each(function() {
      const card = $(this);
      const cardCategory = card.data('category-id')?.toString() || '';
      const cardCompleted = card.data('completed') === true || card.data('completed') === 'true';

      let matchesCategory = !selectedCategory || cardCategory === selectedCategory;
      let matchesCompleted = !hideCompleted || !cardCompleted;

      if (matchesCategory && matchesCompleted) {
        card.show();
        visibleCount++;
      } else {
        card.hide();
      }
    });

    // Show/hide the "no courses" message based on visibility
    if (visibleCount === 0) {
      noCoursesMessage.text(pageData.labels.noCoursesMatch).show();
    } else {
      noCoursesMessage.hide();
    }
  }

  // --- Event Listeners for Filters ---
  categoryFilter.on('change', filterCourses);
  hideCompletedSwitch.on('change', filterCourses);

}); // End Document Ready
