{% extends "qommon/forms/widget.html" %}

{% block widget-control %}
<select id="form_{{widget.name}}" name="{{widget.name}}" style="display: none"
  {% if widget.required %}data-required="true"{% endif %}>
  {% for option in widget.get_options %}
  <option{% for attr in option.attrs.items %} {{attr.0}}="{{attr.1}}"{% endfor %}
            data-image-url="{{ option.options.image_url }}"
            >{{ option.description }}</option>
  {% empty %}
    {% if widget.separate_hint or not widget.hint %}
    <option value="">---</option>
    {% endif %}
  {% endfor %}
</select>
<ul id="form_{{ widget.name }}_images_list" class="list-with-images">
</ul>

<script>
  $(function() {
    var $select = $('#form_{{widget.name}}');
    var $list = $('#form_{{widget.name}}_images_list');

    function build_list(items) {
      $select.empty();
      for (var i=0; i<items.length; i++) {
        var $option = $('<option></option>', {value: items[i].id, text: items[i].text});
        if (items[i].disabled) {
          $option.prop('disabled', true);
        }
      }
    }

    $select.on('wcs:options-change', function(ev, data) {
      if (data !== undefined) {
        build_list(data.items);
      }
      $list.empty();
      var $options = $select.find('option');
      var $items = $();
      for (var i=0; i<$options.length; i++) {
        if ($options[i].value == '---') {
          continue;
        }
        var $item = $('<li style="--bg-image: url(' + $options[i].dataset.imageUrl + ')"/>');
        $item.attr('tabindex', '0');
        $item.attr('data-value', $options[i].value);
        $item.text($options[i].text);
        if ($select.val() == $options[i].value) {
          $item.addClass('selected');
        }
        $items = $items.add($item);
      }
      $list.append($items);
      $items.on('click', function() {
         $select.val($(this).data('value'));
         $items.removeClass('selected');
         $(this).addClass('selected');
         $select.trigger('wcs:change');
         $select.trigger('change');
      });

      $items.on('keydown', function(event) {
        if (event.which == 13 || event.which == 32) {
          event.preventDefault();
          $(this).trigger('click');
        }
      });
    });
    $select.trigger('wcs:options-change');
  })
</script>

{% if request.quixote_request.is_in_backoffice %}
<style>
  .list-with-images {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
  }
  .list-with-images li {
      min-width: 22%;
      margin: 5px;
      text-align: center;
      padding: 95px 10px 10px 10px;
      background-image: var(--bg-image);
      background-repeat: no-repeat;
      background-position: center 7px;
      background-size: 90px auto;
  }
  .list-with-images li.selected {
      border-radius: 5px;
      box-shadow: inset 1px 0px 7px  #bbb;
  }
  .template-with-images.three-items-row .list-with-images li {
      min-width: 30%;
  }
</style>
{% endif %}

{% endblock %}
