{% extends 'django_spire/form/field/base_field.html' %}

{% block field_content %}
    <input
            type="text"
            x-model="value"
            x-ref="glue_field"
            hidden
    >

    <div
            class="position-relative"
            x-data="{
            placeholder: '------------',
            show_dropdown: false,
            choice_verbose: this.placeholder,

            init() {
                this.update_choice();

                $watch('value', (value) => {
                    this.update_choice();
                });

                $watch('glue_field.choices', () => {
                    this.update_choice();
                });
            },

            update_choice() {
                let match = this.glue_field.choices.find(choice => String(choice[0]) === String(this.value));
                this.choice_verbose = match ? match[1] : this.placeholder;
            }
        }"
            x-effect="update_choice();"
    >
        <button
                class="form-control text-start d-flex justify-content-between {{ select_padding }}"
                type="button"
                @click="show_dropdown = !show_dropdown"
        >
            <span x-text="choice_verbose"></span>

            <span class="d-flex align-items-center pt-1">
                {% include 'django_spire/form/field/element/select_down_arrow_element.html' %}
            </span>
        </button>
        <div
                x-cloak
                x-show="show_dropdown"
                @click.outside="show_dropdown = false"
                class="shadow border rounded-2 mt-2 position-absolute z-3 bg-app-glue-layer-one w-100 p-0 list-group"
                style="max-height: 300px; overflow-y: auto; z-index: 3;"
                @keydown.escape="show_dropdown = false"
                x-trap.inert="show_dropdown"
        >
            {% block select_dropdown_header %}
            {% endblock %}

            <template x-for="(choice, index) in glue_field.choices" :key="choice[0]">
                <div
                        class="py-1 d-flex align-items-center list-group-item px-0"
                        tabindex="0"
                        @click="glue_field.disabled_choices.includes(choice[0]) ? '' : value = choice[0]; show_dropdown = false"
                        :class="glue_field.disabled_choices.includes(choice[0]) ? 'opacity-50 glue-user-select glue-cursor-not-allowed' : 'glue-cursor-pointer bg-app-glue-layer-one-hover'"
                        @keydown.enter.prevent="value = choice[0]; show_dropdown = false"
                >
                    {% block choice_item %}
                        {% include 'django_spire/form/field/item/select_choice_item.html' %}
                    {% endblock %}
                </div>
            </template>

            {% block select_dropdown_footer %}
            {% endblock %}
        </div>
    </div>
{% endblock %}
