{% include "header"
  , color: "var(--nintex--color--blue)"
  , text_color: "white"
  , text_en_US: "Learning paths"
  , subtitle_en_US: "Earn your Nintex certification by enrolling in a curated set of courses to move your knowledge <br> and skills to the next level."
  , text_es: "Explorar nuestras rutas de aprendizaje propuestas"
  , subtitle_es: "Lorem ipsum dolor sit amet"
  , text_fr: "Explorer nos parcours d'apprentissage proposés"
  , subtitle_fr: "Lorem ipsum dolor sit amet"
  , text_de: "Unsere vorgeschlagenen Lernpfade erkunden"
  , subtitle_de: "Lorem ipsum dolor sit amet"
  , text_en_GB: "Explore our proposed learning paths"
  , subtitle_en_GB: "Lorem ipsum dolor sit amet"
  , text_nl: "Ontdek onze voorgestelde leerpaden"
  , subtitle_nl: "Lorem ipsum dolor sit amet"
  , text_pt_BR: "Explorar nossos caminhos de aprendizagem propostos"
  , subtitle_pt_BR: "Lorem ipsum dolor sit amet"
  , button_text_en_US: ""
  , button_text_es: ""
  , button_text_fr: ""
  , button_text_de: ""
  , button_text_en_GB: ""
  , button_text_nl: ""
  , button_text_pt_BR: ""
  , button_link: "" %}
{% include "sub_navigation" %}

{% assign is_partner = false %}
{% for group in current_person.groups %}
  {% if group.name == "All Partners" %}
    {% assign is_partner = true %}
  {% endif %}
{% endfor %}

<main class="np-main np-subpage-container nintex-fw-container">
  <div class="np-learning-paths-main">
    <div class="np-resource-title">
      <span class="lang-en-US">Learning paths</span>
      <span class="lang-es">Rutas de aprendizaje</span>
      <span class="lang-fr">Parcours d'apprentissage </span>
      <span class="lang-de">Lernpfade</span>
      <span class="lang-en-GB">Learning paths</span>
      <span class="lang-nl">Leerpaden</span>
      <span class="lang-pt-BR">Caminhos de aprendizagem </span>
    </div>
    {% comment %} <div class="np-resource-subtitle">
      <span class="lang-en-US">{% t.subtitle %}</span>
      <span class="lang-es">Lorem ipsum dolor sit amet</span>
      <span class="lang-fr">Lorem ipsum dolor sit amet</span>
      <span class="lang-de">Lorem ipsum dolor sit amet</span>
      <span class="lang-en-GB">Lorem ipsum dolor sit amet</span>
      <span class="lang-nl">Lorem ipsum dolor sit amet</span>
      <span class="lang-pt-BR">Lorem ipsum dolor sit amet</span> {% endcomment %}
    </div>
    {% if learning_paths.available.any? %}
      <div class="nintex-filters-line">
        <div class="nintex-filters-input-wrapper">
          <i class="far fa-search"></i>
          <input
            type="text"
            placeholder="Search..."
            class="nintex-filters-input"
            id="name-search">
        </div>
        <select class="nintex-filters-select" id="product-filter">
          <option value="">All products</option>
          {% assign categories = "" %}
          {% for path in learning_paths.available %}
            {% for category in path.categories %}
              {% if category.name contains "Nintex Partner Sales" and is_partner == false %}
                {% continue %}
              {% endif %}
              {% unless categories contains category.name %}
                {% if category.name contains "[Product]" %}
                  {% assign categories = categories | append: category.name | append: "," %}
                  {% assign category_name = category.name | replace: "[Product]", "" %}
                  <option value="{{ category_name }}">{{ category_name }}</option>
                {% endif %}
              {% endunless %}
            {% endfor %}
          {% endfor %}
        </select>
        <select class="nintex-filters-select" id="status-filter">
          <option value="">All statuses</option>
          <option value="not_started">Not started</option>
          <option value="in_progress">In progress</option>
          <option value="completed">Completed</option>
        </select>
        <select class="nintex-filters-select" id="sort-filter">
          <option value="">Sort by</option>
          <option value="date_desc">Release Date (Newest First)</option>
          <option value="date_asc">Release Date (Oldest First)</option>
          <option value="name_asc">Name (A-Z)</option>
          <option value="name_desc">Name (Z-A)</option>
        </select>
        <select class="nintex-filters-select" id="skill-filter">
          <option value="">All skill levels</option>
          <option value="[Skill Level]100 - Beginner">Beginner</option>
          <option value="[Skill Level]200 - Intermediate">Intermediate</option>
          <option value="[Skill Level]300 - Advanced">Advanced</option>
          <option value="[Skill Level]400 - Solutions">Solutions</option>
        </select>
      </div>
    {% endif %}
    <div id="learning-paths-container">
      {% include "learning_paths_index"
        , items: learning_paths.available
        ,filter_partners: true,
        , classes: "col-xs-12 col-md-6 col-lg-4" %}
    </div>

    <!-- Pagination Controls -->
    <div
      class="nintex-btns-container"
      id="pagination-controls"
      style="display: none;">
      <div class="nintex-pagination-numbers" id="page-numbers"></div>
      <button
        id="prev-page"
        class="nintex-text-button"
        disabled>
        <i class="fas fa-chevron-left"></i>
        <span class="lang-en-US"></span>Previous</span>
        <span class="lang-es">Anterior</span>
        <span class="lang-fr">Précédent</span>
        <span class="lang-de">Vorherige</span>
        <span class="lang-en-GB">Previous</span>
        <span class="lang-nl">Vorige</span>
        <span class="lang-pt-BR">Anterior</span>
      </button>

      <button
        id="next-page"
        class="nintex-text-button"
        disabled>
        <span class="lang-en-US"></span>Next</span>
        <span class="lang-es">Siguiente</span>
        <span class="lang-fr">Suivant</span>
        <span class="lang-de">Nächste</span>
        <span class="lang-en-GB">Next</span>
        <span class="lang-nl">Volgende</span>
        <span class="lang-pt-BR">Próximo</span>
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>
  </div>
