/**
 * AnchorKit Admin Media Handler
 * 
 * Handles media uploads and previews for the AnchorKit plugin admin.
 */
/* stylelint-disable */
let updateTestButton;

const anchorkitDebugLog = (...args) => {
    if (!window || !window.anchorkitDebug) {
        return;
    }

    if (window.console && typeof window.anchorkitDebugLog === 'function') {
        window.anchorkitDebugLog(...args);
    }
};

jQuery(function($) {
    // Make sure we have the media uploader
    if (typeof wp === 'undefined' || typeof wp.media === 'undefined') {
        console.error('WordPress Media API not available');
        return;
    }

    // Function to update the selected icon state based on the icon type
    function updateSelectedIconState() {
        // Get the selected value from the icon type selector
        var selectedType = $('select[name="anchorkit_back_to_top_icon_type"]').val();
        
        // Hide all content sections first
        $('.icon-type-content').hide();
        
        // Show the selected section
        if (selectedType === 'collection') {
            $('#collection-content').show();
            $('input[name="anchorkit_back_to_top_icon_color"]').closest('.form-group').show();
        } else if (selectedType === 'custom-image') {
            $('#custom-image-content').show();
            $('input[name="anchorkit_back_to_top_icon_color"]').closest('.form-group').hide();
        } else if (selectedType === 'html') {
            $('#html-content').show();
            $('input[name="anchorkit_back_to_top_icon_color"]').closest('.form-group').show();
        }

        // After toggling visibility, make sure the correct icon is visually highlighted
        highlightSelectedIcon();
    }

    // --------------------------------------------------
    // MD3 Selected State for Icon Options
    // --------------------------------------------------
    /**
     * Add the .selected class to the currently checked icon radio button's container
     * and remove it from all others to provide clear visual feedback.
     */
    function highlightSelectedIcon() {
        // Remove existing highlights
        $('.icon-option').removeClass('selected');

        // Add highlight only to the currently checked icon
        $('input[name="anchorkit_back_to_top_collection_icon"]:checked')
            .closest('.icon-option')
            .addClass('selected');
    }

    // When an icon in the collection is chosen, update highlight and preview
    $(document).on('change', 'input[name="anchorkit_back_to_top_collection_icon"]', function () {
        highlightSelectedIcon();
        updateButtonPreview();
    });

    // Make the entire icon-option div clickable to select the radio input
    $(document).on('click', '.icon-option', function (e) {
        // Prevent double-trigger if the click was on the input itself
        if ($(e.target).is('input[type="radio"]')) return;
        const radio = $(this).find('input[type="radio"]');
        if (radio.length) {
            radio.prop('checked', true).trigger('change');
        }
    });

    // Ensure the correct icon is highlighted on initial page load
    $(document).ready(function () {
        highlightSelectedIcon();
    });
    
    // Function to update the button preview
    function updateButtonPreview() {
        const previewContainer = $('#back-to-top-preview-container');
        if (previewContainer.length === 0) return;
        
        // Get all settings
        const settings = {
            width: $('input[name="anchorkit_back_to_top_width"]').val() || '40',
            height: $('input[name="anchorkit_back_to_top_height"]').val() || '40',
            opacity: $('input[name="anchorkit_back_to_top_opacity"]').val() || '80',
            bgColor: $('input[name="anchorkit_back_to_top_bg_color"]').val() || '#000000',
            hoverColor: $('input[name="anchorkit_back_to_top_hover_color"]').val() || '#444444',
            iconColor: $('input[name="anchorkit_back_to_top_icon_color"]').val() || '#ffffff',
            iconType: $('select[name="anchorkit_back_to_top_icon_type"]').val() || 'collection',
            // Get the most current selected radio button value
            collectionIcon: $('input[name="anchorkit_back_to_top_collection_icon"]:checked').val() || 'a-arrow-up-bold.svg',
            customIcon: $('#anchorkit_back_to_top_custom_icon').val() || '',
            customHTML: $('#anchorkit_back_to_top_custom_html').val() || '<i class="fas fa-arrow-up"></i>',
            iconWidth: $('input[name="anchorkit_back_to_top_icon_width"]').val() || '16',
            iconHeight: $('input[name="anchorkit_back_to_top_icon_height"]').val() || '16',
            progressIndicator: $('input[name="anchorkit_back_to_top_progress_indicator"]').is(':checked'),
            progressColor: $('input[name="anchorkit_back_to_top_progress_color"]').val() || '#ff5555',
            progressThickness: $('input[name="anchorkit_back_to_top_progress_thickness"]').val() || '3',
            customCSS: $('#anchorkit_back_to_top_custom_css').val() || ''
        };
        
        anchorkitDebugLog('updateButtonPreview - icon type:', settings.iconType);
        anchorkitDebugLog('updateButtonPreview - collection icon:', settings.collectionIcon);
        anchorkitDebugLog('updateButtonPreview - checked radio value:', $('input[name="anchorkit_back_to_top_collection_icon"]:checked').val());
        
        // Create button styling
        const buttonStyle = {
            width: settings.width + 'px',
            height: settings.height + 'px',
            backgroundColor: settings.bgColor,
            opacity: settings.opacity / 100,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            borderRadius: '50%',
            position: 'relative',
            cursor: 'pointer',
            transition: 'background-color 0.3s, transform 0.3s',
            margin: '20px auto',
            boxShadow: '0 2px 5px rgba(0, 0, 0, 0.2)'
        };
        
        // Update icon content based on selected type
        let iconContent = '';
        
        if (settings.iconType === 'collection') {
            // Force re-check the current radio button selection
            const currentCollectionIcon = $('input[name="anchorkit_back_to_top_collection_icon"]:checked').val() || 'a-arrow-up-bold.svg';
            anchorkitDebugLog('Collection icon - using:', currentCollectionIcon);
            
            // Use the SVG content from anchorkitArrowIcons if available
            if (typeof window.anchorkitArrowIcons !== 'undefined' && window.anchorkitArrowIcons[currentCollectionIcon]) {
                let svgContent = window.anchorkitArrowIcons[currentCollectionIcon];
                svgContent = svgContent.replace(/width="[^"]*"/, `width="${settings.iconWidth}"`);
                svgContent = svgContent.replace(/height="[^"]*"/, `height="${settings.iconHeight}"`);
                svgContent = svgContent.replace(/fill="[^"]*"/, `fill="${settings.iconColor}"`);
                iconContent = svgContent;
                anchorkitDebugLog('Using SVG content from anchorkitArrowIcons');
            } else {
                // Fallback to default arrow
                iconContent = `<svg xmlns="http://www.w3.org/2000/svg" width="${settings.iconWidth}" height="${settings.iconHeight}" fill="${settings.iconColor}" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M8 15a.5.5 0 0 0 .5-.5V2.707l3.146 3.147a.5.5 0 0 0 .708-.708l-4-4a.5.5 0 0 0-.708 0l-4 4a.5.5 0 1 0 .708.708L7.5 2.707V14.5a.5.5 0 0 0 .5.5z"/></svg>`;
                anchorkitDebugLog('Using fallback icon (anchorkitArrowIcons not available or icon not found)');
            }
        } else if (settings.iconType === 'custom-image' && settings.customIcon) {
            iconContent = `<img src="${settings.customIcon}" style="width:${settings.iconWidth}px; height:${settings.iconHeight}px; display:block; object-fit:contain;" alt="Back to Top Icon">`;
        } else if (settings.iconType === 'html' && settings.customHTML) {
            iconContent = `<div style="color:${settings.iconColor}; width:${settings.iconWidth}px; height:${settings.iconHeight}px;">${settings.customHTML}</div>`;
        } else {
            // Default fallback icon
            iconContent = `<svg xmlns="http://www.w3.org/2000/svg" width="${settings.iconWidth}" height="${settings.iconHeight}" fill="${settings.iconColor}" viewBox="0 0 16 16">
            <path fill-rule="evenodd" d="M8 15a.5.5 0 0 0 .5-.5V2.707l3.146 3.147a.5.5 0 0 0 .708-.708l-4-4a.5.5 0 0 0-.708 0l-4 4a.5.5 0 1 0 .708.708L7.5 2.707V14.5a.5.5 0 0 0 .5.5z"/>
            </svg>`;
        }
        
        // Create the button element
        const buttonElement = $('<button id="back-to-top-preview"></button>');
        buttonElement.css(buttonStyle);
        buttonElement.html(iconContent);
        
        // Add hover effects
        buttonElement.hover(
            function() {
                $(this).css({
                    'background-color': settings.hoverColor,
                    'transform': 'translateY(-5px)'
                });
            },
            function() {
                $(this).css({
                    'background-color': settings.bgColor,
                    'transform': 'translateY(0)'
                });
            }
        );
        
        // Update the preview container with the button
        previewContainer.html(buttonElement);
        
        // Apply custom CSS if provided
        $('#anchorkit-preview-custom-css').remove();
        if (settings.customCSS && settings.customCSS.trim() !== '') {
            // Create a style element with the custom CSS, but apply it only to the preview button
            const modifiedCSS = settings.customCSS.replace(/#anchorkit-back-to-top/g, '#back-to-top-preview');
            $('<style id="anchorkit-preview-custom-css">' + modifiedCSS + '</style>').appendTo('head');
        }
        
        // Progress indicator preview
        if (settings.progressIndicator) {
            // Remove any existing progress styles
            $('#preview-progress-styles').remove();
            
            // Add progress indicator styles
            const progressStyle = `
            <style id="preview-progress-styles">
                :root {
                    --anchorkit-preview-progress-color: ${settings.progressColor};
                    --anchorkit-preview-progress-thickness: ${settings.progressThickness}px;
                    --anchorkit-preview-progress-bg-color: ${settings.bgColor};
                    --anchorkit-preview-progress-hover-color: ${settings.hoverColor};
                }
                
                #back-to-top-preview {
                    background: conic-gradient(
                        var(--anchorkit-preview-progress-color, ${settings.progressColor}) 25%, 
                        var(--anchorkit-preview-progress-bg-color, ${settings.bgColor}) 0
                    ) !important;
                }
                #back-to-top-preview::before {
                    content: "";
                    position: absolute;
                    top: var(--anchorkit-preview-progress-thickness, ${settings.progressThickness}px);
                    right: var(--anchorkit-preview-progress-thickness, ${settings.progressThickness}px);
                    bottom: var(--anchorkit-preview-progress-thickness, ${settings.progressThickness}px);
                    left: var(--anchorkit-preview-progress-thickness, ${settings.progressThickness}px);
                    background-color: var(--anchorkit-preview-progress-bg-color, ${settings.bgColor});
                    border-radius: 50%;
                    z-index: 0;
                }
                #back-to-top-preview:hover::before {
                    background-color: var(--anchorkit-preview-progress-hover-color, ${settings.hoverColor});
                }
                #back-to-top-preview svg, 
                #back-to-top-preview img, 
                #back-to-top-preview div {
                    position: relative;
                    z-index: 1;
                }
            </style>
            `;
            
            $('head').append(progressStyle);
        }
    }
    
    // Function to sync test button visibility with checkbox
    function syncTestButtonVisibility() {
        const isChecked = $('input[name="anchorkit_back_to_top_show_test_button"]').is(':checked');
        $('#test-back-to-top-button').css('display', isChecked ? 'block' : 'none');
    }
    
    // Initial update of states
    updateSelectedIconState();
    syncTestButtonVisibility();
    
    // Handle icon type changes
    $('select[name="anchorkit_back_to_top_icon_type"]').on('change', function() {
        updateSelectedIconState();
        updateButtonPreview();
    });
    
    // Handle test button checkbox changes
    $('input[name="anchorkit_back_to_top_show_test_button"]').on('change', function() {
        updateTestButton();
        
        // Also save the setting via AJAX
        const isChecked = $(this).is(':checked');
        $.ajax({
            url: anchorkit_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'anchorkit_update_setting',
                option_name: 'anchorkit_back_to_top_show_test_button',
                option_value: isChecked ? '1' : '0',
                nonce: anchorkit_ajax.nonce
            },
            success: function(response) {
                anchorkitDebugLog('Test button visibility updated successfully:', response);
            },
            error: function(xhr, status, error) {
                console.error('Error updating test button visibility:', error);
            }
        });
    });
    
    // Function to show inline notices
    function showInlineNotice(container, message, type) {
        // If container is a button, use the closest section as the container
        if (container.is('button')) {
            container = container.closest('.media-upload-section, .form-section, .form-group');
        }
        
        // Create notice HTML
        const noticeId = 'inline-notice-' + Math.floor(Math.random() * 10000);
        const noticeClass = type === 'error' ? 'inline-error-notice' : 'inline-success-notice';
        const noticeIcon = type === 'error' ? '⚠️' : '✓';
        
        // Create the notice element
        const noticeHTML = '<div id="' + noticeId + '" class="inline-notice ' + noticeClass + '">' +
            '<span class="notice-icon">' + noticeIcon + '</span>' +
            '<span class="notice-message">' + message + '</span>' +
            '<button type="button" class="notice-dismiss" aria-label="Dismiss">×</button>' +
            '</div>';
        
        // Remove any existing notices in this container
        container.find('.inline-notice').remove();
        
        // Append the notice
        container.append(noticeHTML);
        
        // Add dismiss handler
        $('#' + noticeId + ' .notice-dismiss').on('click', function() {
            $('#' + noticeId).fadeOut(200, function() {
                $(this).remove();
            });
        });
        
        // Auto-dismiss after 5 seconds for success notices
        if (type === 'success') {
            setTimeout(function() {
                $('#' + noticeId).fadeOut(200, function() {
                    $(this).remove();
                });
            }, 5000);
        }
    }
    
    // Function to handle AJAX errors and display appropriate messages
    function handleAjaxError(xhr, status, error, button) {
        // Remove any loading overlays
        $('.loading-overlay').remove();
        
        // Try to parse the response for more details
        let errorMsg = 'Error: Could not save icon. Please try again.';
        try {
            if (xhr.responseJSON && xhr.responseJSON.data) {
                if (typeof xhr.responseJSON.data.message === 'string') {
                    errorMsg = 'Error: ' + xhr.responseJSON.data.message;
                }
                // Log debug info if available
                if (xhr.responseJSON.data.debug) {
                    anchorkitDebugLog('Debug info:', xhr.responseJSON.data.debug);
                }
            }
        } catch (e) {
            console.error('Error parsing AJAX response:', e);
        }
        
        // Show inline error notice
        showInlineNotice(button, errorMsg, 'error');
        
        // Log detailed error
        console.error('AJAX request failed:', {
            status: status,
            error: error,
            response: xhr.responseText
        });
    }
    
    // Function to save custom icon URL via AJAX
    function saveCustomIconURL(iconURL, button, previewContainer) {
        // Show loading state
        if (previewContainer) {
            previewContainer.append('<div class="loading-overlay"><span class="spinner"></span></div>');
        }
        
        return $.ajax({
            url: anchorkit_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'anchorkit_save_custom_icon',
                nonce: anchorkit_ajax.nonce,
                icon_url: iconURL
            }
        }).fail(function(xhr, status, error) {
            handleAjaxError(xhr, status, error, button);
        });
    }
    
    // Add media uploader handlers
    $('.anchorkit-media-upload').on('click', function(e) {
        e.preventDefault();
        
        const button = $(this);
        const targetInputId = button.data('target');
        const targetInput = $('#' + targetInputId);
        const previewContainer = button.closest('.media-upload-section').find('.preview-image');
        let frame;
        
        // If there's already a frame, reuse it
        if (frame) {
            frame.open();
            return;
        }
        
        // Create WP media frame
        frame = wp.media({
            title: 'Select or Upload Image',
            button: {
                text: 'Use this image'
            },
            multiple: false,
            library: {
                type: 'image'
            }
        });
        
        // When an image is selected
        frame.on('select', function() {
            const attachment = frame.state().get('selection').first().toJSON();
            
            // Update the input and data attribute
            targetInput.val(attachment.url);
            targetInput.attr('data-selected-url', attachment.url);
            
            // Update the preview
            previewContainer.html('<img src="' + attachment.url + '" alt="Custom Icon Preview">');
            previewContainer.addClass('has-image');
            
            // Update the button preview immediately
            updateButtonPreview();
            
            // Save the URL via AJAX
            saveCustomIconURL(attachment.url, button, previewContainer)
                .done(function(response) {
                    // Remove loading overlay
                    previewContainer.find('.loading-overlay').remove();
                    
                    if (response.success) {
                        // Add "Remove" button if it doesn't exist
                        const buttonsContainer = button.closest('.buttons-container');
                        if (buttonsContainer.find('.anchorkit-media-clear').length === 0) {
                            $('<button type="button" class="button anchorkit-media-clear" data-target="' + targetInputId + '">Remove</button>')
                                .appendTo(buttonsContainer)
                                .on('click', handleRemoveButtonClick);
                        } else {
                            // Show the existing Remove button
                            buttonsContainer.find('.anchorkit-media-clear').show();
                        }

                        // Show inline success notice
                        showInlineNotice(button, 'Icon successfully saved!', 'success');

                        // Update the hidden field to prevent form notification conflicts
                        if (!$('#anchorkit_custom_icon_already_saved').length) {
                            $('<input>').attr({
                                type: 'hidden',
                                id: 'anchorkit_custom_icon_already_saved',
                                name: 'anchorkit_custom_icon_already_saved',
                                value: '1'
                            }).appendTo(button.closest('form'));
                        }

                        // Update the icon type in the UI
                        const iconTypeSelect = $('select[name="anchorkit_back_to_top_icon_type"]');
                        if (iconTypeSelect.length) {
                            iconTypeSelect.val('custom-image').trigger('change');
                        }

                        // Update the button preview
                        updateButtonPreview();

                        // Remove any WordPress error notices
                        $('.notice-error, .notice.error, #setting-error-settings_updated').fadeOut();
                    }
                });
        });

        // Open the media modal
        frame.open();
    });

    // Function to handle Remove button click
    function handleRemoveButtonClick(e) {
        e.preventDefault();

        const button = $(this);
        const targetInputId = button.data('target');
        const targetInput = $('#' + targetInputId);
        const previewContainer = button.closest('.media-upload-section').find('.preview-image');
        const buttonsContainer = button.closest('.buttons-container');

        // Show loading state
        button.addClass('button-loading').prop('disabled', true);
        button.text('Removing...');

        // Use AJAX to clear the custom icon URL
        $.ajax({
            url: anchorkit_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'anchorkit_save_custom_icon',
                icon_url: '', // Empty URL to clear
                nonce: anchorkit_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Clear the input value
                    targetInput.val('');
                    targetInput.removeAttr('data-selected-url');

                    // Update the preview to show "No image selected"
                    previewContainer.removeClass('has-image pending-selection');
                    previewContainer.html('<span class="no-image">No image selected</span>');

                    // Remove the Remove button as it's no longer needed
                    button.remove();

                    // Update the button preview
                    updateButtonPreview();

                    // Show inline success notice
                    showInlineNotice(button, 'Custom icon removed successfully!', 'success');

                    anchorkitDebugLog('Custom icon removed via AJAX');
                } else {
                    // Show inline error notice
                    showInlineNotice(button, 'Error removing icon: ' + (response.data || 'Unknown error'), 'error');
                    console.error('Error removing custom icon:', response);
                    button.removeClass('button-loading').prop('disabled', false);
                    button.text('Remove');
                }
            },
            error: function(xhr, status, error) {
                // Show inline error notice
                showInlineNotice(button, 'Error: Could not remove icon. Please try again.', 'error');
                console.error('AJAX error:', status, error);
                button.removeClass('button-loading').prop('disabled', false);
                button.text('Remove');
            }
        });
    }

    // Attach event handlers to any existing buttons on page load
    $('.anchorkit-media-clear').on('click', handleRemoveButtonClick);

    // Add media uploader click handlers
    $('.anchorkit-upload-custom-icon').on('click', function(e) {
        e.preventDefault();
        var button = $(this);
        var customMediaUploader;
        
        // Create the media frame or open existing one
        if (customMediaUploader) {
            customMediaUploader.open();
            return;
        }
        
        // Create new media frame
        customMediaUploader = wp.media({
            title: 'Select or Upload Custom Icon',
            button: {
                text: 'Use this icon'
            },
            multiple: false,
            library: {
                type: 'image'
            }
        });
        
        // When an image is selected, run a callback
        customMediaUploader.on('select', function() {
            var attachment = customMediaUploader.state().get('selection').first().toJSON();
            
            // Update hidden input field with URL
            $('#anchorkit_back_to_top_custom_icon').val(attachment.url);
            
            // Update preview
            var previewContainer = $('#anchorkit_back_to_top_custom_icon_preview');
            previewContainer.html('<img src="' + attachment.url + '" alt="Custom Icon Preview">');
            
            // Show the remove button
            $('.anchorkit-remove-custom-icon').show();
            
            // Change the icon type to custom image
            $('select[name="anchorkit_back_to_top_icon_type"]').val('custom-image').trigger('change');
            
            // Save the URL via AJAX for immediate effect
            saveCustomIconURL(attachment.url, button, previewContainer);
            
            // Update button preview
            updateButtonPreview();
        });
        
        // Open the uploader dialog
        customMediaUploader.open();
    });
    
    // Remove icon click handler
    $('.anchorkit-remove-custom-icon').on('click', function(e) {
        e.preventDefault();
        
        // Clear the input value
        $('#anchorkit_back_to_top_custom_icon').val('');
        
        // Clear the preview
        $('#anchorkit_back_to_top_custom_icon_preview').html('<div class="no-image">No image selected</div>');
        
        // Hide the remove button
        $(this).hide();
        
        // Change the icon type back to collection
        $('select[name="anchorkit_back_to_top_icon_type"]').val('collection').trigger('change');
        
        // Save empty URL via AJAX
        saveCustomIconURL('', button, previewContainer);
        
        // Update button preview
        updateButtonPreview();
    });
    
    // Update preview when settings change
    $(document).on('change input', `
        select[name="anchorkit_back_to_top_icon_type"],
        input[name="anchorkit_back_to_top_collection_icon"],
        input[name="anchorkit_back_to_top_bg_color"],
        input[name="anchorkit_back_to_top_hover_color"],
        input[name="anchorkit_back_to_top_width"],
        input[name="anchorkit_back_to_top_height"],
        input[name="anchorkit_back_to_top_opacity"],
        input[name="anchorkit_back_to_top_icon_color"],
        input[name="anchorkit_back_to_top_icon_width"],
        input[name="anchorkit_back_to_top_icon_height"],
        input[name="anchorkit_back_to_top_progress_indicator"],
        input[name="anchorkit_back_to_top_progress_color"],
        input[name="anchorkit_back_to_top_progress_thickness"],
        input[name="anchorkit_back_to_top_margin_x"],
        input[name="anchorkit_back_to_top_margin_y"],
        select[name="anchorkit_back_to_top_position"],
        textarea[name="anchorkit_back_to_top_custom_html"],
        textarea[name="anchorkit_back_to_top_custom_css"]
    `, function() {
        updateButtonPreview();
        // Also update test button if it's enabled
        if ($('input[name="anchorkit_back_to_top_show_test_button"]').is(':checked')) {
            updateTestButton();
        }
    });
    
    // Initial preview update
    $(document).ready(function() {
        updateButtonPreview();
    });

    // Function to create or update the live test button 
    updateTestButton = function() {
        // Check if test button should be visible
        const isTestButtonEnabled = $('input[name="anchorkit_back_to_top_show_test_button"]').is(':checked');
        
        // Get existing button or create it if it doesn't exist
        let testButton = $('#anchorkit-back-to-top');
        if (testButton.length === 0) {
            testButton = $('<button id="anchorkit-back-to-top" class="anchorkit-back-to-top-button"></button>');
            $('body').append(testButton);
        }
        
        // Get all the same settings used for the preview
        const settings = {
            width: $('input[name="anchorkit_back_to_top_width"]').val() || '40',
            height: $('input[name="anchorkit_back_to_top_height"]').val() || '40',
            opacity: $('input[name="anchorkit_back_to_top_opacity"]').val() || '80',
            bgColor: $('input[name="anchorkit_back_to_top_bg_color"]').val() || '#000000',
            hoverColor: $('input[name="anchorkit_back_to_top_hover_color"]').val() || '#444444',
            iconColor: $('input[name="anchorkit_back_to_top_icon_color"]').val() || '#ffffff',
            iconType: $('select[name="anchorkit_back_to_top_icon_type"]').val() || 'collection',
            collectionIcon: $('input[name="anchorkit_back_to_top_collection_icon"]:checked').val() || 'a-arrow-up-bold.svg',
            customIcon: $('#anchorkit_back_to_top_custom_icon').val() || '',
            customHTML: $('#anchorkit_back_to_top_custom_html').val() || '<i class="fas fa-arrow-up"></i>',
            iconWidth: $('input[name="anchorkit_back_to_top_icon_width"]').val() || '16',
            iconHeight: $('input[name="anchorkit_back_to_top_icon_height"]').val() || '16',
            progressIndicator: $('input[name="anchorkit_back_to_top_progress_indicator"]').is(':checked'),
            progressColor: $('input[name="anchorkit_back_to_top_progress_color"]').val() || '#ff5555',
            progressThickness: $('input[name="anchorkit_back_to_top_progress_thickness"]').val() || '3',
            position: $('select[name="anchorkit_back_to_top_position"]').val() || 'bottom-right',
            marginX: $('input[name="anchorkit_back_to_top_margin_x"]').val() || '20',
            marginY: $('input[name="anchorkit_back_to_top_margin_y"]').val() || '20',
            customCSS: $('#anchorkit_back_to_top_custom_css').val() || ''
        };
        
        anchorkitDebugLog("Updating test button, show button enabled:", isTestButtonEnabled);
        
        // Apply base styles
        const btnStyles = {
            width: settings.width + 'px',
            height: settings.height + 'px',
            backgroundColor: settings.bgColor,
            opacity: isTestButtonEnabled ? settings.opacity / 100 : 0,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            position: 'fixed',
            borderRadius: '50%',
            border: 'none',
            cursor: 'pointer',
            zIndex: '9999',
            boxShadow: '0 2px 5px rgba(0, 0, 0, 0.2)',
            transition: 'opacity 0.3s, transform 0.3s, background-color 0.3s'
        };
        
        // Set position based on selected position
        const position = settings.position.split('-');
        const y = position[0]; // top or bottom
        const x = position[1]; // left or right
        btnStyles[y] = `${settings.marginY}px`;
        btnStyles[x] = `${settings.marginX}px`;
        
        // Apply styles
        testButton.css(btnStyles);
        
        // Add icon content based on type (similar to preview button)
        let iconContent = '';
        if (settings.iconType === 'collection') {
            // Use the SVG content from anchorkitArrowIcons if available
            if (typeof window.anchorkitArrowIcons !== 'undefined' && window.anchorkitArrowIcons[settings.collectionIcon]) {
                let svgContent = window.anchorkitArrowIcons[settings.collectionIcon];
                svgContent = svgContent.replace(/width="[^"]*"/, `width="${settings.iconWidth}"`);
                svgContent = svgContent.replace(/height="[^"]*"/, `height="${settings.iconHeight}"`);
                svgContent = svgContent.replace(/fill="[^"]*"/, `fill="${settings.iconColor}"`);
                iconContent = svgContent;
            } else {
                // Fallback to default arrow
                iconContent = `<svg xmlns="http://www.w3.org/2000/svg" width="${settings.iconWidth}" height="${settings.iconHeight}" fill="${settings.iconColor}" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M8 15a.5.5 0 0 0 .5-.5V2.707l3.146 3.147a.5.5 0 0 0 .708-.708l-4-4a.5.5 0 0 0-.708 0l-4 4a.5.5 0 1 0 .708.708L7.5 2.707V14.5a.5.5 0 0 0 .5.5z"/></svg>`;
            }
        } else if (settings.iconType === 'custom-image' && settings.customIcon) {
            iconContent = `<img src="${settings.customIcon}" alt="Back to Top" style="width:${settings.iconWidth}px; height:${settings.iconHeight}px; object-fit:contain; display:block; position:relative; z-index:1;">`;
        } else if (settings.iconType === 'html' && settings.customHTML) {
            iconContent = `<div style="color:${settings.iconColor}; width:${settings.iconWidth}px; height:${settings.iconHeight}px; position:relative; z-index:1;">${settings.customHTML}</div>`;
        } else {
            // Fallback
            iconContent = `<svg xmlns="http://www.w3.org/2000/svg" width="${settings.iconWidth}" height="${settings.iconHeight}" fill="${settings.iconColor}" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M8 15a.5.5 0 0 0 .5-.5V2.707l3.146 3.147a.5.5 0 0 0 .708-.708l-4-4a.5.5 0 0 0-.708 0l-4 4a.5.5 0 1 0 .708.708L7.5 2.707V14.5a.5.5 0 0 0 .5.5z"/></svg>`;
        }
        
        // Update button content
        testButton.html(iconContent);
        
        // Remove any existing custom CSS style block
        $('#anchorkit-back-to-top-custom-css-preview').remove();
        
        // Add progress indicator if enabled
        if (settings.progressIndicator) {
            // Remove any existing progress styles
            $('#test-progress-styles').remove();
            
            // Create progress styles using CSS variables (with fallbacks)
            const progressStyles = `
                #anchorkit-back-to-top {
                    --anchorkit-progress-color: ${settings.progressColor};
                    --anchorkit-progress-thickness: ${settings.progressThickness}px;
                    --anchorkit-progress-bg-color: ${settings.bgColor};
                    --anchorkit-progress-hover-color: ${settings.hoverColor};
                    background: conic-gradient(
                        var(--anchorkit-progress-color, ${settings.progressColor}) var(--progress-percent, 0%), 
                        var(--anchorkit-progress-bg-color, ${settings.bgColor}) var(--progress-percent, 0%)
                    ) !important;
                }
                #anchorkit-back-to-top::before {
                    content: "";
                    position: absolute;
                    top: var(--anchorkit-progress-thickness, ${settings.progressThickness}px);
                    right: var(--anchorkit-progress-thickness, ${settings.progressThickness}px);
                    bottom: var(--anchorkit-progress-thickness, ${settings.progressThickness}px);
                    left: var(--anchorkit-progress-thickness, ${settings.progressThickness}px);
                    background-color: var(--anchorkit-progress-bg-color, ${settings.bgColor});
                    border-radius: 50%;
                    z-index: 0;
                }
                #anchorkit-back-to-top:hover::before {
                    background-color: var(--anchorkit-progress-hover-color, ${settings.hoverColor}) !important;
                }
                #anchorkit-back-to-top svg, 
                #anchorkit-back-to-top img, 
                #anchorkit-back-to-top div {
                    position: relative;
                    z-index: 1;
                }
            `;
            
            // Add styles to head
            $('<style id="test-progress-styles">' + progressStyles + '</style>').appendTo('head');
            
            // Create and update progress indicator
            const updateProgressIndicator = function() {
                if (!isTestButtonEnabled) return;
                
                // Calculate scroll percentage
                const scrollTop = $(window).scrollTop();
                const docHeight = $(document).height() - $(window).height();
                const scrollPercentage = Math.min(100, Math.max(0, Math.floor((scrollTop / docHeight) * 100)));
                
                // Update the progress indicator using setAttribute for better browser compatibility
                testButton[0].style.setProperty('--progress-percent', `${scrollPercentage}%`);
            };
            
            // Remove existing scroll handler and add new one
            $(window).off('scroll.progressIndicator').on('scroll.progressIndicator', updateProgressIndicator);
            
            // Initial update
            updateProgressIndicator();
        } else {
            // Remove any existing progress styles if disabled
            $('#test-progress-styles').remove();
            $(window).off('scroll.progressIndicator');
        }
        
        // Inject custom CSS after progress indicator styles
        if (settings.customCSS && settings.customCSS.trim() !== '') {
            $('<style id="anchorkit-back-to-top-custom-css-preview">' + settings.customCSS + '</style>').appendTo('head');
        }
        
        // Add hover effects
        testButton.off('mouseenter mouseleave'); // Remove existing events
        testButton.on({
            mouseenter: function() {
                $(this).css({
                    'background-color': settings.progressIndicator ? $(this).css('background-color') : settings.hoverColor,
                    'transform': 'translateY(-5px)'
                });
                
                if (settings.progressIndicator) {
                    $(this).find('::before').css('background-color', settings.hoverColor);
                }
            },
            mouseleave: function() {
                $(this).css({
                    'background-color': settings.progressIndicator ? $(this).css('background-color') : settings.bgColor,
                    'transform': 'translateY(0)'
                });
                
                if (settings.progressIndicator) {
                    $(this).find('::before').css('background-color', settings.bgColor);
                }
            }
        });
        
        // Add click behavior to scroll to top
        testButton.off('click').on('click', function(e) {
            e.preventDefault();
            $('html, body').animate({ scrollTop: 0 }, 400);
        });
    };
    
    // Initial preview and test button update
    $(document).ready(function() {
        updateButtonPreview();
        updateTestButton();
    });

    // Add document ready handler at the end of the file
    $(document).ready(function() {
        // Initialize the test button on page load
        updateTestButton();
        
        // Also update the test button whenever relevant settings change
        $('input[name^="anchorkit_back_to_top_"], select[name^="anchorkit_back_to_top_"], textarea[name="anchorkit_back_to_top_custom_css"], textarea[name="anchorkit_back_to_top_custom_html"]').on('change', function() {
            updateTestButton();
        });
        
        // Update for color changes
        $('input[type="color"]').on('input', function() {
            updateTestButton();
        });
        
        // Specifically listen for progress indicator settings changes
        $('input[name="anchorkit_back_to_top_progress_indicator"]').on('change', function() {
            updateTestButton();
        });
        
        $('input[name="anchorkit_back_to_top_progress_color"], input[name="anchorkit_back_to_top_progress_thickness"]').on('input change', function() {
            if ($('input[name="anchorkit_back_to_top_progress_indicator"]').is(':checked')) {
                updateTestButton();
            }
        });
    });

    // Expose updateTestButton globally for cross-file access
    window.updateTestButton = updateTestButton;

    // Make the preview update function globally accessible so other admin scripts
    // (like anchorkit-admin.js) can invoke it after actions such as resetting settings.
    window.updateButtonPreview = updateButtonPreview;
});

