{% include "header" %}
{% assign available_courses = "" %}
{% for course in courses.enrolled %}
    {% assign available_courses = available_courses |  append: course.name | append: '[lang]' |  append: course.properties.language |  append: ',' %}
{% endfor %}
{% for course in courses.in_catalog %}
  {% assign available_courses = available_courses |  append: course.name | append: '[lang]' |  append: course.properties.language |  append: ',' %}
{% endfor %}

<main class="np-main np-search np-subpage-container np-max-width">
  <div class="np-resource-title lang-en">
    {% t .title %}
  </div>
  <div class="np-resource-title lang-de">
    Suchergebnisse 
  </div>
  <div class="np-resource-title lang-fr">
    Rechercher 
  </div>
  <div class="np-resource-title lang-jp">
    検索 
  </div>
  
  <div class="np-search-header">
    <div class="np-resource-subtitle lang-en">
      {% t .showing %}
      {% t .results_for %}
      <span class="np-button-color">"{{ results.term }}"</span>
    </div>
    <div class="np-resource-subtitle lang-de">
      Unte
      resultate für
      <span class="np-button-color">"{{ results.term }}"</span>
    </div>

  </div>
  {% if results.items.any? %}
    {% render "search_result" for results.items as result %}
  {% else %}
    {% include "search_zero_state" %}
  {% endif %}
</main>
{% include "footer" %}

<script>
  function filterSearchResults() {
    const userSelectedLanguage = localStorage.getItem("userLanguage");
    const search_result = document.querySelectorAll(".np-search-result"); 
    let available_courses = "{{ available_courses }}".toLowerCase().split(",");
    let uniq_available_courses = [...new Set(available_courses)];

    let courses = uniq_available_courses.map(item => {
      const parts = item.split("[lang]");
      return { name: parts[0].trim(), lang: parts[1] };
    })

    search_result.forEach((result) => {
      const result_name = result.querySelector(".result-name").innerText.toLowerCase();

      let is_visible = courses.some(course => course.name === result_name && course.lang === userSelectedLanguage);
      result.style.display = is_visible ? "block" : "none";
    });
  }

  addEventListener("DOMContentLoaded", (event) => {
    filterSearchResults();
  });
</script>