{% set id = id ?? "selectize#{random()}" %}
{% set selectizeOptions = {
    dropdownParent: 'body',
}|merge(selectizeOptions ?? []) %}

{# Normalize the options #}
{% set options = (options ?? [])|map((o, k) => (o.optgroup is defined or o.value is defined) ? o : {
    value: k,
    label: o.label is defined ? o.label : o,
}) %}

{% if includeEnvVars ?? false %}
    {% if allowedEnvValues is not defined %}
        {% set allowedEnvValues = options|filter(o => o.optgroup is not defined)|map(o => o.value) %}
    {% endif %}
    {% set options = options|map(o => o.data.data.hint is defined ? o : o|merge({
        data: {
            data: {
                hint: o.value,
            }
        },
    }, recursive=true))|merge(craft.cp.getEnvOptions(allowedEnvValues)) %}
{% endif %}

{% include '_includes/forms/select' with {
    class: (class ?? [])|explodeClass|push('selectize')|unique,
} %}

{% js %}
(() => {
    const label = (data, showHint) => {
        let label = Craft.escapeHtml(data.text);
        const status = (() => {
            if (typeof data.status !== 'undefined') {
                return data.status;
            }
            if (typeof data.boolean !== 'undefined') {
                return data.boolean ? 'green' : 'white';
            }
            return null;
        })();
        if (status) {
            label = `<span class="status ${status}"></span>${label}`;
        }
        if (showHint && typeof data.hint === 'string' && data.hint !== '') {
            label += ` <span class="light">– ${Craft.escapeHtml(data.hint)}</span>`;
        }
        return label;
    };

    const $select = $("#{{ id|namespaceInputId|e('js') }}");

    const updateBooleanValue = () => {
        const boolean = $select.data('selectize').$wrapper.find('.item').data('boolean');
        if (typeof boolean !== 'undefined') {
            $select.data('boolean', !!boolean);
        } else {
            $select.removeData('boolean');
        }
    };

    $select.selectize($.extend({
        render: {
            option: data => {
                const classes = ['option'];
                if (data.value === '') {
                    classes.push('selectize-dropdown-emptyoptionlabel');
                }
                return `<div class="${classes.join(' ')}">${label(data, true)}</div>`;
            },
            item: data => {
                const attrs = ['class="item"'];
                if (typeof data.boolean !== 'undefined') {
                    attrs.push(`data-boolean="${data.boolean ? '1' : ''}"`);
                }
                return `<div ${attrs.join(' ')}>${label(data, false)}</div>`;
            },
        },
        onChange: updateBooleanValue,
    }, {{ selectizeOptions|json_encode|raw }}));

    updateBooleanValue();
})()
{% endjs %}
