{% include "header"
  , color: "var(--nintex--color--deep-purple)"
  , text_color: "white"
  , text_en_US: ""
  , text_es: ""
  , text_fr: ""
  , text_de: ""
  , text_en_GB: ""
  , text_nl: ""
  , text_pt_BR: ""
  , subtitle_en_US: ""
  , subtitle_es: ""
  , subtitle_fr: ""
  , subtitle_de: ""
  , subtitle_en_GB: ""
  , subtitle_nl: ""
  , subtitle_pt_BR: ""
  , 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 "account_tabs" %}

<main class="np-main nintex-fw-container">
  <div class="badges-headline">
    <div class="badges-subtitle">
      Nintex University
    </div>
    <div class="badges-title">
      <span class="lang-en-US"> Badges for {{ current_person.first_name }}</span>
      <span class="lang-es"> Insignias para {{ current_person.first_name }}</span>
      <span class="lang-fr"> Insignes pour {{ current_person.first_name }}</span>
      <span class="lang-de"> Abzeichen für {{ current_person.first_name }}</span>
      <span class="lang-en-GB"> Badges for {{ current_person.first_name }}</span>
      <span class="lang-nl"> Insignes voor {{ current_person.first_name }}</span>
      <span class="lang-pt-BR"> Insignias para {{ current_person.first_name }}</span>
    </div>
  </div>
  {% if learning_paths.enrolled.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="level-filter">
        <option value="">All skill levels</option>
        <option value="Beginner">Beginner</option>
        <option value="Intermediate">Intermediate</option>
        <option value="Advanced">Advanced</option>
        <option value="Solutions">Solutions</option>
      </select>
      <select class="nintex-filters-select" id="sort-filter">
        <option value="">Sort by</option>
        <option value="name_asc">Name (A-Z)</option>
        <option value="name_desc">Name (Z-A)</option>
      </select>
    </div>
  {% endif %}

  {% if learning_paths.enrolled.any? %}
  <div id="badges-container">
    <div class="row np-catalog-courses nintex-cards-container badges-row">
    {% for path in learning_paths.enrolled %}
    {% if path.progress == 100 %}
    {% for category in path.categories %}
    {% if category.name == "[Skill Level]100 - Beginner" %}
    <div class="col-xs-12 col-sm-4 nintex-card-stretch">
      <div class="nintex-card">
        <div class="badge-type">
          Beginner
        </div>
        <img class="nintex-badge-image"
          src="https://s3.us-east-1.amazonaws.com/static.northpass.com/nintex/badges/Nintex_University_Badges_250x250_091225-01.png"></img>
        <div class="badge-pathname">
          {{ path.name }}
        </div>
      </div>
    </div>
    {% elsif category.name == "[Skill Level]200 - Intermediate" %}
    <div class="col-xs-12 col-sm-4 nintex-card-stretch">
      <div class="nintex-card">
        <div class="badge-type">
          Intermediate
        </div>
        <img class="nintex-badge-image"
          src="https://s3.us-east-1.amazonaws.com/static.northpass.com/nintex/badges/Nintex_University_Badges_250x250_091225-02.png"></img>
        <div class="badge-pathname">
          {{ path.name }}
        </div>
      </div>
    </div>
    {% elsif category.name == "[Skill Level]300 - Advanced" %}
    <div class="col-xs-12 col-sm-4 nintex-card-stretch">
      <div class="nintex-card">
        <div class="badge-type">
          Advanced
        </div>
        <img class="nintex-badge-image"
          src="https://s3.us-east-1.amazonaws.com/static.northpass.com/nintex/badges/Nintex_University_Badges_250x250_091225-03.png"></img>
        <div class="badge-pathname">
          {{ path.name }}
        </div>
      </div>
    </div>
    {% elsif category.name == "[Skill Level]400 - Solutions" %}
    <div class="col-xs-12 col-sm-4 nintex-card-stretch">
      <div class="nintex-card">
        <div class="badge-type">
          Solutions
        </div>
        <img class="nintex-badge-image"
          src="https://s3.us-east-1.amazonaws.com/static.northpass.com/nintex/badges/Nintex_University_Badges_250x250_091225-04.png"></img>
        <div class="badge-pathname">
          {{ path.name }}
        </div>
      </div>
    </div>
    {% endif %}
    {% endfor %}
    {% endif %}
    {% endfor %}
  </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">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">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 class="np-learning-paths-resources-container" style="display: none;">
    <div class="np-zero-state-text">
      <span class="lang-en-US">
        No badges found
      </span>
      <span class="lang-es">
        No se encontraron insignias
      </span>
      <span class="lang-fr">
        Aucun parcours trouvé
      </span>
      <span class="lang-de">
        Keine Lernpfade gefunden
      </span>
      <span class="lang-en-GB">
        No badges found
      </span>
      <span class="lang-nl">
        Geen leerpaden gevonden
      </span>
      <span class="lang-pt-BR">
        Nenhum emblema encontrado
      </span>
    </div>
    <img class="np-zero-state-learning-paths" />
  </div>
{% else %}

  <div class="np-learning-paths-resources-container"  style="margin-top: 60px;">
    <div class="np-zero-state-text">
      <span class="lang-en-US">
        No badges found
      </span>
      <span class="lang-es">
        No se encontraron insignias
      </span>
      <span class="lang-fr">
        Aucun parcours trouvé
      </span>
      <span class="lang-de">
        Keine Lernpfade gefunden
      </span>
      <span class="lang-en-GB">
        No badges found
      </span>
      <span class="lang-nl">
        Geen leerpaden gevonden
      </span>
      <span class="lang-pt-BR">
        Nenhum emblema encontrado
      </span>
    </div>
    <img class="np-zero-state-learning-paths" />
  </div>
{% endif %}

</main>

<style>
  .badges-headline {
    display: flex;
    flex-direction: column;
    font-weight: bold;
    align-items: flex-start;
  }

  .badges-subtitle {
    color: rgb(72, 103, 118);
    font-size: 12px;
    line-height: 15px;
    margin: 0 0 8px;
    padding: 0;
    text-transform: uppercase;
  }

  .badges-title {
    color: rgb(27, 62, 79);
    font-size: 24px;
    line-height: 18px;
    margin: 0;
    padding: 0;
  }

  .badges-row {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .nintex-card {
    align-items: center;
    justify-content: center;
    padding: 20%;
    position: relative;
  }

  .nintex-badge-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .badge-type, .badge-pathname{
  color: var(--nintex--color--deep-purple);
  position: absolute;
  }

  .badge-type{
    font-weight: 600;
    top: 15%;
  }
  .badge-pathname{
    bottom: 15%;
  }

  .nintex-filters-line{
    padding-top: 15px;
  }

</style>

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

  function handleFilterChange() {
    const filters = {
      name: document.getElementById('name-search').value,
      level: document.getElementById('level-filter').value,
      sort: document.getElementById('sort-filter').value
    }

    // Get all badge cards and apply filters
    const allCards = document.querySelectorAll('.nintex-card-stretch');
    const visibleCards = [];

    allCards.forEach(card => {
      let displayCard = true;

      // Get badge info from existing elements
      const badgeName = card.querySelector('.badge-pathname').textContent.trim();
      const badgeLevel = card.querySelector('.badge-type').textContent.trim();

      // Text search filter (name and level)
      if (filters.name && !(
        badgeName.toLowerCase().includes(filters.name.toLowerCase()) ||
        badgeLevel.toLowerCase().includes(filters.name.toLowerCase())
      )) {
        displayCard = false;
      }

      // Level filter
      if (filters.level && badgeLevel !== filters.level) {
        displayCard = false;
      }

      if (displayCard) {
        visibleCards.push(card);
      }
    });

    // Apply sorting if specified
    if (filters.sort && visibleCards.length > 0) {
      visibleCards.sort((a, b) => {
        const nameAEl = a.querySelector('.badge-pathname');
        const nameBEl = b.querySelector('.badge-pathname');
        const nameA = nameAEl ? nameAEl.textContent.trim().toLowerCase() : '';
        const nameB = nameBEl ? nameBEl.textContent.trim().toLowerCase() : '';
        const levelAEl = a.querySelector('.badge-type');
        const levelBEl = b.querySelector('.badge-type');
        const levelA = levelAEl ? levelAEl.textContent.trim().replace(/\s+/g, ' ') : '';
        const levelB = levelBEl ? levelBEl.textContent.trim().replace(/\s+/g, ' ') : '';

        const levelOrder = {
          'Beginner': 1,
          'Intermediate': 2,
          'Advanced': 3,
          'Solutions': 4
        };

        if (filters.sort === 'name_asc') {
          return nameA.localeCompare(nameB);
        } else if (filters.sort === 'name_desc') {
          return nameB.localeCompare(nameA);
        }
        return 0;
      });
    }

    // Re-append sorted elements to maintain DOM order
    const container = document.querySelector('.nintex-cards-container');
    if (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-sm-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');

    // Check if pagination elements exist
    if (!paginationControls || !prevBtn || !nextBtn || !pageNumbers) {
      return;
    }

    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 when page loads
  function initializePagination() {
    // Get all cards initially
    const allCards = document.querySelectorAll('.nintex-card-stretch');
    filteredAndSortedCards = Array.from(allCards);

    // Set up event listeners only if elements exist
    const prevBtn = document.getElementById('prev-page');
    const nextBtn = document.getElementById('next-page');

    if (prevBtn) {
      prevBtn.addEventListener('click', goToPreviousPage);
    }
    if (nextBtn) {
      nextBtn.addEventListener('click', goToNextPage);
    }

    // Initial display
    updatePagination();
    displayCurrentPage();
  }

  function translateFormOptions() {
    const search = document.getElementById('name-search');
    const levelFilter = document.getElementById('level-filter');
    const sortFilter = document.getElementById('sort-filter');

    if (!search || !levelFilter || !sortFilter) {
      return;
    }

    if(lang === 'es') {
      search.placeholder = 'Buscar...';
      levelFilter.options[0].textContent = 'Todos los niveles';
      levelFilter.options[1].textContent = 'Principiante';
      levelFilter.options[2].textContent = 'Intermedio';
      levelFilter.options[3].textContent = 'Avanzado';
      levelFilter.options[4].textContent = 'Soluciones';
      sortFilter.options[0].textContent = 'Ordenar por';
      sortFilter.options[1].textContent = 'Nombre (A-Z)';
      sortFilter.options[2].textContent = 'Nombre (Z-A)';
    } else if(lang === 'fr') {
      search.placeholder = 'Rechercher...';
      levelFilter.options[0].textContent = 'Tous les niveaux';
      levelFilter.options[1].textContent = 'Débutant';
      levelFilter.options[2].textContent = 'Intermédiaire';
      levelFilter.options[3].textContent = 'Avancé';
      levelFilter.options[4].textContent = 'Solutions';
      sortFilter.options[0].textContent = 'Trier par';
      sortFilter.options[1].textContent = 'Nom (A-Z)';
      sortFilter.options[2].textContent = 'Nom (Z-A)';
    } else if(lang === 'de') {
      search.placeholder = 'Suchen...';
      levelFilter.options[0].textContent = 'Alle Level';
      levelFilter.options[1].textContent = 'Anfänger';
      levelFilter.options[2].textContent = 'Fortgeschritten';
      levelFilter.options[3].textContent = 'Experte';
      levelFilter.options[4].textContent = 'Lösungen';
      sortFilter.options[0].textContent = 'Sortieren nach';
      sortFilter.options[1].textContent = 'Name (A-Z)';
      sortFilter.options[2].textContent = 'Name (Z-A)';
    } else if(lang === 'nl') {
      search.placeholder = 'Zoeken...';
      levelFilter.options[0].textContent = 'Alle niveaus';
      levelFilter.options[1].textContent = 'Beginner';
      levelFilter.options[2].textContent = 'Gevorderd';
      levelFilter.options[3].textContent = 'Expert';
      levelFilter.options[4].textContent = 'Oplossingen';
      sortFilter.options[0].textContent = 'Sorteren op';
      sortFilter.options[1].textContent = 'Naam (A-Z)';
      sortFilter.options[2].textContent = 'Naam (Z-A)';
    } else if(lang === 'pt-BR') {
      search.placeholder = 'Pesquisar...';
      levelFilter.options[0].textContent = 'Todos os níveis';
      levelFilter.options[1].textContent = 'Iniciante';
      levelFilter.options[2].textContent = 'Intermediário';
      levelFilter.options[3].textContent = 'Avançado';
      levelFilter.options[4].textContent = 'Soluções';
      sortFilter.options[0].textContent = 'Ordenar por';
      sortFilter.options[1].textContent = 'Nome (A-Z)';
      sortFilter.options[2].textContent = 'Nome (Z-A)';
    }
  }

  // Add event listeners to all filters (only if they exist)
  const nameSearch = document.getElementById('name-search');
  const levelFilter = document.getElementById('level-filter');
  const sortFilter = document.getElementById('sort-filter');

  if (nameSearch) {
    nameSearch.addEventListener('input', handleFilterChange);
  }
  if (levelFilter) {
    levelFilter.addEventListener('change', handleFilterChange);
  }
  if (sortFilter) {
    sortFilter.addEventListener('change', handleFilterChange);
  }

  // Initialize pagination when page loads
  document.addEventListener('DOMContentLoaded', initializePagination);
  document.addEventListener('DOMContentLoaded', translateFormOptions);
</script>

{% include "footer" %}