{# LIBRARIES #}
{{ attach_library('ui_patterns/best_fares.best_fares_lib') }}

{# VARIABLES #}
{% set header_text = header_text|default("Best fares {{dir_a}} {{stations}} {{dir_b}}")%}
{% set direction = direction|default("from") %}
{% set dir_a = direction == 'from' ? 'to' : 'from'  %}
{% set dir_b = direction == 'from' ? 'from' : 'to'  %}

{% set count = count + 3 %}
{% set slides = [] %}
{% set range_numb = 1 %}


{% for crs, ticket_group in tickets %}
  {% set count = 0 %}
  {% set crs_compare = '' %}
  {% set ticket_group_thirds = ticket_group|length / 3 %}
  {% if ticket_group_thirds < range_numb %}
    {% set ticket_group_thirds = range_numb %}
  {% endif %}
  {% for i in range(range_numb, ticket_group_thirds) %}
    {# Loop counters #}
    {% set end = count + 3 > ticket_group|length ? ticket_group|length : count + 3 %}
    {# Package up for carousel #}
    {% set slide_item %}
      {% include "@organisms/tm-bf/_best-fares-slide.twig" with {'tickets': ticket_group}  %}
    {% endset %}
    {% set slides = slides|merge([{
      'slide': slide_item,
      'sid': crs == crs_compare ? 'crs-' ~ random() : crs,
    }]) %}
    {# Loop counters #}
    {% set count = count + 3 %}
    {% set crs_compare = crs %}
  {% endfor %}
{% endfor %}

{% set stations %}
  {% include "@organisms/tm-bf/_best-fares-station-select.twig" with {
    'stations_list': stations_list,
    'tickets': tickets,
    'status': 'default'
  } only %}
{% endset %}

{# TEMPLATE #}
{% if slides|length %}
  <div id="best_fares">

    {% if header_text %}
      <div class="bf_header">
        <h2>{{ include(template_from_string(header_text)) }}</h2>
      </div>
    {% endif %}

    <div class="bf_body">
      {{ pattern('bs_carousel', {
        'pid': 'best-fares',
        'slides': slides,
        'data_ride': 'false',
        'show_indicators': false,
        'show_controls': true,
      }) }}
    </div>

  </div>
{% endif %}
