<%
  conditions = @refine_filter_query.available_conditions_attributes

  conditions_for_category = -> (category) do
    conditions.filter { |c| c[:meta][:category] == category}
  end

  # If an ordering has been defined for categories, use that, otherwise use the order in which they appear in the sorted conditions
  categories = (@refine_filter.has_category_ordering?) ? @refine_filter.category_order : conditions.map { |c| c[:meta][:category] }.uniq.compact

  recommended_conditions = conditions.select { |c| c[:meta][:recommended] }

  # Note that the stimulus controllers set default condition id for new conditions
  # so this is only for rare cases where it gets unset
  selected_condition_id ||= @refine_filter.default_condition_id
  selected_condition_id ||= categories
    .first
    &.conditions_for_category.call(categories.first)
    [:id]

  uncategorized_conditions = conditions.filter { |c| c[:meta][:category].nil? }

%>

<%= tag.div data: {
  action: "$change->refine--update#condition",
  controller: 'fields--super-select',
  fields__super_select_enable_search_value: 'true',
  fields__super_select_container_width_value: 'resolve',
} do %>
  <select
    data-fields--super-select-target="select"
    data-condition-id="<%= selected_condition_id %>"
    name="conditions"
    class="refine-condition-select"
  >
    <% if uncategorized_conditions&.any? %>
      <optgroup >
        <% uncategorized_conditions.each do |condition_option| %>
          <option
            value="<%= condition_option[:id] %>"
            <% if selected_condition_id == condition_option[:id] %>selected<% end %>
            title="<%= condition_option[:display] %>"
          ><%= condition_option[:display] %></option>
        <% end %>
      </optgroup>
    <% end %>      

    <% if recommended_conditions&.any? %>
      <optgroup class="divider" label="<%= t(".recommended") %>">
        <% recommended_conditions.each do |condition_option| %>
          <option
            value="<%= condition_option[:id] %>"
            <% if selected_condition_id == condition_option[:id] %>selected<% end %>
            title="<%= condition_option[:display] %>"
          ><%= condition_option[:display] %></option>
        <% end %>
      </optgroup>
    <% end %>

    <% categories.each do |category| %>
      <optgroup class="divider" label="<%= category %>">
        <% conditions_for_category.call(category).each do |condition_option| %>
          <option
            value="<%= condition_option[:id] %>"
            <% if selected_condition_id == condition_option[:id] %>selected<% end %>
            title="<%= condition_option[:display] %>"
          >
            <%= condition_option[:display] %>
          </option>
        <% end %>
      </optgroup>
    <% end %>
  </select>
<% end %>