{% load i18n %}<div{% if widget.attrs.id %} id="{{ widget.attrs.id|safe }}"{% endif %} class="frontend-icon-picker{% if widget.attrs.class %} {{ widget.attrs.class }}{% endif %}">
    <div class="icon-container">
        <div id="{{ widget.attrs.id|safe }}-preview" class="icon-preview">
            <div class="icon-box">{{ widget.preview|safe }}</div>
            <div class="empty-box{% if widget.preview %} hidden{% endif %}">{% translate "Click to add icon" %}</div>
        </div>
        {% if not widget.required %}<div class="icon-close-indicator"></div>{% endif %}
    </div>
    <select{% if icon_libraries|length < 2 %} style="display: none;"{% endif %}>
        {% for value, verbose, json, css in icon_libraries %}
            <option value="{{ value }}" data-json="{{ json }}" data-css="{{ css }}">{{ verbose }}</option>
        {% endfor %}
    </select>
    <input hidden type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %} />
</div>
<script>
    (function ($) {
        var selectElement = $('#{{ widget.attrs.id|safe }} select');
        selectElement.val("{{ widget.library }}");
        if (!selectElement.val()) {
            selectElement.val("{{ icon_libraries.0.0 }}");
        }
        function setIcon(jsonIconData) {
            if (jsonIconData && jsonIconData.iconHtml) {
                jsonIconData.library = selectElement.val();
                $('#{{ widget.attrs.id|safe }} .icon-preview .icon-box' ).html(jsonIconData.iconHtml);
                $('#{{ widget.attrs.id|safe }} input[hidden]').val(JSON.stringify(jsonIconData));
                $('#{{ widget.attrs.id|safe }} .icon-preview .empty-box').addClass('hidden');
            } else {
                $('#{{ widget.attrs.id|safe }} .icon-preview .icon-box').html("");
                $('#{{ widget.attrs.id|safe }} input[hidden]').val("");
                $('#{{ widget.attrs.id|safe }} .icon-preview .empty-box').removeClass('hidden');
            }
        };
        var options = {
            selector: '#{{ widget.attrs.id|safe }}-preview',
            {% if not widget.required %}
                resetSelector: '#{{ widget.attrs.id|safe }} .icon-close-indicator',
            {% endif %}
            onSelect: setIcon,
            onReset: setIcon,
            iconLibraries: [selectElement.find(':selected').data('json')],
            iconLibrariesCss: [selectElement.find(':selected').data('css')],
            loadCustomCss: true,
            allowEmpty: false
        };
        var uip = new UniversalIconPicker(options.selector, options);
        selectElement.on('change', function () {
            uip.setOptions({
               iconLibraries: [this.options[this.selectedIndex].dataset.json],
               iconLibrariesCss: [this.options[this.selectedIndex].dataset.css]
            });
        });
    })(django.jQuery);
</script>
