{%- set class = (class ?? [])|explodeClass|push('multiselect') %}
{%- set options = options ?? [] %}
{%- set values = values ?? [] -%}
{%- set hasOptgroups = false -%}

{% set containerAttributes = {
  class: (class ?? [])|explodeClass,
}|merge(containerAttributes ?? [], recursive=true) %}

{%- if block('attr') is defined %}
    {%- set containerAttributes = containerAttributes|merge(('<div ' ~ block('attr') ~ '>')|parseAttr, recursive=true) %}
{% endif %}

{% if name ?? false %}
    {{ hiddenInput(name, '') }}
{% endif -%}

{% set inputAttributes = {
    multiple: true,
    id: id ?? false,
    name: (name ?? false) ? "#{name}[]" : false,
    autofocus: (autofocus ?? false) and not craft.app.request.isMobileBrowser(true),
    disabled: disabled ?? false,
    size: size ?? false,
    aria: {
        describedby: describedBy ?? false,
    },
}|merge(inputAttributes ?? [], recursive=true) %}

{% tag 'div' with containerAttributes %}
    {% tag 'select' with inputAttributes %}
        {%- for key, option in options %}
            {% if option.optgroup is defined %}
                {% if hasOptgroups %}
                    </optgroup>
                {% else %}
                    {% set hasOptgroups = true %}
                {% endif %}
                <optgroup label="{{ option.optgroup }}">
            {% else %}
                {% set optionValue = (option.value is defined ? option.value : key) %}
                {{ tag('option', {
                  value: optionValue ?? '',
                  selected: optionValue in values,
                  disabled: option.disabled ?? false,
                  hidden: option.hidden ?? false,
                  text: option.label is defined ? option.label : option,
                  data: option.data ?? false,
                }) }}
            {% endif %}
        {%- endfor %}
        {% if hasOptgroups %}
            </optgroup>
        {% endif %}
    {% endtag %}
{% endtag %}
