// Scroll to Top Functionality
class ScrollToTop {
    constructor() {
        this.scrollBtn = document.getElementById('scrollToTopBtn');
        this.init();
    }

    init() {
        if (!this.scrollBtn) return;
        
        this.setupEventListeners();
        this.handleScroll();
    }

    setupEventListeners() {
        // Show/hide button on scroll
        window.addEventListener('scroll', () => this.handleScroll());
        
        // Smooth scroll to top on click
        this.scrollBtn.addEventListener('click', () => this.scrollToTop());
    }

    handleScroll() {
        const scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
        
        if (scrollPosition > 300) {
            this.showButton();
        } else {
            this.hideButton();
        }
    }

    showButton() {
        this.scrollBtn.classList.add('visible');
    }

    hideButton() {
        this.scrollBtn.classList.remove('visible');
    }

    scrollToTop() {
        const startPosition = window.pageYOffset;
        const duration = 500;
        const startTime = performance.now();

        const animateScroll = (currentTime) => {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            
            // Easing function for smooth animation
            const easeOutCubic = 1 - Math.pow(1 - progress, 3);
            
            window.scrollTo(0, startPosition * (1 - easeOutCubic));
            
            if (progress < 1) {
                requestAnimationFrame(animateScroll);
            }
        };

        requestAnimationFrame(animateScroll);
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new ScrollToTop();
});