{% comment %}
Main Tom Select template.

**Context Variables:**
- widget: Contains configuration, plugin settings, URLs, selected items, etc.

**Blocks:**
- block select_element: Override to change the way the <select> is included.
- block tomselect_init: Override to alter the TomSelect initialization logic, including event handlers, fetch calls, and callback methods.
- block tomselect_plugins: Insert or override plugin-related JS configuration.
- block tomselect_extra_js: Add custom JS at the end of initialization.

**Overriding Example:**
To override only the plugin configuration, you might create:
`templates/django_tomselect/tomselect.html`:
{% block tomselect_plugins %}
    // Your custom plugin code here
{% endblock %}
This will append your changes to the default configuration.

To completely replace initialization logic, you could:
{% block tomselect_init %}
    // Your entirely custom initialization code here
{% endblock %}
This will replace the original code block if you use `{% block ... %}{% endblock %}` without super.

You can also extend and call `{{ block.super }}` to augment existing logic.

{% endcomment %}

{% load i18n %}

{% block select_element %}
    {% include "django_tomselect/render/select.html" with widget=widget %}
{% endblock select_element %}

<script>
    {% block tomselect_init %}
        // Initialize TomSelect after the DOM is loaded (if not using htmx)
        {% if not widget.use_htmx %}
            document.addEventListener("DOMContentLoaded", function(e) {
        {% endif %}

        // Example initialization variables
        let wasReset{{ widget.name }} = false;
        function logCallback(data) {
            console.log("%c Received callback data:", "color:red;", data);
        }

        // Constructing the originalFirstUrl function based on query and filters
        var originalFirstUrl = function(query) {
            let url = '{{ widget.autocomplete_url }}' + '?q=' + encodeURIComponent(query){% if 'autocomplete_params' in widget.keys and not widget.autocomplete_params == '' %} + '&{{ widget.autocomplete_params|safe }}'{% endif %};
            {% if "dependent_field" in widget.keys %}
                const dependentField = document.getElementById('id_{{ widget.dependent_field }}');
                const dependentValue = dependentField ? dependentField.value : '';
                url = `${url}&f='{{ widget.dependent_field }}__{{ widget.dependent_field_lookup }}=${dependentValue}'`;
            {% endif %}
            {% if "exclude_field" in widget.keys %}
                const excludeField = document.getElementById('id_{{ widget.exclude_field }}');
                const excludeValue = excludeField ? excludeField.value : '';
                url = `${url}&e='{{ widget.exclude_field }}__{{ widget.exclude_field_lookup }}=${excludeValue}'`;
            {% endif %}
            return url;
        };

        // TomSelect configuration object
        var config = {
            valueField: '{{ widget.value_field }}',
            labelField: '{{ widget.label_field }}',
            searchField: [],
            highlight: {% if widget.highlight %}true{% else %}false{% endif %},
            openOnFocus: {% if widget.open_on_focus %}true{% else %}false{% endif %},
            maxOptions: {% if widget.max_options %}{{ widget.max_options }}{% else %}null{% endif %},
            preload: {% if widget.preload == "focus" %}'focus'{% elif widget.preload %}true{% else %}false{% endif %},
            maxItems: {% if not widget.is_multiple %}1{% else %}{% if widget.max_items %}{{ widget.max_items }}{% else %}null{% endif %}{% endif %},
            showValueField: {% if 'dropdown_header' in widget.plugins.keys and widget.plugins.dropdown_header.show_value_field %}true{% else %}false{% endif %},
            create: {% if 'create' in widget.keys and widget.create %}true{% else %}false{% endif %},

            {% block tomselect_plugins %}
                plugins: {
                    {% if 'checkbox_options' in widget.plugins.keys and widget.plugins.checkbox_options %}
                        checkbox_options: true,
                    {% endif %}

                    {% if 'clear_button' in widget.plugins.keys %}
                        clear_button: {
                            title: '{{ widget.plugins.clear_button.title }}',
                            className: '{{ widget.plugins.clear_button.class_name }}'
                        },
                    {% endif %}

                    {% comment %} {% if 'dropdown_header' in widget.plugins.keys %}
                        dropdown_header: {
                            title: '{{ widget.plugins.dropdown_header.title }}',
                            header_class: '{{ widget.plugins.dropdown_header.header_class }}',
                            title_row_class: '{{ widget.plugins.dropdown_header.title_row_class }}',
                            label_class: '{{ widget.plugins.dropdown_header.label_class }}',
                            value_field_label: '{{ widget.plugins.dropdown_header.value_field_label }}',
                            label_field_label: '{{ widget.plugins.dropdown_header.label_field_label }}',
                            label_col_class: '{{ widget.plugins.dropdown_header.label_col_class }}',
                            show_value_field: {% if widget.plugins.dropdown_header.show_value_field %}true{% else %}false{% endif %},
                            extra_columns: {{ widget.plugins.dropdown_header.extra_columns|safe }},
                            extra_headers: {{ widget.plugins.dropdown_header.extra_headers|safe }},
                            extra_values: {{ widget.plugins.dropdown_header.extra_values|safe }}
                        },
                    {% endif %} {% endcomment %}

                    {% if 'dropdown_header' in widget.plugins.keys %}
                        dropdown_header:{
                            title: '{% if widget.plugins.dropdown_header.title %}{{ widget.plugins.dropdown_header.title }}{% else %}Select an option{% endif %}',
                            headerClass: '{{ widget.plugins.dropdown_header.header_class }}',
                            {% include "django_tomselect/render/dropdown_header.html" with widget=widget %}
                        },
                    {% endif %}


                    {% comment %} {% if 'dropdown_footer' in widget.plugins.keys %}
                        dropdown_footer: {
                            title: '{{ widget.plugins.dropdown_footer.title }}',
                            footer_class: '{{ widget.plugins.dropdown_footer.footer_class }}',
                            create_view_label: '{{ widget.plugins.dropdown_footer.create_view_label }}',
                            create_view_class: '{{ widget.plugins.dropdown_footer.create_view_class }}',
                            list_view_label: '{{ widget.plugins.dropdown_footer.list_view_label }}',
                            list_view_class: '{{ widget.plugins.dropdown_footer.list_view_class }}'
                        },
                    {% endif %} {% endcomment %}

                    {% if 'dropdown_footer' in widget.plugins.keys %}
                        dropdown_footer:{
                            title: '{% if widget.plugins.dropdown_footer.title %}{{ widget.plugins.dropdown_footer.title }}{% else %}Select an option{% endif %}',
                            footerClass: '{{ widget.plugins.dropdown_footer.footer_class }}',
                            {% include "django_tomselect/render/dropdown_footer.html" with widget=widget %}
                        },
                    {% endif %}

                    {% if 'dropdown_input' in widget.plugins.keys and widget.plugins.dropdown_input %}
                        dropdown_input: true,
                    {% endif %}

                    {% if 'remove_button' in widget.plugins.keys %}
                        remove_button: {
                            title: '{{ widget.plugins.remove_button.title }}',
                            label: '{{ widget.plugins.remove_button.label|safe }}',
                            className: '{{ widget.plugins.remove_button.class_name }}'
                        },
                    {% endif %}

                    virtual_scroll: true
                },
            {% endblock tomselect_plugins %}

            {% if widget.value %}
                onInitialize: function() {
                    {% for option in widget.selected_options %}
                        this.addOption({
                            {{ widget.value_field }}: '{{ option.value }}',
                            {{ widget.label_field }}: '{{ option.label }}',
                            {% if "create_url" in option.keys %}create_url: '{{ option.create_url }}',{% endif %}
                            {% if "detail_url" in option.keys %}detail_url: '{{ option.detail_url }}',{% endif %}
                            {% if "update_url" in option.keys %}update_url: '{{ option.update_url }}',{% endif %}
                            {% if "delete_url" in option.keys %}delete_url: '{{ option.delete_url }}',{% endif %}
                        });
                        this.addItem('{{ option.value }}');
                    {% endfor %}
                },
            {% endif %}

            shouldLoad: function(query){
                var shouldLoadValue;
                if (this.settings.page && (!query.trim() || query === undefined)) {
                    shouldLoadValue = true;
                } else {
                    shouldLoadValue = query.length >= {{ widget.minimum_query_length }};
                }
                return shouldLoadValue;
            },

            firstUrl: originalFirstUrl,

            getUrl: function(query) {
                let url = this.settings.pagination[query] || this.settings.firstUrl(query);
                return url;
            },

            load: function(query, callback) {
                let url = this.getUrl(query);
                if (wasReset{{ widget.name }} === true) {
                    url = originalFirstUrl(query);
                }

                fetch(url)
                    .then(response => response.json())
                    .then(json => {
                        if (json.has_more) {
                            url = url.replace(/&p=\d+/g, '');
                            {% if "dependent_field" in widget.keys or "exclude_field" in widget.keys %}
                                if (wasReset{{ widget.name }} === false) {
                                    this.setNextUrl(query, url + '&p=' + (json.page + 1));
                                } else {
                                    wasReset{{ widget.name }} = false;
                                    this.setNextUrl(query, url + '&p=1');
                                }
                            {% else %}
                                this.setNextUrl(query, url + '&p=' + (json.page + 1));
                            {% endif %}
                        }

                        const _scrollToOption = this.scrollToOption;
                        this.scrollToOption = () => {};
                        callback(json.results);
                        this.scrollToOption = _scrollToOption;
                    }).catch(() => {
                        console.log('%c Error loading data for {{ widget.name }}, url=', "color:red;", url);
                        callback();
                    })
            },

            render: {
                {% with widget.attrs as attrs %}
                    {% if 'data_custom_rendering' in attrs.keys and attrs.data_custom_rendering|default:False %}
                        option: function(data, escape) {
                            {{ attrs.data_template_option|safe }}
                        },
                        item: function(data, escape) {
                            {{ attrs.data_template_item|safe }}
                        },
                    {% elif 'render' in attrs.keys %}
                        {% if attrs.render.option|default:False %}
                            option: function(data, escape) {
                                {{ attrs.render.option|safe }}
                            },
                        {% endif %}
                        {% if attrs.render.item|default:False %}
                            item: function(data, escape) {
                                {{ attrs.render.item|safe }}
                            },
                        {% endif %}
                    {% else %}
                        {% include "django_tomselect/render/item.html" with widget=widget %}
                        {% include "django_tomselect/render/option.html" with widget=widget %}
                    {% endif %}
                {% endwith %}

                {% include "django_tomselect/render/loading.html" with widget=widget %}
                {% include "django_tomselect/render/loading_more.html" with widget=widget %}
                {% include "django_tomselect/render/no_more_results.html" with widget=widget %}
                {% include "django_tomselect/render/no_results.html" with widget=widget %}
                {% include "django_tomselect/render/not_loading.html" with widget=widget %}
                {% if 'create' in widget.keys and widget.create %}
                    {% include "django_tomselect/render/option_create.html" with widget=widget %}
                {% endif %}
            }

        };

        var {{ widget.name }} = new TomSelect('#{% if 'id' in widget.attrs.keys and widget.attrs.id %}{{ widget.attrs.id }}{% else %}{{ widget.name }}{% endif %}', config);

        {% if 'render' in widget.attrs.keys and widget.attrs.render %}
            {{ widget.name }}.on('option_add', function(value, data) {
                // Preserve rich data for rendering
                this.options[value] = data;
            });

            {{ widget.name }}.on('load', function(data) {
                // Ensure all loaded data is preserved
                data.forEach(item => {
                    this.options[item.id] = item;
                });
            });
        {% endif %}

        // Dependent/exclude field change handling
        var change_handler = function(value) {
            const tomSelect = {{ widget.name }};

            tomSelect.clear();
            tomSelect.clearOptions();
            tomSelect.clearCache();
            tomSelect.settings.pagination = {};

            if (tomSelect.dropdown_content) {
                tomSelect.dropdown_content.scrollTop = 0;
            }

            tomSelect.settings.firstUrl = originalFirstUrl;
            tomSelect.settings.setNextUrl = originalFirstUrl;
            tomSelect.clearPagination();
            tomSelect.load('', logCallback);

            wasReset{{ widget.name }} = true;
        };

        {% if "dependent_field" in widget.keys %}
            const dependentField = document.getElementById('id_{{ widget.dependent_field }}');
            if (dependentField && dependentField.tomselect) {
                dependentField.tomselect.on('change', change_handler);
            }
        {% endif %}
        {% if "exclude_field" in widget.keys %}
            const excludeField = document.getElementById('id_{{ widget.exclude_field }}');
            if (excludeField && excludeField.tomselect) {
                excludeField.tomselect.on('change', change_handler);
            }
        {% endif %}

        {% if not widget.use_htmx %}
        });
        {% endif %}
    {% endblock tomselect_init %}

    {% block tomselect_extra_js %}{% endblock tomselect_extra_js %}
</script>
