{% with options=widget.get_options|list %}
  {% firstof options.0.options.details.JOURDATE options.0.options.details.day_str as first_day %}
  {% with first_monday=first_day|adjust_to_week_monday last_option=options|last %}
    {% firstof last_option.options.details.JOURDATE last_option.options.details.day_str as last_day %}
    {% with last_sunday=last_day|adjust_to_week_monday|add_days:6 %}
      {% now 'W' as current_week %}
      {% spaceless %}
        <button class="previous-week">←</button>
        <div class="week-list">
          <div class="slider">
            {% for day in first_monday|iterate_days_until:last_sunday %}
              {% if day.weekday == 0 %}
                {% with sunday=day|add_days:6 %}
                  <div class="week-title {% if form.var.current_day == day|date:"Y-m-d" or not form.var.current_day and current_week == day|date:"W" %}current{% endif %}">
                    Du {{ day|date:"d/m" }} au {{ sunday|date:"d/m" }}
                  </div>
                {% endwith %}
              {% endif %}
              <div class="day-item" data-weekday="{{ day.weekday }}">
                <div class="day-title">
                  {{ day|date:"l d/m" }}
                </div>
                {% with day_str=day|date:"Y-m-d" %}
                  {% for option in options %}
                    {% if option.options.details.JOURDATE == day_str or option.options.details.day_str == day_str %}
                      <div class="activity-item {% if option.disabled %}disabled{% endif %} {% if widget.readonly %}readonly{% endif %}"
                        data-activity-type="{{ option.options.details.activity_type }}"
                        data-activity-id="{{ option.options.details.activity_id }}"
                        data-date="{% firstof option.options.details.JOURDATE option.options.details.day_str %}"
                        {% if widget.readonly and not option.disabled %}
                          {% if option.selected and not option.options.prefill %}data-has-change
                          {% elif not option.selected and option.options.prefill %}data-has-change
                          {% endif %}
                        {% endif %}
                      >
                        <div class="activity-status {{ option.options.details.status_color }}"></div>
                        <div class="activity-label"/>
                        <label>
                          <input
                            {# never displayed, no possible changes to not overwrite #}
                            {% if not widget.value and option.options.prefill %}checked="checked"{% endif %}
                            {# already displayed but for another child #}
                            {% if widget.value and widget.value|first|split:':'|first != last_option.value|split:':'|first and option.options.prefill %}checked="checked"{% endif %}
                            {% if option.selected %}checked="checked"
                            {% elif widget.readonly or option.disabled %}disabled{% endif %}
                            {% for attr in widget.attrs.items %}{{attr.0}}="{{attr.1}}"{% endfor %}
                            type="checkbox"
                            {% if widget.readonly %}value="yes" disabled
                            {% else %}name="{{ option.name }}" value="yes"
                            {% endif %} />
                          <span>{{ option.options.details.activity_label }}</span>
                        </label>
                        {% if widget.readonly and option.selected %}<input type="hidden" name="{{ option.name }}" value="yes">{% endif %}
                      </div>
                      </div>
                    {% endif %}
                  {% endfor %}
                {% endwith %}
              </div>
            {% endfor %}
          </div>
        </div>
        <button class="next-week">→</button>
      {% endspaceless %}
    {% endwith %}
  {% endwith %}
{% endwith %}
<style>
  .template-{{ widget_prefix }}-reservations-enfant .content {
    margin-top: 1em;
    display: grid;
    grid-template-columns: repeat(3, auto);
    grid-template-rows: repeat(2, auto);
    justify-items: left;
    --min-column-width: 250;
  }

  .template-{{ widget_prefix }}-reservations-enfant .previous-week,
  .template-{{ widget_prefix }}-reservations-enfant .next-week {
    height: 3em;
    width: 3em;
  }

  .template-{{ widget_prefix }}-reservations-enfant .next-week {
    margin-left: 1rem;
  }


  .template-{{ widget_prefix }}-reservations-enfant .edit-btn {
    grid-column: 2;
    grid-row: 2;
  }

  .template-{{ widget_prefix }}-reservations-enfant .week-list {
    overflow: hidden;
    margin-bottom: 2rem;
    width: 100%;
  }

  .template-{{ widget_prefix }}-reservations-enfant .slider {
    column-gap: 0px;
    display: grid;
    grid-auto-columns: 0px;
    grid-auto-rows: 0px;
    grid-auto-flow: column;
    position: relative;
  }

  .template-{{ widget_prefix }}-reservations-enfant .week-title {
    display: block;
    height: 3em;
    line-height: 3em;
  }

  .template-{{ widget_prefix }}-reservations-enfant .week-item:nth-child(even) {
    background: #fafafa;
  }

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

  .template-{{ widget_prefix }}-reservations-enfant .day-item {
    margin: 0 1rem;
  }

  .template-{{ widget_prefix }}-reservations-enfant .day-title {
    border-bottom: 1px solid #888;
    margin: 1rem 0;
    font-weight: bold;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-item {
    display: flex;
    align-items: baseline;
    margin: 0.3rem 0;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-item.disabled {
    color: #888;
  }

  .template-{{ widget_prefix }}-reservations-enfant .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;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-status.green {
    background: #3c3;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-status.grey {
    background: #aaa;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-status.orange {
    background: orange;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-status.red {
    background: red;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-status.yellow {
    background: yellow;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-item[data-has-change] .activity-status:not(.green) {
    background: #3f3;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-item[data-has-change] .activity-status.green {
    background: orange;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-item[data-has-change] label {
    font-weight: bold;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-item:not(.readonly):not(.disabled) .activity-status {
    display: none;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-item input {
    flex-shrink: 0;
    margin-right: 1rem;
    margin-bottom: 0;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-item input[disabled] {
    display: none;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-label {
    flex-grow: 1;
  }

  .template-{{ widget_prefix }}-reservations-enfant .activity-label label {
    display: flex;
    align-items: baseline;
  }
</style>
<script>
  function initAgendaWidget($widget) {
    const $weekList = $('.week-list', $widget);
    const $slider = $('.slider', $widget);
    let $currentWeek = $('.week-title.current', $widget);
    if (!$currentWeek.length) {
      $currentWeek = $('.week-title:first', $widget);
    }
    const $nextWeekButton = $('.next-week', $widget);
    const $previousWeekButton = $('.previous-week', $widget);
    const $editAgendaBtn = $('.edit-btn', $widget);

    let $selectedWeek = $currentWeek;

    function getPreviousWeek() { return $selectedWeek.prevAll('.week-title:first'); }
    function getNextWeek() { return $selectedWeek.nextAll('.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('.week-title.current').length;
      $weekToEdit = selectedWeekIsInPast ? $currentWeek : $selectedWeek;
      $editAgendaBtn.prop('href', $weekToEdit.attr('data-edit-url'));
    }

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

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

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

    $widget.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 = $(`.day-item[data-weekday=${i}]`, $widget);
        const $activities = $('.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);
  }


  initAgendaWidget($('.template-{{ widget_prefix }}-reservations-enfant'));


  $('.template-{{ widget_prefix }}-reservations-enfant input').on('change', function() {
    if ($(this).is(':checked')) {
      var $current_item = $(this).parents('.activity-item').first();
      $(this).parents('.day-item').find('.activity-item[data-activity-type="' +
        $current_item.data('activity-type') + '"][data-date="' +
        $current_item.data('date') + '"]:not([data-activity-id="' +
        $current_item.data('activity-id') + '"])').find('input').prop('checked', false);
    }
  });
</script>
