<h2 class="cell--title">Catalogue des activités</h2>
<div class="cell--body" data-cell-id="{{ cell.id }}">
  <div class="theme-activities--search">
    {% for criteria_id in json.meta.all_criterias_order %}
      {% with criteria=json.meta.all_criterias|get:criteria_id %}
        {% if criteria.data %}
          <div class="theme-activites--criteria">
            <label class="theme-activities--criteria-label">
              {{ criteria.text }} :
            </label>
            <div class="theme-activities--criteria-choices">
              <select data-autocomplete="true" multiple="true" data-criteria="{{criteria_id}}">
                {% for value_id in criteria.order %}
                  <option value={{value_id}}>
                    {{ criteria.data|get:value_id }}
                  </option>
                {% endfor %}
              </select>
            </div>
          </div>
        {% endif %}
      {% endwith %}
    {% endfor %}
  </div>
  <div class="theme-activities--items">
    {% for item in json.data %}
      <div class="theme-activities--item filtered collapsed"
        {% for criteria_id, criterias in item.criterias.items %}
          data-criteria-{{ criteria_id }}="{{ criterias.order|join:',' }}"
        {% endfor %}
      >
        <div class="theme-activities--item-label" role="button" aria-label="Voir les détails" title="Détails">{{ item.text }}</div>
        <div class="theme-activities--item-summary">
          <div class="theme-activities--item-type">{{ item.criterias.type.data|get:item.criterias.type.order.0 }}</div>
          <div class="theme-activities--item-location">{{ item.place.text }}</div>
          <div class="theme-activities--item-date">Du {{ item.unit.dateStart|date:"d/m/Y" }} au {{ item.unit.dateEnd|date:"d/m/Y" }}</div>
        </div>
        <div class="theme-activities--item-details">
          <p class"theme-activities--item-description">{{ item.activity.activityPortail.blocNoteList.0.note }}</p>
          <p class"theme-activities--item-audience">
            Public :
            {% for key in item.criterias.public.order %}
              {{ item.criterias.public.data|get:key }}
              {% if not forloop.last %}, {% endif %}
            {% endfor %}.
          </p>
        </div>
        <a class="pk-button" href="{{ eservices_url }}inscription-loisirs/tryauth?activity_id={{ item.activity.id }}&unit_id={{ item.unit.id }}&place_id={{ item.place.id }}&catalogue=Oui&cancelurl={{ portal_url }}mes-activites/">Inscription</a>
      </div>
    {% endfor %}
    <div class="theme-activities--pagination">
      <button class="theme-activities--pagination-prev">←</a>
      <button class="theme-activities--pagination-next">→</a>
    </div>
    <div class="theme-activities--no-result" hidden>
      <p class="infonotice">Aucun résultat</p>
    </div>
  </div>
</div>

<link rel="stylesheet" type="text/css" href="/static/xstatic/select2.min.css">

<script>
  $(() =>  {
    $.getScript("/static/xstatic/select2.min.js", function( data, textStatus, jqxhr ) {
      const $cell = $('[data-cell-id="{{ cell.id }}"')
      const $pagination = $cell.find('.theme-activities--pagination')
      const $paginationPrev = $cell.find('.theme-activities--pagination-prev')
      const $paginationNext = $cell.find('.theme-activities--pagination-next')
      const paginateBy = {{ pagination|default:4 }};

      function updatePagination(step) {
        const items = $cell.find('.theme-activities--item.filtered')

        const maxPageIndex = Math.ceil(items.length / paginateBy);
        let pageIndex = $pagination.data('page_index') || 0
        pageIndex = Math.max(0, Math.min(pageIndex + step, maxPageIndex - 1));

        $pagination.prop('hidden', maxPageIndex <= 1);
        $paginationPrev.prop('disabled', pageIndex === 0);
        $paginationNext.prop('disabled', pageIndex === maxPageIndex - 1)

        const startItem = paginateBy * pageIndex;

        items.hide();
        items.slice(startItem, startItem + paginateBy).show();
        $pagination.data('page_index', pageIndex);
      };

      $paginationPrev.click(() => updatePagination(-1))
      $paginationNext.click(() => updatePagination(1))
      updatePagination(0)

      $cell.find('select[data-criteria]').each((_, elem) => $(elem).select2())
      $cell.find('select[data-criteria]').on('change', evt => {
        let selectedCriterias = []

        for(const select of $cell.find('select[data-criteria]')) {
          if(select.selectedOptions.length === 0) {
            continue
          }

          selectedCriterias.push([
            select.dataset.criteria,
            new Set([...select.selectedOptions].map(option => option.value))
          ])
        }

        $cell.find(`.theme-activities--item`).each((_, element) => {
          element.classList.add('filtered')
          for ([criteriaId, filteredValues] of selectedCriterias) {
            const elementValues = element.getAttribute(`data-criteria-${criteriaId}`)

            if (elementValues !== undefined &&
              !elementValues.split(',').some(value => filteredValues.has(value))) {
                element.classList.remove('filtered')
                break
              }
          }
        })

        const filteredResults = $cell.find(`.theme-activities--item.filtered`)
        $cell.find(".theme-activities--no-result").prop('hidden', filteredResults.length !== 0)

        updatePagination(0)
      })

      $cell.find('.theme-activities--item-label').on('click', evt => {
        $(evt.target).closest('.theme-activities--item').toggleClass('collapsed')
      })
    })})
</script>
