<div class="np-learning-paths-resources carrot-padded-row row row-with-thumbnails">
  {% if items.any? %}
    {% assign sortedLearningPaths = items | sort: 'name' %}
    {% for learning_path in sortedLearningPaths %}
      {% assign language = 'en' %}
      {% for category in learning_path.categories %}
        {% if category.name contains '[lang]' %}
          {% assign language = category.name | remove: '[lang]' %}
          {% break %}
        {% endif %}
      {% endfor %}
      {% if current_person.properties.preferred_language == 'en' and language != 'en' %}
        {% continue %}
      {% endif %}

      <div
        class="col-xs-12 col-sm-6  np-stretch-content path-item"
        {% if forloop.index > 4 %}
        style="display: none;"
        {% endif %}>
        {% include "cards_learning_path_custom" with learning_path %}
      </div>
    {% endfor %}
    {% if items.size > 4 %}
      <div class="load-more-btn">
        <span class="lang-en">See More</span>
        <span class="lang-es">Ver Más</span>
      </div>
    {% endif %}
  {% else %}
    <div class="np-learning-paths-resources-container">
      <div class="np-zero-state-text">
        {% t.empty %}
      </div>
      <img class="np-zero-state-learning-paths" alt="{% t .empty %}" />
    </div>
  {% endif %}
