
(function() {

    function initTomSelect() {
        var elements = document.querySelectorAll('select.dp-tom-select');

        elements.forEach(function(el) {

            // Skip if already initialized
            if (el.tomselect) {
                return;
            }

            var plugins = [];

            if (el.dataset.clearButton === 'true') {
                plugins.push('clear_button');
            }

            if (el.multiple) {
                plugins.push('remove_button');
            }

            var settings = {
                plugins: plugins,
                allowEmptyOption: true
            };

            if (el.dataset.placeholder) {
                settings.placeholder = el.dataset.placeholder;
            }

            if (el.dataset.closeAfterSelect !== undefined) {
                settings.closeAfterSelect = el.dataset.closeAfterSelect === 'true';
            }

            if (el.dataset.dropdownClass) {
                settings.dropdownClass = 'ts-dropdown ' + el.dataset.dropdownClass;
            }

            // Store initial value before TomSelect clears it
            var initialValue = el.value || el.dataset.ajaxInitialValue;

            // Handle AJAX selects
            if (el.dataset.ajaxUrl) {
                var ajaxUrl = el.dataset.ajaxUrl;
                var separator = ajaxUrl.indexOf('?') !== -1 ? '&' : '?';

                settings.valueField = 'id';
                settings.labelField = 'text';
                settings.searchField = ['text'];
                settings.loadThrottle = parseInt(el.dataset.ajaxDelay) || 250;
                settings.preload = 'focus';
                //settings.allowEmptyOption = true;
                //settings.hidePlaceholder = false;
                settings.hideSelected = false;

                settings.load = function(query, callback) {
                    var url = ajaxUrl + separator + 'q=' + encodeURIComponent(query);
                    fetch(url)
                        .then(function(response) {
                            return response.json();
                        })
                        .then(function(json) {
                            callback(json.results);
                        })
                        .catch(function(err) {
                            console.error('TomSelect AJAX error:', err);
                            callback();
                        });
                };
            }

            // For AJAX selects with initial value: clear value first, then fetch and set properly
            if (el.dataset.ajaxUrl && initialValue) {
                el.value = '';
                var ts = new TomSelect(el, settings);
                var url = el.dataset.ajaxInitialUrl || el.dataset.ajaxUrl;
                fetch(url)
                    .then(function(response) {
                        return response.json();
                    })
                    .then(function(json) {
			// compatibility for select2 ajax calls
			if (json.value) {
			    json = { id: json.value, text: json.label };
			}
                        ts.clearOptions();
                        ts.addOption(json);
                        ts.setValue(Number(initialValue));
                    });
            } else {
                new TomSelect(el, settings);
            }
        });
    }

    // Run immediately if DOM is ready, otherwise wait
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initTomSelect);
    } else {
        initTomSelect();
    }
})();
