jQuery(document).ready(function ($) {
    'use strict';

    var $scrollToTopBtn = $('#ustt-scroll-to-top');
    var $progressBar = $('#ustt-progress-bar');
    var ticking = false;

    // Helper: Throttled Scroll
    function onScroll() {
        if (!ticking) {
            window.requestAnimationFrame(function () {
                updateUI();
                ticking = false;
            });
            ticking = true;
        }
    }

    // Initialize Progress Attributes (e.g. SVG path lengths)
    function initProgressAttributes() {
        $scrollToTopBtn.find('.ustt-progress-indicator[data-type="stroke"]').each(function () {
            var length = this.getTotalLength();
            this.style.strokeDasharray = length;
            this.style.strokeDashoffset = length; // Start empty
        });
    }

    if ($scrollToTopBtn.length) {
        initProgressAttributes();
    }

    function updateUI() {
        // Robust vanilla JS calculation
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        var docHeight = Math.max(
            document.body.scrollHeight, document.body.offsetHeight,
            document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight
        );
        var winHeight = window.innerHeight || document.documentElement.clientHeight ||
            document.getElementsByTagName('body')[0].clientHeight;

        var scrollPercent = 0;
        if (docHeight > winHeight) {
            scrollPercent = (scrollTop / (docHeight - winHeight)) * 100;
        }
        // Clamp
        scrollPercent = Math.min(100, Math.max(0, scrollPercent));

        // Scroll to Top Visibility
        if ($scrollToTopBtn.length) {
            if (scrollTop > 300) {
                $scrollToTopBtn.addClass('is-visible');
            } else {
                $scrollToTopBtn.removeClass('is-visible');
            }

            // Update Inner Progress Indicators
            updateScrollProgress($scrollToTopBtn, scrollPercent);
        }

        // Global Progress Bar (Top/Bottom)
        if ($progressBar.length) {
            $progressBar.css('width', scrollPercent + '%');
        }
    }

    // Generic function to update any progress indicator within a container
    function updateScrollProgress($container, percent) {
        // 1. Stroke (SVG)
        $container.find('.ustt-progress-indicator[data-type="stroke"]').each(function () {
            var length = parseFloat(this.style.strokeDasharray);
            // Fallback if not set (e.g. dynamic loaded)
            if (!length || isNaN(length)) {
                length = this.getTotalLength();
                this.style.strokeDasharray = length;
            }
            var offset = length - (length * percent / 100);
            this.style.strokeDashoffset = offset;
        });

        // 2. Width (Horizontal Bar)
        $container.find('.ustt-progress-indicator[data-type="width"]').each(function () {
            $(this).css('width', percent + '%');
        });

        // 3. Height (Vertical Bar/Fill)
        $container.find('.ustt-progress-indicator[data-type="height"]').each(function () {
            $(this).css('height', percent + '%');
        });

        // 4. Text (Percentage)
        $container.find('.ustt-progress-indicator[data-type="text"]').each(function () {
            $(this).text(Math.round(percent) + '%');
        });

        // 5. Steps (Opacity/Visibility)
        $container.find('.ustt-progress-container[data-type="steps"]').each(function () {
            var $steps = $(this).children();
            var totalSteps = $steps.length;
            var stepPercent = 100 / totalSteps;

            $steps.each(function (index) {
                var threshold = (index + 1) * stepPercent;
                if (percent >= threshold) {
                    $(this).addClass('active');
                } else {
                    $(this).removeClass('active');
                }
            });
        });

        // 6. Steps-Dots
        $container.find('.ustt-progress-container[data-type="steps-dots"]').each(function () {
            var dots = $(this).data('dots') || 12;
            var radius = $(this).data('radius') || 40;
            var $this = $(this);

            // Create dots if not exists
            if ($this.children().length === 0) {
                for (var i = 0; i < dots; i++) {
                    var angle = (i / dots) * 2 * Math.PI - (Math.PI / 2); // Start at top
                    var x = 50 + radius * Math.cos(angle); // Assuming 100x100 coord system approx
                    // Actually logic depends on CSS implementation. 
                    // Assuming CSS handles layout or we inject divs.
                    // The CSS provided in previous steps handled layout for some, but specific "dots" grid might need spans.
                    // Let's assume standard divs.
                    $this.append('<div class="ustt-dot"></div>');
                }
            }

            var $steps = $this.children();
            var stepPercent = 100 / dots;
            $steps.each(function (index) {
                var threshold = (index + 1) * stepPercent;
                if (percent >= threshold) {
                    $(this).addClass('active');
                } else {
                    $(this).removeClass('active');
                }
            });
        });
    }

    // Initialize
    if ($scrollToTopBtn.length || $progressBar.length) {
        $(window).on('scroll', onScroll);

        // Initial check on ready
        initProgressAttributes();
        updateUI();

        // Re-check on load (images/SVGs might shift layout)
        $(window).on('load', function () {
            initProgressAttributes();
            updateUI();
        });
    }

    // Smooth Scroll to Top
    if ($scrollToTopBtn.length) {
        $scrollToTopBtn.on('click', function (e) {
            e.preventDefault();
            $('html, body').animate({ scrollTop: 0 }, 800);
        });
    }

});
