{# 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 button_size = button_size|default('md') %}
{% set card_button_status = card_button_status|default('default') %}
{% set status = status|default('default') %}
{% set icon = icon|default(false) %}
{# Multiplying by 1 to convert to int #}
{% set cards_per_slide = cards_per_slide|default(3) * 1 %}

{% set slides = [] %}
{% set range_numb = 1 %}


{% for crs, ticket_group in tickets %}
  {% set count = 0 %}
  {% set crs_compare = '' %}
  {% set ticket_group_count = (ticket_group|length / cards_per_slide) | round(0, 'ceil') %}
  {% if ticket_group_count < range_numb %}
    {% set ticket_group_count = range_numb %}
  {% endif %}
  {% for i in range(range_numb, ticket_group_count) %}
    {# Loop counters #}
    {% set increase = count + cards_per_slide %}
    {% set end = increase > ticket_group|length ? ticket_group|length : increase %}
    {# 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 = increase %}
    {% 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': status,
    'cards_per_slide': cards_per_slide,
    'controls_type': controls_type,
  } only %}
{% endset %}

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

    {% if header_text %}
      <div class="bf_header">
        <h2 class="header">{% if icon %}<i class="{{ icon }}"></i> {% endif %}{{ 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 %}