// Create a secondary globally accessible reference to ensure availability
(function() {
    // Wait for the main jQuery function to complete and create the global function
    jQuery(document).ready(function() {
        setTimeout(function() {
            // If for some reason window.updateTestButton is not available, create a fallback
            if (typeof window.updateTestButton !== 'function') {
                anchorkitDebugLog('Creating fallback updateTestButton function');
                window.updateTestButton = function() {
                    // Basic fallback implementation
                    const isTestButtonEnabled = jQuery('input[name="anchorkit_back_to_top_show_test_button"]').is(':checked');
                    let testButton = jQuery('#anchorkit-back-to-top');
                    
                    // Create button if it doesn't exist
                    if (testButton.length === 0) {
                        testButton = jQuery('<button id="anchorkit-back-to-top" class="anchorkit-back-to-top-button">▲</button>');
                        jQuery('body').append(testButton);
                    }
                    
                    // Display or hide based on setting
                    testButton.css({
                        'display': isTestButtonEnabled ? 'flex' : 'none',
                        'position': 'fixed',
                        'bottom': '20px',
                        'right': '20px',
                        'width': '40px',
                        'height': '40px',
                        'background-color': '#000000',
                        'color': '#ffffff',
                        'border-radius': '50%',
                        'align-items': 'center',
                        'justify-content': 'center',
                        'z-index': '9999',
                        'cursor': 'pointer'
                    });
                };
            }
        }, 500); // Small delay to ensure jQuery function has completed
    });
})(); 
