{%- comment -%}
  Renders sort by popover

  Accepts:
  - results: {Object} Collection or Search object (required)
  - section_id: {String} The ID of the section that contains this card. (required)

  Usage:
  {%- render 'sort-by-popover', results: collection -%}
{%- endcomment -%}

{%- liquid
  assign sort_by = results.sort_by | default: results.default_sort_by
  assign option_selected = results.sort_options | where: "value", sort_by | first
  assign id = results.id | default: 'main_6868'
-%}

<hdt-popover-sorting class="hdt-popover__sorting" section-id="{{ section_id }}">
  <button aria-controls="dropdown{{ id }}" aria-owns="listbox{{ id }}" class="hdt-flex hdt-align-center hdt-justify-between">
    <span class="md:hdt-block hdt-hidden" change-text>{{ option_selected.name }}</span>
    <span class="hdt-block md:hdt-hidden">{{ 'sections.collection_template.short_by_txt' | t -}}</span>
    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="7" viewBox="0 0 12 7" fill="none">
      <path d="M0.738281 1.23813L6.23828 6.73813L11.7383 1.23813L10.762 0.261879L6.23828 4.78563L1.71453 0.261879L0.738281 1.23813Z" fill="currentColor"/>
    </svg>
  </button>
  <hdt-popover class="hdt-popover hdt-dropdown hdt-hidden hdt-collection-sorting" id="dropdown{{ id }}" placement="bottom" color-scheme="{{ settings.color_scheme_dialog }}" config='{ "closeRichlistSelect": true }'>
      <p slot="header" class="hdt-s-text">{{ 'products.facets.sort_by_label' | t }}</p>
      <hdt-richlist role="listbox" selected="{{ option_selected.value }}" id="listbox{{ id }}">
        {%- for option in results.sort_options -%}
        <button type="button" role="option" value="{{ option.value }}" aria-selected="{% if option.value == sort_by %}true{% else %}false{% endif %}">
          <span>{{ option.name | escape }}</span>
        </button>
        {%- endfor -%}
      </hdt-richlist>
  </hdt-popover>
</hdt-popover-sorting>