(function ($) {
    var DCE_EnhancedMultiStep_Init = function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/form.default', function ($scope) {
            var $form = $scope.find('.elementor-form');
            var settings = $form.data('dce-enhanced-multi-step');

            if (!settings) {
                return;
            }

            if (settings.dce_step_scroll === 'yes') {
                // Scroll to Top on change
                setTimeout(function () {
                    let nextButtons = $form.find('.elementor-field-type-next');
                    let prevButtons = $form.find('.elementor-field-type-previous');
                    let stepButtons = nextButtons.add(prevButtons);
                    
                    stepButtons.on('click', function () {
                        let formOffset = $form.offset().top - 70;
                        jQuery("html, body").animate({ scrollTop: formOffset });
                    });
                }, 200);
            }

            if (settings.form_fields && settings.form_fields.length) {
                jQuery.each(settings.form_fields, function (index, afield) {
                    if (afield.field_type == 'step') {
                        var field = $scope.find('.elementor-field-group-' + afield.custom_id);
                        field.addClass("dce-form-step");
                        field.addClass("dce-form-step" + afield.custom_id);
                        field.attr('data-custom_id', afield.custom_id);
                        field.attr('id', 'dce-form-step-' + afield.custom_id);

                        if (settings.dce_step_legend) {
                            // Legend
                            var legend = jQuery('<legend class="elementor-step-legend elementor-column elementor-col-100"></legend>');
                            legend.text(afield.field_label);
                            field.prepend(legend);
                        }
                    }
                });
            }
        });
    };

    if (typeof elementorFrontend !== 'undefined' && elementorFrontend.hooks) {
        DCE_EnhancedMultiStep_Init();
    } else {
        $(window).on('elementor/frontend/init', DCE_EnhancedMultiStep_Init);
    }
})(jQuery);
