{% load static %}
{% comment %} 
This is the main component template that creates the basic HTML structure.
{% endcomment %}
<div
    id="{{ route_name }}__container"
    class="phac_aspc_form_autocomplete {{ disabled|yesno:'disabled,' }}"
>
    {# Hidden input elements used to maintain the component's state #}
    {# and used when submitting forms #}
    <div id="{{ route_name }}">
        {% include "./values.html" %}
    </div>

    {# Data element used to store component state data #}
    <span
        id="{{ route_name }}__data"
        {% if not multiselect and selected_items|length == 1 %}
        data-phac-aspc-autocomplete="{{ selected_items.0.label }}"
        {% endif %}
    ></span>

    {% if label is not None %}
    <label for="{{ route_name }}__textinput" class="form-label">{{ label }}</label>
    {% endif %}

    {% include "./ac_container.html" %}
    <div class="dropdown-menu" id="{{ route_name }}__items"></div>
</div>
{# This code snippet loads the required CSS and JS if not already loaded. #}
<script>
    (function () {
        const sc = document.createElement('script');
        sc.src = '{% static "autocomplete/js/autocomplete.js" %}';
        if (!Array.from(document.querySelectorAll('script')).map(s => s.src).includes(sc.src)) {
            document.body.appendChild(sc);
        }
        const ln = document.createElement('link');
        ln.href = '{% static 'autocomplete/css/autocomplete.css' %}';
        ln.rel = 'stylesheet';
        if (!Array.from(document.querySelectorAll('link')).map(s => s.href).includes(ln.href)) {
            document.getElementsByTagName('head')[0].appendChild(ln);
        }
        document.querySelector('#{{ route_name }}__container').addEventListener(
            'click',
            function(evt) {
                if (evt.target === this || evt.target.classList.contains('ac_container')) {
                    document.getElementById('{{ route_name }}__textinput').focus();
                }
            }
        );
    })();
</script>
