{% set variant = variant|default('dropdown')|replace({'_': '-'}) %}
{% set dropdown_id = dropdown_id|default('dropdown-' ~ random()) %}
{% set auto_close = auto_close|default('true') %}
{% set button_variant = button_variant|default('primary') %}
{% set button_url = button_url|default('') %}
{# Some changes when used in navbar. #}
{% set dropdown_tag = dropdown_navbar ? 'li' : 'div' %}
{% set button_variant = dropdown_navbar ? 'default' : button_variant %}
{# Some changes when split. #}
{% set attributes = button_split ? attributes.addClass('btn-group') : attributes %}
{% set dropdown_menu_start = dropdown_menu_start ? 'dropdown-menu-' ~ dropdown_menu_start : '' %}
{% set dropdown_menu_end = dropdown_menu_end ? 'dropdown-menu-' ~ dropdown_menu_end : '' %}

{% set button_attributes = create_attribute(button_attributes|default({})) %}
{% set button_attributes = dropdown_navbar ? button_attributes.addClass('nav-link') : button_attributes %}
{% if megamenu %}
  {% set button_attributes = button_attributes.addClass('dropdown-toggle') %}
  {% set button_attributes = button_attributes.setAttribute('data-bs-toggle', 'dropdown') %}
  {% set button_attributes = button_attributes.setAttribute('data-bs-auto-close', auto_close) %}
  {% set button_attributes = button_attributes.setAttribute('aria-expanded', 'false') %}
  {% set button_attributes = (dropdown_menu_start or dropdown_menu_end) ? button_attributes.setAttribute('data-bs-display', 'static') : button_attributes %}
{% endif %}

{% set dropdown_menu_attributes = create_attribute() %}
{% set dropdown_menu_attributes = dropdown_menu_attributes.addClass('dropdown-menu') %}
{% set dropdown_menu_attributes = dark ? dropdown_menu_attributes.setAttribute('data-bs-theme', 'dark') : dropdown_menu_attributes %}
{% set dropdown_menu_attributes = dropdown_menu_attributes.addClass([dropdown_menu_start, dropdown_menu_end]) %}
{% set dropdown_menu_attributes = dropdown_menu_attributes.setAttribute('aria-labelledby', dropdown_id) %}

<{{ dropdown_tag }}{{ attributes.addClass(variant) }}>

{% if button_split %}
  {{ pattern('button', {
    variant: button_variant,
    label: title,
    url: button_url,
    attributes: create_attribute().setAttribute('id', dropdown_id)
  }) }}
  {{ pattern('button', {
    variant: button_variant,
    label: 'Toggle dropdown'|t,
    label_visually_hidden: true,
    attributes: button_attributes.addClass('dropdown-toggle-split')
  }) }}
{% else %}
  {{ pattern('button', {
    variant: button_variant,
    label: title,
    url: button_url,
    attributes: button_attributes.setAttribute('id', dropdown_id)
  }) }}
{% endif %}

  {% if megamenu %}
    <ul{{ dropdown_menu_attributes }}>
      <li class="dropdown-item-megamenu">
        {{ megamenu }}
      </li>
    </ul>
  {% endif %}

</{{ dropdown_tag }}>
