jQuery(window).on('elementor/frontend/init', function() {
    elementorFrontend.hooks.addAction('frontend/element_ready/form.default', function($scope) {
        var configStr = $scope.attr('data-dce-submit-on-change');
        if (!configStr) {
            return;
        }

        var config = JSON.parse(configStr);
        if (!config.fields || config.fields.length === 0) {
            return;
        }

        var widgetId = $scope.data('id');

        config.fields.forEach(function(customId) {
            var $inputs = jQuery('.elementor-element-' + widgetId + ' .elementor-field-group-' + customId +' input, .elementor-element-' + widgetId + ' .elementor-field-group-' + customId + ' select');
            
            $inputs.on('change', function() {
                var $field = jQuery(this).closest('.elementor-field-group');
                
                if ($field.siblings('.dce-form-step-bnt-next').length) {
                    // Multi-step form: click next button
                    $field.siblings('.dce-form-step-bnt-next').find('button').trigger('click');
                } else {
                    // Regular form: click submit button
                    jQuery(this).closest('form').find('.elementor-field-type-submit button').trigger('click');
                }
            });
        });

        // Remove Select2 arrow if present
        jQuery('.elementor-element-' + widgetId + ' .select2-selection__arrow').remove();
    });
});
