{% if json.extra_data %}
  <h2>Agenda de l'année scolaire {{ json.extra_data.school_year }}</h2>
  <div class="{{ cell_prefix }}-agenda-cell {{ cell_prefix }}-agenda-cell-{{ cell.pk }}">
    {% with first_monday=json.extra_data.start_date|adjust_to_week_monday %}
      {% with last_day=json.extra_data.end_date|adjust_to_week_monday|add_days:6 %}
        {% now 'WY' as current_week %}
        {% spaceless %}
          <button class="{{ cell_prefix }}-agenda-cell--previous-week">←</button>
          <div class="{{ cell_prefix }}-agenda-cell--week-list">
            <div class="{{ cell_prefix }}-agenda-cell--slider">
              {% for day in first_monday|iterate_days_until:last_day %}
                {% if day.weekday == 0 %}
                  {% with sunday=day|add_days:6 %}
                    <div class="{{ cell_prefix }}-agenda-cell--week-title {% if current_week == day|date:"WY" %}current{% endif %}"
                      data-edit-url={% block edit_url %}"{{ eservices_url }}{{ form_url }}{% if not is_portal_agent %}tryauth{% endif %}?child_id={{ child_id }}{% if is_portal_agent %}&family_id={{ foyer_id }}{% endif %}&reference_year={{ first_monday.year }}&current={{ day|adjust_to_week_monday|date:"Y-m-d" }}"{% endblock edit_url %}>
                      Du {{ day|date:"d/m" }} au {{ sunday|date:"d/m" }}
                    </div>
                  {% endwith %}
                {% endif %}
                <div class="{{ cell_prefix }}-agenda-cell--day-item" data-weekday="{{ day.weekday }}">
                  <div class="{{ cell_prefix }}-agenda-cell--day-title" >
                    {{ day|date:"l d/m" }}
                  </div>
                  {% with day_str=day|date:"Y-m-d" %}
                    {% for item in json.data %}
                      {% if item.details.JOURDATE == day_str or item.details.day_str == day_str %}
                        <div class="{{ cell_prefix }}-agenda-cell--activity-item {% if item.disabled %}disabled{% endif %}">
                          <div class="{{ cell_prefix }}-agenda-cell--activity-status {{ item.details.status_color }}"/></div>
                        <div class="{{ cell_prefix }}-agenda-cell--activity-label"/>{{ item.details.activity_label }}</div>
                        </div>
                      {% endif %}
                    {% endfor %}
                  {% endwith %}
                  <div class="{{ cell_prefix }}-agenda-cell--day-no-activity">
                    Pas d'activité ce jour.
                  </div>
                </div>
              {% endfor %}
            </div>
          </div>
          <button class="{{ cell_prefix }}-agenda-cell--next-week">→</button>
          <a class="pk-button {{ cell_prefix }}-agenda-cell--edit-btn">
            {% block edit_btn_label %}
              Modifier l'agenda
            {% endblock edit_btn_label %}
          </a>
        {% endspaceless %}
      {% endwith %}
    {% endwith %}
    <style>
      .{{ cell_prefix }}-agenda-cell {
        margin-top: 1em;
        display: grid;
        grid-template-columns: repeat(3, auto);
        grid-template-rows: repeat(2, auto);
        justify-items: left;
        --min-column-width: 250;
      }

      .{{ cell_prefix }}-agenda-cell--previous-week,
      .{{ cell_prefix }}-agenda-cell--next-week {
        height: 3em;
        width: 3em;
      }

      .{{ cell_prefix }}-agenda-cell--next-week {
        margin-left: 1rem;
      }

      .{{ cell_prefix }}-agenda-cell--edit-btn {
        grid-column: 2;
        grid-row: 2;
      }

      .{{ cell_prefix }}-agenda-cell--week-list {
        overflow: hidden;
        margin-bottom: 2rem;
        width: 100%;
      }

      .{{ cell_prefix }}-agenda-cell--slider {
        column-gap: 0px;
        display: grid;
        grid-auto-columns: 0px;
        grid-auto-rows: 0px;
        grid-auto-flow: column;
        position: relative;
      }

      .{{ cell_prefix }}-agenda-cell--week-item:nth-child(even) {
        background: #fafafa;
      }

      .{{ cell_prefix }}-agenda-cell--week-title {
        border-bottom: 1px solid #888;
        font-weight: bold;
        margin-bottom: 1rem;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 3.2rem;
      }

      .{{ cell_prefix }}-agenda-cell--day-item {
        margin: 0 1rem;
      }

      .{{ cell_prefix }}-agenda-cell--day-title {
        border-bottom: 1px solid #888;
        margin: 1rem 0;
        font-weight: bold;
      }

      .{{ cell_prefix }}-agenda-cell--day-no-activity {
        color: #888;
      }

      .{{ cell_prefix }}-agenda-cell--activity-item  + .{{ cell_prefix }}-agenda-cell--day-no-activity {
        display: none;
      }

      .{{ cell_prefix }}-agenda-cell--activity-item {
        display: flex;
        align-items: baseline;
        margin: 0.3rem 0;
      }

      .{{ cell_prefix }}-agenda-cell--activity-item.disabled {
        color: #888;
      }

      .{{ cell_prefix }}-agenda-cell--activity-status {
        min-height: calc(0.66rem + 2px);
        min-width: calc(0.66rem + 2px);
        background: transparent;
        border: 1px solid #aaa;
        border-radius: 2px;
        margin-right: 1rem;
      }

      .{{ cell_prefix }}-agenda-cell--activity-label {
        flex-grow: 1;
      }

      .{{ cell_prefix }}-agenda-cell--activity-status.green {
        background: #3c3;
      }

      .{{ cell_prefix }}-agenda-cell--activity-status.grey {
        background: #aaa;
      }

      .{{ cell_prefix }}-agenda-cell--activity-status.orange {
        background: orange;
      }

      .{{ cell_prefix }}-agenda-cell--activity-status.red {
        background: red;
      }

      .{{ cell_prefix }}-agenda-cell--activity-status.yellow {
        background: yellow;
      }

    </style>

    <script>
      function initAgendaCell($cell) {
        const $weekList = $('.{{ cell_prefix }}-agenda-cell--week-list', $cell);
        const $slider = $('.{{ cell_prefix }}-agenda-cell--slider', $cell);
        let $currentWeek = $('.{{ cell_prefix }}-agenda-cell--week-title.current', $cell);
        if (!$currentWeek.length) {
          $currentWeek = $('.{{ cell_prefix }}-agenda-cell--week-title:first', $cell);
        }
        const $nextWeekButton = $('.{{ cell_prefix }}-agenda-cell--next-week', $cell);
        const $previousWeekButton = $('.{{ cell_prefix }}-agenda-cell--previous-week', $cell);
        const $editAgendaBtn = $('.{{ cell_prefix }}-agenda-cell--edit-btn', $cell);

        let $selectedWeek = $currentWeek;

        function getPreviousWeek() { return $selectedWeek.prevAll('.{{ cell_prefix }}-agenda-cell--week-title:first'); }
        function getNextWeek() { return $selectedWeek.nextAll('.{{ cell_prefix }}-agenda-cell--week-title:first'); }

        function setCurrentWeek($week, enableTransition) {
          if(!$week.length) {
            return;
          }
          const currentOffset = $week[0].offsetLeft;
          $slider.css({
            'transform': `translate(-${currentOffset}px)`,
            'transition': (enableTransition ? 'transform 0.5s' : '')
          });

          $selectedWeek = $week;
          $nextWeekButton.prop('disabled', getNextWeek().length == 0);
          $previousWeekButton.prop('disabled', getPreviousWeek().length == 0);

          const selectedWeekIsInPast = $selectedWeek.nextAll('.{{ cell_prefix }}-agenda-cell--week-title.current').length;
          $weekToEdit = selectedWeekIsInPast ? $currentWeek : $selectedWeek;
          $editAgendaBtn.prop('href', $weekToEdit.attr('data-edit-url'));
        }

        function setPreviousWeek() { setCurrentWeek(getPreviousWeek(), true); }
        function setNextWeek() { setCurrentWeek(getNextWeek(), true); }

        $previousWeekButton.on('click', setPreviousWeek);
        $nextWeekButton.on('click', setNextWeek);

        let touchStartX = 0;
        $cell.on('touchstart', (e) => {
          touchStartX = e.changedTouches[0].screenX;
        });

        $cell.on('touchend', (e) => {
          const touchEndX = e.changedTouches[0].screenX;
          if (touchEndX - touchStartX < -30) {
            setNextWeek();
          } else if (touchEndX - touchStartX > 30) {
            setPreviousWeek();
          }
        });

        function updateColumnsWidth() {
          const minWidth = $slider.css('--min-column-width');
          const availableWidth = $weekList[0].offsetWidth;
          let columnsWidth = availableWidth < minWidth ? availableWidth : availableWidth / Math.floor(availableWidth / minWidth);
          $slider.css('grid-template-columns', `repeat(53, ${columnsWidth}px)`);

          if($selectedWeek) {
            // Update slider offset to bring it at the new position of the selectedWeek
            setCurrentWeek($selectedWeek, false);
          }
        }

        function hideEmptyDays() {
          let nbRows = 8;
          for(let i = 0; i < 7; ++i) {
            const $days = $(`.{{ cell_prefix }}-agenda-cell--day-item[data-weekday=${i}]`, $cell);
            const $activities = $('.{{ cell_prefix }}-agenda-cell--activity-item', $days);
            if(!$activities.length) {
              $days.css('display', 'none');
              nbRows -= 1;
            }

            $slider.css('grid-template-rows', `repeat(${nbRows}, auto`);
          }
        }

        hideEmptyDays();
        new ResizeObserver(updateColumnsWidth).observe($weekList[0]);
        addEventListener('resize', updateColumnsWidth);
      }


      initAgendaCell($('.{{ cell_prefix }}-agenda-cell-{{ cell.pk }}'));

    </script>
  </div>
{% endif %}
