{% load i18n %} {% load basefilters %}

<!-- filter items showing here -->
<div style="display: none;">{{filter_dict}}</div>
<script>
  var formButton = ".filterButton";
  function clearFilterFromTag(element) {
    let field_id = element.attr("data-x-field");
    $(`[name=${field_id}]`).val("");
    $(`[name=${field_id}]`).change();
    // Update all elements with the same ID to have null values
    let elementId = $(`[name=${field_id}]:last`).attr("id");
    let spanElement = $(
      `.oh-dropdown__filter-body:first #select2-id_${field_id}-container, #select2-${elementId}-container`
    );
    if (spanElement.length) {
      spanElement.attr("title", "---------");
      spanElement.text("---------");
    }
    $(formButton).click();
  }
  function clearAllFilter(element) {
    $('[role="tooltip"]').remove();
    let field_ids = $("[data-x-field]");
    for (var i = 0; i < field_ids.length; i++) {
      let item_id = field_ids[i].getAttribute("data-x-field");

      $(`[name=${item_id}]`).val("");
      $(`[name=${item_id}]`).change();
      let elementId = $(`[name=${item_id}]:last`).attr("id");
      let spanElement = $(
        `.oh-dropdown__filter-body:first #select2-id_${item_id}-container, #select2-${elementId}-container`
      );
      if (spanElement.length) {
        spanElement.attr("title", "---------");
        spanElement.text("---------");
      }
      $(formButton).click();
      localStorage.removeItem("savedFilters");
      var url = window.location.href.split("?")[0];
      window.history.replaceState({}, document.title, url);
    }
  }
  function fieldLabel(value, field) {
    if (field == "field") {
      return $(`option[value="${value}"]`).html();
    }
    return value;
  }
  $(document).ready(function () {
    var nav = $("#filterTagContainerSectionNav");
    tags = $(`
    {% if filter_dict %}
    <span class="oh-titlebar__tag oh-titlebar__tag--custom"
      >{% trans 'Filters' %}:</span
    >
    {% endif %}
    {%for field,values in filter_dict.items %} {% if values %}
    {% with translation_field=field|filter_field %}
    <span class="oh-titlebar__tag filter-field" >
      {% trans translation_field %} :
	  {% for value in values %}
		${fieldLabel("{% trans value %}", "{{field}}")}
	  {% endfor %}
      <button class="oh-titlebar__tag-close" onclick="clearFilterFromTag($(this))" data-x-field="{{field}}">
        <ion-icon
          name="close-outline"
          role="img"
          class="md hydrated close-icon"
          aria-label="close outline"
        >
        </ion-icon>
      </button>
    </span>
    {% endwith %} {% endif %} {% endfor %}
    {% if filter_dict %}
    <span class="oh-titlebar__tag oh-titlebar__tag--custom" title="{% trans 'Clear All' %}" role="button" onclick="clearAllFilter($(this));"
      ><ion-icon class="close-icon" name="close-outline"></ion-icon></span
    >
    {% endif %}
    `);

    nav.html(tags);
    $("oh-tabs__tab oh-tabs__tab--active:first").click();
  });
</script>
