(function() {
    'use strict';

    if (typeof scrollToTopSettings === 'undefined') {
        return;
    }

    const settings = scrollToTopSettings;
    let button = null;
    let scrollTimeout = null;

    function createButton() {
        button = document.createElement('div');
        button.className = 'scroll-to-top-button';
        button.setAttribute('aria-label', 'Scroll to top');
        
        button.classList.add('stt-style-' + settings.style);
        button.classList.add('stt-size-' + settings.size);
        button.classList.add('stt-position-' + settings.position);
        
        if (!settings.showMobile) {
            button.classList.add('stt-hide-mobile');
        }
        
        const content = document.createElement('span');
        content.className = 'stt-button-content';
        button.appendChild(content);
        
        document.body.appendChild(button);
        
        applyStyles();
        addEventListeners();
    }

    function applyStyles() {
        if (!button) return;
        
        button.style.backgroundColor = settings.bgColor;
        button.style.color = settings.textColor;
        
        if (settings.position === 'bottom-right') {
            button.style.right = '20px';
            button.style.left = 'auto';
        } else {
            button.style.left = '20px';
            button.style.right = 'auto';
        }
    }

    function handleScroll() {
        if (!button) return;
        
        clearTimeout(scrollTimeout);
        
        scrollTimeout = setTimeout(function() {
            if (window.scrollY > 200) {
                button.classList.add('visible');
            } else {
                button.classList.remove('visible');
            }
        }, 10);
    }

    function scrollToTop(e) {
        e.preventDefault();
        
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    }

    function addEventListeners() {
        if (!button) return;
        
        window.addEventListener('scroll', handleScroll, { passive: true });
        
        button.addEventListener('click', scrollToTop);
    }

    function init() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', createButton);
        } else {
            createButton();
        }
    }

    init();
})();
