require(['jquery', 'cla_select2', 'domReady', 'cla_moment', 'cla_locale'], function ($, select2, domReady, moment, locale) {
    domReady(function () {
        $('.js-select2-field').select2({
            width: '100%',
            containerCss: {
                'min-height': '60px'
            }
        });
        
        document.querySelector('.filter-form').addEventListener('submit', function(event) {
            // Flag to track if any validation fails
            let validationFailed = false;

            // Iterate over each fieldset
            document.querySelectorAll('.js-date-range-fieldset').forEach(function(fieldset) {
                const fromDateInput = fieldset.querySelector('.js-date-from');
                const toDateInput = fieldset.querySelector('.js-date-to');

                const parsedFromDate = moment(fromDateInput.value, locale.date_format, true);
                const parsedToDate = moment(toDateInput.value, locale.date_format, true);

                // Validate the dates in this fieldset checking if the 'to' date is before the 'from' date
                if (moment(parsedToDate).isBefore(parsedFromDate)) {
                    validationFailed = true;
                    fieldset.querySelector('.invalid-feedback').classList.add('d-block');
                    fromDateInput.classList.add('is-invalid');
                    toDateInput.classList.add('is-invalid');
                }
            });

            // If any validation failed, do not submit the form
            if (validationFailed) {
                event.preventDefault();
                return;
            }

            // Otherwise, submit the form
            this.submit();
        });

        document.querySelectorAll('.js-date').forEach(function(element) {
            element.addEventListener('focus', function() {
                const parentFieldset = this.closest('.js-date-range-fieldset');
                const invalidFeedback = parentFieldset.querySelector('.invalid-feedback');
                const fromDateInput = parentFieldset.querySelector('.js-date-from');
                const toDateInput = parentFieldset.querySelector('.js-date-to');
                invalidFeedback.classList.remove('d-block');
                fromDateInput.classList.remove('is-invalid');
                toDateInput.classList.remove('is-invalid');
            });
        });
    })
});