</div>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Sort learning path items by progress (lowest first)
    const pathContainer = document.querySelector('.np-learning-paths-resources');
    if (pathContainer) {
      const pathItems = Array.from(pathContainer.querySelectorAll('.path-item'));
      const loadMoreBtn = pathContainer.querySelector('.load-more-btn');
      
      // Sort by progress (ascending order - lowest progress first)
      pathItems.sort(function(a, b) {
        const cardA = a.querySelector('.np-card');
        const cardB = b.querySelector('.np-card');
        
        if (!cardA || !cardB) return 0;
        
        const progressA = parseInt(cardA.getAttribute('progress')) || 0;
        const progressB = parseInt(cardB.getAttribute('progress')) || 0;
        
        return progressA - progressB; // Ascending order
      });
      
      // Remove load more button temporarily to preserve its position
      if (loadMoreBtn) {
        loadMoreBtn.remove();
      }
      
      // Reorder path items in the DOM
      pathItems.forEach(function(item) {
        pathContainer.appendChild(item);
      });
      
      // Re-add load more button at the end
      if (loadMoreBtn) {
        pathContainer.appendChild(loadMoreBtn);
      }
      
      // Reset visibility: show only first 4, hide the rest
      pathItems.forEach(function(item, index) {
        if (index < 4) {
          item.style.display = 'block';
        } else {
          item.style.display = 'none';
        }
      });
    }

    const loadMoreBtn = document.querySelector('.load-more-btn');
    if (!loadMoreBtn) return;

    const courseItems = document.querySelectorAll('.path-item');
    let currentlyVisible = 4;

    loadMoreBtn.addEventListener('click', function() {
      const nextItems = Array.from(courseItems).slice(currentlyVisible, currentlyVisible + 4);
      nextItems.forEach(item => item.style.display = 'block');
      
      currentlyVisible += 4;
      
      if (currentlyVisible >= courseItems.length) {
        loadMoreBtn.style.display = 'none';
      }
    });
  });

  // Listen for filter events
  {% if eventId %}
  document.addEventListener('filterUpdate', function(event) {
    if (event.detail.filterId === '{{ eventId }}') {
      const selectedCategories = event.detail.categoryValues || [];
      const selectedProgress = event.detail.progressValues || [];
      const pathItems = document.querySelectorAll('.path-item');
      const loadMoreBtn = document.querySelector('.load-more-btn');
      const filteredZeroState = document.querySelector('.filtered-zero-state');
      
      let visibleFilteredCount = 0;
      let totalFilteredCount = 0;
      
      pathItems.forEach(function(pathItem) {
        const card = pathItem.querySelector('.np-card');
        if (card) {
          const cardCategories = card.getAttribute('categories');
          const cardProgress = parseInt(card.getAttribute('progress')) || 0;
          let shouldShow = false;
          
          // Check category filter
          let categoryMatch = true;
          if (selectedCategories.length > 0) {
            categoryMatch = false;
            if (cardCategories) {
              const cardCategoryArray = cardCategories.split(',');
              categoryMatch = selectedCategories.some(selectedCat => 
                cardCategoryArray.some(cardCat => 
                  cardCat.trim().toLowerCase().includes(selectedCat.toLowerCase())
                )
              );
            }
          }
          
          // Check progress filter
          let progressMatch = true;
          if (selectedProgress.length > 0) {
            progressMatch = selectedProgress.some(selectedProg => {
              if (selectedProg === 'Not Started') {
                return cardProgress === 0;
              } else if (selectedProg === 'In Progress') {
                return cardProgress > 0 && cardProgress < 100;
              } else if (selectedProg === 'Completed') {
                return cardProgress === 100;
              }
              return false;
            });
          }
          
          // Show item if both filters match
          shouldShow = categoryMatch && progressMatch;
          
          if (shouldShow) {
            totalFilteredCount++;
            // Show only first 4 filtered items initially
            if (totalFilteredCount <= 4) {
              pathItem.style.display = 'block';
              visibleFilteredCount++;
            } else {
              pathItem.style.display = 'none';
            }
          } else {
            pathItem.style.display = 'none';
          }
        }
      });
      
      // Show/hide zero state for filtered results
      if (filteredZeroState) {
        if (totalFilteredCount === 0 && (selectedCategories.length > 0 || selectedProgress.length > 0)) {
          filteredZeroState.style.display = 'block';
        } else {
          filteredZeroState.style.display = 'none';
        }
      }
      
      // Update load more button visibility
      if (loadMoreBtn) {
        if (totalFilteredCount > 4) {
          loadMoreBtn.style.display = 'block';
        } else {
          loadMoreBtn.style.display = 'none';
        }
      }
      
      // Reset the load more functionality for filtered results
      let currentlyVisible = 4;
      if (loadMoreBtn) {
        loadMoreBtn.onclick = function() {
          const hiddenFilteredItems = Array.from(pathItems).filter(item => {
            const card = item.querySelector('.np-card');
            if (!card) return false;
            
            const cardCategories = card.getAttribute('categories');
            const cardProgress = parseInt(card.getAttribute('progress')) || 0;
            
            // Check category filter
            let categoryMatch = true;
            if (selectedCategories.length > 0) {
              categoryMatch = false;
              if (cardCategories) {
                const cardCategoryArray = cardCategories.split(',');
                categoryMatch = selectedCategories.some(selectedCat => 
                  cardCategoryArray.some(cardCat => 
                    cardCat.trim().toLowerCase().includes(selectedCat.toLowerCase())
                  )
                );
              }
            }
            
            // Check progress filter
            let progressMatch = true;
            if (selectedProgress.length > 0) {
              progressMatch = selectedProgress.some(selectedProg => {
                if (selectedProg === 'Not Started') {
                  return cardProgress === 0;
                } else if (selectedProg === 'In Progress') {
                  return cardProgress > 0 && cardProgress < 100;
                } else if (selectedProg === 'Completed') {
                  return cardProgress === 100;
                }
                return false;
              });
            }
            
            const shouldShow = categoryMatch && progressMatch;
            return shouldShow && item.style.display === 'none';
          });
          
          // Show next 4 items
          const nextItems = hiddenFilteredItems.slice(0, 4);
          nextItems.forEach(item => item.style.display = 'block');
          currentlyVisible += nextItems.length;
          
          // Hide load more if no more items
          if (hiddenFilteredItems.length <= 4) {
            loadMoreBtn.style.display = 'none';
          }
        };
      }
    }
  });
  {% endif %}
</script>