</main>


<script>
  let currentPage = 1;
  const itemsPerPage = 6;
  let filteredAndSortedCards = [];


  function handleFilterChange() {
    const filters = {
      name: document.getElementById('name-search').value,
      product: document.getElementById('product-filter').value,
      status: document.getElementById('status-filter').value,
      sort: document.getElementById('sort-filter').value,
      skill: document.getElementById('skill-filter').value
    }
    
    // Get all cards and apply filters
    const allCards = document.querySelectorAll('.nintex-card');
    const visibleCards = [];
    
    allCards.forEach(card => {
      let displayCard = true;

      const isPartnerCard = card.getAttribute('categories')?.includes("Nintex Partner Sales");
      if (!{{ is_partner }} && isPartnerCard) {
        displayCard = false;
      }
      
      if (filters.name && !card.textContent.toLowerCase().includes(filters.name.toLowerCase())) {
        displayCard = false;
      }
      if (filters.product && !card.getAttribute('categories').includes(filters.product)) {
        displayCard = false;
      }
      if (filters.skill && !card.getAttribute('categories').includes(filters.skill)) {
        displayCard = false;
      }
      if(filters.status){
        const progress = Number(card.getAttribute('progress'));
        if(filters.status === 'not_started' && progress !== 0){
          displayCard = false;
        }
        if(filters.status === 'in_progress' && (progress === 0 || progress === 100)){
          displayCard = false;
        }
        if(filters.status === 'completed' && progress !== 100){
          displayCard = false;
        }
      }
      
      if(displayCard){
        visibleCards.push(card.parentElement);
      }
    });

    // Apply sorting if specified
    if (filters.sort && visibleCards.length > 0) {
      visibleCards.sort((a, b) => {
        const cardA = a.querySelector('.nintex-card');
        const cardB = b.querySelector('.nintex-card');
        
        if (filters.sort === 'date_desc') {
          const createdAtA = new Date(cardA.getAttribute('created-at'));
          const createdAtB = new Date(cardB.getAttribute('created-at'));
          return createdAtB - createdAtA; // Newest first
        } else if (filters.sort === 'date_asc') {
          const createdAtA = new Date(cardA.getAttribute('created-at'));
          const createdAtB = new Date(cardB.getAttribute('created-at'));
          return createdAtA - createdAtB; // Oldest first
        } else if (filters.sort === 'name_asc') {
          const nameA = cardA.querySelector('.card-title').textContent.trim();
          const nameB = cardB.querySelector('.card-title').textContent.trim();
          return nameA.localeCompare(nameB);
        } else if (filters.sort === 'name_desc') {
          const nameA = cardA.querySelector('.card-title').textContent.trim();
          const nameB = cardB.querySelector('.card-title').textContent.trim();
          return nameB.localeCompare(nameA);
        }
        return 0;
      });
      
      // Re-append sorted elements to maintain DOM order
      const container = document.querySelector('.nintex-cards-container');
      visibleCards.forEach(card => {
        container.appendChild(card);
      });
    }

    // Store filtered and sorted cards
    filteredAndSortedCards = visibleCards;
    
    // Reset to first page and update display
    currentPage = 1;
    updatePagination();
    displayCurrentPage();
  }

  function displayCurrentPage() {
    const container = document.querySelector('.nintex-cards-container');
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const cardsToShow = filteredAndSortedCards.slice(startIndex, endIndex);

    // Hide all cards first
    const allCards = container.querySelectorAll('.col-xs-12, .col-md-6, .col-lg-4');
    allCards.forEach(card => {
      card.style.display = 'none';
    });

    // Hide zero state container
    const zeroStateContainer = document.querySelector('.np-learning-paths-resources-container');
    if (zeroStateContainer) zeroStateContainer.style.display = 'none';

    // Show zero state if no filtered results
    if (filteredAndSortedCards.length === 0) {
      if (zeroStateContainer) zeroStateContainer.style.display = 'block';
      return;
    }

    // Show only cards for current page
    cardsToShow.forEach(card => {
      card.style.display = 'flex';
    });
  }

  function updatePagination() {
    const totalItems = filteredAndSortedCards.length;
    const totalPages = Math.ceil(totalItems / itemsPerPage);
    const paginationControls = document.getElementById('pagination-controls');
    const prevBtn = document.getElementById('prev-page');
    const nextBtn = document.getElementById('next-page');
    const pageNumbers = document.getElementById('page-numbers');
    
    if (totalItems === 0) {
      paginationControls.style.display = 'none';
      return;
    }
    
    paginationControls.style.display = 'flex';
    
    // Update navigation buttons
    prevBtn.disabled = currentPage === 1;
    nextBtn.disabled = currentPage === totalPages;
    
    // Generate page number display
    pageNumbers.innerHTML = '';
    const pageSpan = document.createElement('span');
    pageSpan.className = 'nintex-page-number active';
    if(lang === 'en-US') {
      pageSpan.textContent = `Page ${currentPage}`;
    } else if(lang === 'es') {
      pageSpan.textContent = `Página ${currentPage}`;
    } else if(lang === 'fr') {
      pageSpan.textContent = `Page ${currentPage}`;
    } else if(lang === 'de') {
      pageSpan.textContent = `Seite ${currentPage}`;
    } else if(lang === 'en-GB') {
      pageSpan.textContent = `Page ${currentPage}`;
    } else if(lang === 'nl') {
      pageSpan.textContent = `Pagina ${currentPage}`;
    } else if(lang === 'pt-BR') {
      pageSpan.textContent = `Página ${currentPage}`;
    }
    pageNumbers.appendChild(pageSpan);
  }

  function goToPreviousPage() {
    if (currentPage > 1) {
      currentPage--;
      updatePagination();
      displayCurrentPage();
    }
  }

  function goToNextPage() {
    const totalPages = Math.ceil(filteredAndSortedCards.length / itemsPerPage);
    if (currentPage < totalPages) {
      currentPage++;
      updatePagination();
      displayCurrentPage();
    }
  }

  // Initialize pagination
  function initializePagination() {
    // Get all cards initially
    const allCards = document.querySelectorAll('.nintex-card');
    filteredAndSortedCards = Array.from(allCards).map(card => card.parentElement);
    
    // Set up event listeners
    document.getElementById('prev-page').addEventListener('click', goToPreviousPage);
    document.getElementById('next-page').addEventListener('click', goToNextPage);
    
    // Initial display
    updatePagination();
    displayCurrentPage();
  }

  function translateFormOptions() {
  const search = document.getElementById('name-search');

    const productFilter = document.getElementById('product-filter');
    const statusFilter = document.getElementById('status-filter');
    const sortFilter = document.getElementById('sort-filter');
    const skillFilter = document.getElementById('skill-filter');
    
    
   if(lang === 'es') {
    search.placeholder = 'Buscar...';
    productFilter.options[0].textContent = 'Todos los productos';
    statusFilter.options[0].textContent = 'Todos los estados';
    statusFilter.options[1].textContent = 'No iniciado';
    statusFilter.options[2].textContent = 'En progreso';
    statusFilter.options[3].textContent = 'Completado';
    sortFilter.options[0].textContent = 'Ordenar por';
    sortFilter.options[1].textContent = 'Fecha de salida (Nueva en primer lugar)';
    sortFilter.options[2].textContent = 'Fecha de salida (Antigua en primer lugar)';
    sortFilter.options[3].textContent = 'Nombre (A-Z)';
    sortFilter.options[4].textContent = 'Nombre (Z-A)';
    skillFilter.options[0].textContent = 'Nivel de habilidade';
    skillFilter.options[1].textContent = 'Iniciante';
    skillFilter.options[2].textContent = 'Intermediário';
    skillFilter.options[3].textContent = 'Avançado';
    skillFilter.options[4].textContent = 'Soluções';
   } else if(lang === 'fr') {
    search.placeholder = 'Rechercher...';
    productFilter.options[0].textContent = 'Tous les produits';
    statusFilter.options[0].textContent = 'Tous les statuts';
    statusFilter.options[1].textContent = 'Non commencé';
    statusFilter.options[2].textContent = 'En cours';
    statusFilter.options[3].textContent = 'Terminé';
    sortFilter.options[0].textContent = 'Trier par';
    sortFilter.options[1].textContent = 'Date de sortie (Nouveau en premier)';
    sortFilter.options[2].textContent = 'Date de sortie (Ancien en premier)';
    sortFilter.options[3].textContent = 'Nom (A-Z)';
    sortFilter.options[4].textContent = 'Nom (Z-A)';
    skillFilter.options[0].textContent = 'Niveau de compétence';
    skillFilter.options[1].textContent = 'Débutant';
    skillFilter.options[2].textContent = 'Intermédiaire';
    skillFilter.options[3].textContent = 'Avancé';
    skillFilter.options[4].textContent = 'Solutions';
   } else if(lang === 'de') {
    search.placeholder = 'Suchen...';
    productFilter.options[0].textContent = 'Alle Produkte';
    statusFilter.options[0].textContent = 'Alle Status';
    statusFilter.options[1].textContent = 'Nicht gestartet';
    statusFilter.options[2].textContent = 'In Progress';
    statusFilter.options[3].textContent = 'Completed';
    sortFilter.options[0].textContent = 'Sortieren nach';
    sortFilter.options[1].textContent = 'Release Date (Neueste zuerst)';
    sortFilter.options[2].textContent = 'Release Date (Älteste zuerst)';
    sortFilter.options[3].textContent = 'Name (A-Z)';
    sortFilter.options[4].textContent = 'Name (Z-A)';
    skillFilter.options[0].textContent = 'Niveau de compétence';
    skillFilter.options[1].textContent = 'Débutant';
    skillFilter.options[2].textContent = 'Intermédiaire';
    skillFilter.options[3].textContent = 'Avancé';
    skillFilter.options[4].textContent = 'Solutions';
   } else if(lang === 'nl') {
    search.placeholder = 'Zoeken...';
    productFilter.options[0].textContent = 'Alle producten';
    statusFilter.options[0].textContent = 'Alle statussen';
    statusFilter.options[1].textContent = 'Niet gestart';
    statusFilter.options[2].textContent = 'In progress';
    statusFilter.options[3].textContent = 'Completed';
    sortFilter.options[0].textContent = 'Sorteren op';
    sortFilter.options[1].textContent = 'Release Date (Nieuwste eerst)';
    sortFilter.options[2].textContent = 'Release Date (Oudste eerst)';
    sortFilter.options[3].textContent = 'Naam (A-Z)';
    sortFilter.options[4].textContent = 'Naam (Z-A)';
    skillFilter.options[0].textContent = 'Niveau de compétence';
    skillFilter.options[1].textContent = 'Débutant';
    skillFilter.options[2].textContent = 'Intermédiaire';
    skillFilter.options[3].textContent = 'Avancé';
    skillFilter.options[4].textContent = 'Solutions';
   } else if(lang === 'nl') {
    search.placeholder = 'Zoeken...';
    productFilter.options[0].textContent = 'Alle producten';
    statusFilter.options[0].textContent = 'Alle statussen';
    statusFilter.options[1].textContent = 'Niet gestart';
    statusFilter.options[2].textContent = 'In progress';
    statusFilter.options[3].textContent = 'Completed';
    sortFilter.options[0].textContent = 'Sorteren op';
    sortFilter.options[1].textContent = 'Release Date (Nieuwste eerst)';
    sortFilter.options[2].textContent = 'Release Date (Oudste eerst)';
    sortFilter.options[3].textContent = 'Naam (A-Z)';
    sortFilter.options[4].textContent = 'Naam (Z-A)';
    skillFilter.options[0].textContent = 'Niveau de compétence';
    skillFilter.options[1].textContent = 'Débutant';
    skillFilter.options[2].textContent = 'Intermédiaire';
    skillFilter.options[3].textContent = 'Avancé';
    skillFilter.options[4].textContent = 'Solutions';
   } else if(lang === 'pt-BR') {
    search.placeholder = 'Pesquisar...';
    productFilter.options[0].textContent = 'Todos os produtos';
    statusFilter.options[0].textContent = 'Todos os statuses';
    statusFilter.options[1].textContent = 'Não iniciado';
    statusFilter.options[2].textContent = 'Em progresso';
    statusFilter.options[3].textContent = 'Completado';
    sortFilter.options[0].textContent = 'Ordenar por';
    sortFilter.options[1].textContent = 'Release Date (Novo em primeiro)';
    sortFilter.options[2].textContent = 'Release Date (Antigo em primeiro)';
    sortFilter.options[3].textContent = 'Nome (A-Z)';
    sortFilter.options[4].textContent = 'Nome (Z-A)';
    skillFilter.options[0].textContent = 'Nível de habilidade';
    skillFilter.options[1].textContent = 'Iniciante';
    skillFilter.options[2].textContent = 'Intermediário';
    skillFilter.options[3].textContent = 'Avançado';
    skillFilter.options[4].textContent = 'Soluções';
   }
  }

  // Add event listeners to all filters
  document.getElementById('name-search').addEventListener('input', handleFilterChange);
  document.getElementById('product-filter').addEventListener('change', handleFilterChange);
  document.getElementById('status-filter').addEventListener('change', handleFilterChange);
  document.getElementById('sort-filter').addEventListener('change', handleFilterChange);
  document.getElementById('skill-filter').addEventListener('change', handleFilterChange);

  // Initialize pagination when page loads
  document.addEventListener('DOMContentLoaded', initializePagination);
  document.addEventListener('DOMContentLoaded', translateFormOptions);
</script>
{% include "footer" %}