(function($) {
    'use strict';

    function updatePreview() {
        const settings = {
            style: $('input[name="scroll_to_top_style"]:checked').val(),
            bgColor: $('input[name="scroll_to_top_bg_color"]').val(),
            textColor: $('input[name="scroll_to_top_text_color"]').val(),
            size: $('input[name="scroll_to_top_size"]').val(),
            position: $('input[name="scroll_to_top_position"]').val(),
        };

        const $button = $('#stt-preview-button');
        
        $button.css('background-color', settings.bgColor);
        $button.css('color', settings.textColor);
        
        $button.removeClass('stt-style-circle stt-style-arrow stt-style-text')
               .addClass('stt-style-' + settings.style);
        
        $button.removeClass('stt-size-small stt-size-medium stt-size-large')
               .addClass('stt-size-' + settings.size);
        
        $button.removeClass('stt-position-bottom-right stt-position-bottom-left')
               .addClass('stt-position-' + settings.position);
    }

    $(document).ready(function() {
        const $previewBox = $('.stt-preview-box');
        const $button = $('#stt-preview-button');
        
        updatePreview();
        
        $('input[name="scroll_to_top_style"]').change(function() {
            updatePreview();
        });
        
        $('input[name="scroll_to_top_bg_color"]').change(function() {
            updatePreview();
        });
        
        $('input[name="scroll_to_top_text_color"]').change(function() {
            updatePreview();
        });
        
        $('select[name="scroll_to_top_size"]').change(function() {
            updatePreview();
        });
        
        $('select[name="scroll_to_top_position"]').change(function() {
            updatePreview();
        });

        $previewBox.on('scroll', function() {
            if ($previewBox.scrollTop() > 50) {
                $button.addClass('visible');
            } else {
                $button.removeClass('visible');
            }
        });

        $button.on('click', function(e) {
            e.preventDefault();
            $previewBox.animate({ scrollTop: 0 }, 300);
        });
    });
})(jQuery);
