/**
 * Frontend multistep (step field) behavior.
 * Extends WP_User_Frontend when loaded after wpuf-frontend-form.
 */
(function ($, window) {

    if (typeof window.WP_User_Frontend === 'undefined') {
        return;
    }

    var stepNumber = 0;
    var enableMultistepRetried = false;

    window.WP_User_Frontend.enableMultistep = function (o) {
        var progressbarType = $(':hidden[name="wpuf_multistep_type"]').val();
        if (progressbarType == null) {
            var $wrapper = $('.wpuf-elementor-step-preview');
            if ($wrapper.length) {
                progressbarType = $wrapper.attr('data-wpuf-multistep-type') || 'step_by_step';
            } else if (!enableMultistepRetried) {
                enableMultistepRetried = true;
                setTimeout(function () {
                    window.WP_User_Frontend.enableMultistep(o);
                }, 250);
                return;
            }
        }
        if (progressbarType == null) {
            return;
        }

        $('fieldset.wpuf-multistep-fieldset').find('.wpuf-multistep-prev-btn').first().remove();
        $('fieldset.wpuf-multistep-fieldset').find('.wpuf-multistep-next-btn').last().remove();

        $('.wpuf-form fieldset').removeClass('field-active').first().addClass('field-active');

        if (progressbarType === 'progressive' && $('.wpuf-form .wpuf-multistep-fieldset').length !== 0) {
            var totalSteps = $('.wpuf-form .wpuf-multistep-fieldset').length;

            var firstStepText = (typeof wpuf_frontend !== 'undefined' && wpuf_frontend.step_progress)
                ? wpuf_frontend.step_progress.replace('%step%', 1).replace('%total%', totalSteps)
                : 'Step 1 of ' + totalSteps;

            $('.wpuf-multistep-progressbar').html(
                '<div class="wpuf-progressbar-header">' +
                    '<span class="wpuf-progressbar-step-text">' + firstStepText + '</span>' +
                    '<span class="wpuf-progressbar-percent">0%</span>' +
                '</div>' +
                '<div class="wpuf-progressbar-track">' +
                    '<div class="wpuf-progressbar-fill" style="width: 0%;"></div>' +
                '</div>'
            );

            $('.wpuf-multistep-fieldset legend').hide();
        } else {
            $('.wpuf-form').each(function () {
                var thisObj = $(this);
                var progressbar = $('.wpuf-multistep-progressbar', thisObj);
                var $fieldsets = $('.wpuf-multistep-fieldset', thisObj);
                var totalSteps = $fieldsets.length;

                if (!totalSteps) {
                    return;
                }

                progressbar.addClass('wizard-steps');

                var $wizard = $('<div class="wpuf-step-wizard"></div>');

                $fieldsets.each(function (index) {
                    var label = $.trim($('legend', this).text());
                    $('legend', this).hide();

                    var $item = $('<div class="wpuf-step-item"></div>');
                    $item.append('<div class="wpuf-step-circle">' + (index + 1) + '</div>');
                    $item.append($('<div class="wpuf-step-label"></div>').text(label));
                    $wizard.append($item);

                    if (index < totalSteps - 1) {
                        $wizard.append('<div class="wpuf-step-line"></div>');
                    }
                });

                progressbar.append($wizard);

                $('.wpuf-step-item', progressbar).first().addClass('active-step');
            });
        }

        o.change_fieldset(stepNumber, progressbarType);

        $('fieldset .wpuf-multistep-prev-btn, fieldset .wpuf-multistep-next-btn').on('click', function (e) {
            e.preventDefault();

            if ($(this).hasClass('wpuf-multistep-next-btn')) {
                var result = window.WP_User_Frontend.formStepCheck('', $(this).closest('fieldset'));

                if (result !== false) {
                    o.change_fieldset(++stepNumber, progressbarType);
                }
            } else if ($(this).hasClass('wpuf-multistep-prev-btn')) {
                o.change_fieldset(--stepNumber, progressbarType);
            }

            var formDiv = $('form.wpuf-form-add');
            var position = formDiv.offset().top;

            window.scrollTo({
                top: position - 32,
                behavior: 'smooth'
            });

            return false;
        });
    };

    window.WP_User_Frontend.change_fieldset = function (stepNumber, progressbarType) {
        var currentStep = $('fieldset.wpuf-multistep-fieldset').eq(stepNumber);

        $('fieldset.wpuf-multistep-fieldset').removeClass('field-active').eq(stepNumber).addClass('field-active');

        $('.wpuf-step-wizard').each(function () {
            var $wizard = $(this);
            var $items = $wizard.find('.wpuf-step-item');
            var $lines = $wizard.find('.wpuf-step-line');

            if ($items.length) {
                $items.removeClass('active-step completed-step passed-wpuf-ms-bar wpuf-ms-bar-active');

                $items.each(function (index) {
                    if (index < stepNumber) {
                        $(this).addClass('completed-step passed-wpuf-ms-bar');
                    } else if (index === stepNumber) {
                        $(this).addClass('active-step wpuf-ms-bar-active passed-wpuf-ms-bar');
                    }
                });

                $lines.removeClass('wpuf-step-line-active');
                $lines.each(function (index) {
                    if (index < stepNumber) {
                        $(this).addClass('wpuf-step-line-active');
                    }
                });
            } else {
                // Legacy markup fallback (older custom templates)
                var $li = $wizard.find('li');
                $li.each(function () {
                    if ($(this).index() <= stepNumber) {
                        progressbarType === 'step_by_step' ? $(this).addClass('passed-wpuf-ms-bar') : $('.wpuf-ps-bar', this).addClass('passed-wpuf-ms-bar');
                    } else {
                        progressbarType === 'step_by_step' ? $(this).removeClass('passed-wpuf-ms-bar') : $('.wpuf-ps-bar', this).removeClass('passed-wpuf-ms-bar');
                    }
                });

                $li.removeClass('wpuf-ms-bar-active active-step completed-step');
                $wizard.find('.passed-wpuf-ms-bar').addClass('completed-step').last().addClass('wpuf-ms-bar-active');
                $wizard.find('.wpuf-ms-bar-active').addClass('active-step');
            }
        });

        var legend = $('fieldset.wpuf-multistep-fieldset').eq(stepNumber).find('legend').text();
        legend = $.trim(legend);

        if (progressbarType === 'progressive' && $('.wpuf-form .wpuf-multistep-fieldset').length !== 0) {
            var totalSteps = $('fieldset.wpuf-multistep-fieldset').length;
            var progressPercent = Math.round((stepNumber + 1) * 100 / totalSteps);

            var stepText = (typeof wpuf_frontend !== 'undefined' && wpuf_frontend.step_progress)
                ? wpuf_frontend.step_progress.replace('%step%', (stepNumber + 1)).replace('%total%', totalSteps)
                : 'Step ' + (stepNumber + 1) + ' of ' + totalSteps;

            $('.wpuf-multistep-progressbar .wpuf-progressbar-fill').css('width', progressPercent + '%');
            $('.wpuf-multistep-progressbar .wpuf-progressbar-step-text').text(stepText);
            $('.wpuf-multistep-progressbar .wpuf-progressbar-percent').text(progressPercent + '%');
        }

        $('.wpuf-form').trigger('step-change-fieldset', [stepNumber, currentStep]);
    };

})(jQuery, window);
