{% import '_includes/forms.twig' as forms %}
{% from '_includes/disclosuremenu.twig' import item as itemMacro %}

{% set id = id ?? "customselect#{random()}" %}
{% set buttonId = buttonId ?? "#{id}-button" %}
{% set menuId = menuId ?? "#{id}-menu" %}
{% set inputId = inputId ?? "#{id}-input" %}
{% set value = value ?? '' %}
{% set disabled = disabled ?? false %}
{% set selectedOption = value ? options|firstWhere(o => o.value == value) : null %}
{% set buttonAttributes = buttonAttribues ?? {} %}
{% if disabled %}
  {% set buttonAttributes = buttonAttributes|merge({'disabled': 'disabled'}) %}
{% endif %}

{% macro color(color) %}
  {{- color is instance of ('craft\\enums\\Color') ? color.value : color -}}
{% endmacro %}

{% set buttonIconHtml = null %}
{% if (selectedOption.icon ?? null) or (selectedOption.icon ?? null) is same as('0') %}
    {% set buttonIconHtml %}
        {{ tag('div', {
            class: [
                'cp-icon',
                _self.color(selectedOption.iconColor ?? null),
            ]|filter,
            html: iconSvg(selectedOption.icon),
        }) }}
    {% endset %}
{% endif %}

{% set buttonLabel = selectedOption ? (selectedOption.label ?? selectedOption.labelHtml|raw) : defaultButtonLabel ?? 'Choose'|t('app')  %}

{% tag 'div' with {
  class: {
    'custom-select': true,
    disabled: disabled,
  }|filter|keys,
  id: id,
  data: {value},
}|merge(attributes ?? {}, recursive=true) %}
  {{ forms.button({
    id: buttonId,
    iconHtml: buttonIconHtml,
    label: buttonLabel,
    class: ['menubtn'],
    attributes: buttonAttributes ?? {},
  }) }}

  {% if not disabled %}
    {% tag 'div' with {
      id: menuId,
      class: ['menu']
    }|merge(menuAttributes ?? {}, recursive=true) %}
      <ul class="padded">
        {% for option in options %}
          <li>
            {% tag 'button' with {
              class: {
                'menu-item': true,
                sel: option.value == value,
              }|filter|keys,
              data: {
                value: option.value,
              },
            }|merge(option.attributes ?? {}, recursive=true) %}
              {% if (option.icon ?? null) or (option.icon ?? null) is same as('0') %}
                {{ tag('span', {
                  class: [
                    'icon',
                    _self.color(option.iconColor ?? null),
                  ]|filter,
                  html: iconSvg(option.icon),
                }) }}
              {% endif %}
              <span class="label">{{ option.label ?? option.labelHtml|raw }}</span>
            {% endtag %}
          </li>
        {% endfor %}
      </ul>
    {% endtag %}

    {% if name ?? false %}
      {{ hiddenInput(name, value, {
        id: inputId,
      }) }}
    {% endif %}
  {% endif %}
{% endtag %}

{% if not disabled %}
  {% js %}
    (() => {
      const $container = $('#{{ id|namespaceInputId }}');
      const $button = $('#{{ buttonId|namespaceInputId }}');
      const $buttonFlex = $button.find('.inline-flex:first');
      const $input = $('#{{ inputId|namespaceInputId }}');
      const menubtn = $button
        .menubtn()
        .data('menubtn');
        if (menubtn) {
          menubtn
            .on('optionSelect', (ev) => {
              const $option = $(ev.option);
              const $icon = $option.find('.icon');
              const $label = $option.find('.label');
              let labelHtml = '';
              if ($icon.length) {
                labelHtml += $icon.clone().removeClass('icon').addClass('cp-icon').prop('outerHTML');
              }
              labelHtml += `<div class="label">${$label.html()}</div>`;
              $buttonFlex.html(labelHtml);
              $input.val($option.data('value'));
              menubtn.menu.$options.removeClass('sel');
              $option.addClass('sel');
              $container.data('value', $option.data('value'));
              $container.trigger('change');
            });
        }
    })();
  {% endjs %}
{% endif %}
