// Smooth Scroll to Top functionality
(function() {
    'use strict';
    
    // Wait for everything to load
    function initScrollToTop() {
        // Wait a bit for page loader to finish
        setTimeout(function() {
            let scrollButton = document.getElementById('scroll-to-top');
            
            // Create button if it doesn't exist
            if (!scrollButton) {
                scrollButton = document.createElement('button');
                scrollButton.id = 'scroll-to-top';
                scrollButton.className = 'scroll-to-top';
                scrollButton.setAttribute('aria-label', 'Scroll to top');
                scrollButton.setAttribute('title', 'Back to top');
                document.body.appendChild(scrollButton);
            }
            
            // Show/hide button based on scroll position
            function toggleButton() {
                if (!scrollButton) return;
                const scrollY = window.pageYOffset || window.scrollY || document.documentElement.scrollTop || 0;
                if (scrollY > 50) {
                    scrollButton.classList.add('visible');
                } else {
                    scrollButton.classList.remove('visible');
                }
            }
            
            // Smooth scroll to top
            function scrollToTop(e) {
                if (e) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            }
            
            // Throttle scroll event for better performance
            let ticking = false;
            function onScroll() {
                if (!ticking) {
                    window.requestAnimationFrame(function() {
                        toggleButton();
                        ticking = false;
                    });
                    ticking = true;
                }
            }
            
            // Event listeners
            window.addEventListener('scroll', onScroll, { passive: true });
            scrollButton.addEventListener('click', scrollToTop);
            
            // Initial check
            toggleButton();
        }, 500); // Small delay to ensure page loader is done
    }
    
    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initScrollToTop);
    } else {
        initScrollToTop();
    }
})();
