/**
 * DESCRIPTION: Multistep progressbar preview for Elementor editor
 *
 * Populates the progressbar in Elementor preview with minimal HTML structure
 * since the normal JS initialization may not run in the editor context.
 */
(function($) {
    'use strict';

    var initializationAttempts = 0;
    var maxAttempts = 10;
    var initializationDelay = 500; // ms

    /**
     * Main initialization function with retry logic
     */
    function initWPUFStepPreview() {
        var $wrappers = $('.wpuf-elementor-step-preview');

        if ($wrappers.length === 0) {
            initializationAttempts++;
            if (initializationAttempts < maxAttempts) {
                setTimeout(initWPUFStepPreview, initializationDelay);
            }
            return;
        }

        // Reset attempts on success
        initializationAttempts = 0;

        $wrappers.each(function() {
            var $wrapper = $(this);
            var multistepType = $wrapper.data('wpuf-multistep-type');
            var $progressbar = $wrapper.find('.wpuf-multistep-progressbar');

            if ($progressbar.length === 0) {
                return;
            }

            // Skip if already initialized
            var hasFill = $progressbar.find('.wpuf-progress-percentage').length > 0;
            var hasPercentage = $progressbar.find('.wpuf-progressbar-fill').length > 0;
            var hasWizard = $progressbar.find('.wpuf-step-wizard').length > 0;

            if (hasFill || hasPercentage || hasWizard) {
                return;
            }

            if (multistepType === 'progressive') {
                initProgressivePreview($wrapper, $progressbar);
            } else {
                initStepByStepPreview($wrapper, $progressbar);
            }
        });
    }

    /**
     * Initialize progressive progressbar preview
     */
    function initProgressivePreview($wrapper, $progressbar) {
        // Get total steps from data attribute (actual count, not filtered)
        var totalStepsFromAttr = $wrapper.data('wpuf-total-steps');
        var totalSteps = parseInt(totalStepsFromAttr) || 0;
        var $fieldsets = $wrapper.find('fieldset.wpuf-multistep-fieldset');

        // Fallback to DOM count if data attribute not available
        if (totalSteps === 0) {
            totalSteps = $fieldsets.length;
        }

        var currentStep = 1; // First step is active in preview

        if (totalSteps === 0) {
            return;
        }

        // Add ui-progressbar class for styling
        $progressbar.addClass('ui-progressbar');

        // Calculate progress percentage for first step
        var progressPercent = Math.round((currentStep / totalSteps) * 100);

        // Create the fill element
        var $fill = $('<div class="wpuf-progressbar-fill"></div>').css('width', progressPercent + '%');

        // Create the percentage text element
        var $percentage = $('<div class="wpuf-progress-percentage"></div>');

        // Get the first step legend text
        var stepText = '';
        var firstFieldset = $fieldsets.first();

        if (firstFieldset.length) {
            var legendText = firstFieldset.find('legend').first().text().trim();

            if (legendText) {
                stepText = legendText + ' (' + progressPercent + '%)';
            } else {
                stepText = progressPercent + '%';
            }
        }
        $percentage.text(stepText);

        // Add elements to progressbar
        $progressbar.append($fill).append($percentage);
    }

    /**
     * Initialize step-by-step progressbar preview
     */
    function initStepByStepPreview($wrapper, $progressbar) {
        // Get total steps from data attribute (actual count, not filtered)
        var totalStepsFromAttr = $wrapper.data('wpuf-total-steps');
        var totalSteps = parseInt(totalStepsFromAttr) || 0;
        var $fieldsets = $wrapper.find('fieldset.wpuf-multistep-fieldset');

        // Fallback to DOM count if data attribute not available
        if (totalSteps === 0) {
            totalSteps = $fieldsets.length;
        }

        if (totalSteps === 0) {
            return;
        }

        // Create the step wizard list
        var $wizard = $('<ul class="wpuf-step-wizard"></ul>');

        // Add a step for each fieldset
        $fieldsets.each(function(index) {
            var $fieldset = $(this);
            var legendText = $fieldset.find('legend').first().text().trim();

            // Create step item
            var $li = $('<li>' + legendText + '</li>');

            // Mark first step as active
            if (index === 0) {
                $li.addClass('active-step');
            }

            $wizard.append($li);
        });

        // Add wizard to progressbar
        $progressbar.append($wizard);
    }

    // Multiple initialization strategies for Elementor's async loading

    // Strategy 1: On DOM ready
    $(document).ready(function() {
        // Delay slightly to let Elementor finish rendering
        setTimeout(initWPUFStepPreview, 100);
    });

    // Strategy 2: On Elementor render event (if it fires)
    $(document).on('elementor/render/wpuf-form', function() {
        initializationAttempts = 0; // Reset attempts
        initWPUFStepPreview();
    });

    // Strategy 3: On Elementor frontend preview render (alternative event)
    $(document).on('elementor/frontend/preview/rendered', function() {
        initializationAttempts = 0; // Reset attempts
        initWPUFStepPreview();
    });

    // Strategy 4: Watch for DOM changes using MutationObserver (most reliable)
    if (window.MutationObserver) {
        var observer = new MutationObserver(function(mutations) {
            // Check if any wpuf-elementor-step-preview elements were added
            var hasNewWrappers = false;
            mutations.forEach(function(mutation) {
                if (mutation.addedNodes && mutation.addedNodes.length) {
                    for (var i = 0; i < mutation.addedNodes.length; i++) {
                        var node = mutation.addedNodes[i];
                        if (node.nodeType === 1) { // Element node
                            if ($(node).hasClass('wpuf-elementor-step-preview') ||
                                $(node).find('.wpuf-elementor-step-preview').length > 0) {
                                hasNewWrappers = true;
                                break;
                            }
                        }
                    }
                }
            });

            if (hasNewWrappers) {
                initializationAttempts = 0; // Reset attempts
                setTimeout(initWPUFStepPreview, 50);
            }
        });

        // Start observing the document body
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    // Strategy 5: Periodic check as fallback (only for a limited time)
    var periodicCheckCount = 0;
    var periodicCheck = setInterval(function() {
        periodicCheckCount++;
        var $wrappers = $('.wpuf-elementor-step-preview');
        var $uninitialized = $wrappers.filter(function() {
            var $pb = $(this).find('.wpuf-multistep-progressbar');
            return $pb.length === 0 ||
                   ($pb.find('.wpuf-progress-percentage').length === 0 &&
                    $pb.find('.wpuf-progressbar-fill').length === 0 &&
                    $pb.find('.wpuf-step-wizard').length === 0);
        });

        if ($uninitialized.length > 0) {
            initializationAttempts = 0;
            initWPUFStepPreview();
        }

        // Stop periodic checks after 30 seconds
        if (periodicCheckCount >= 60) {
            clearInterval(periodicCheck);
        }
    }, 500);

    // Stop periodic checks when window is fully loaded
    $(window).on('load', function() {
        setTimeout(function() {
            initializationAttempts = 0;
            initWPUFStepPreview();
        }, 500);
    });

})(jQuery);
