/**
 * Admin JavaScript for ReplicateWP Virtual Try-On
 */

(function($) {
    'use strict';
    
    // Wait for document ready
    $(document).ready(function() {
        
        // Initialize
        RWPVTO_Admin.init();
        
    });
    
    /**
     * Main admin object
     */
    var RWPVTO_Admin = {
        
        /**
         * Initialize
         */
        init: function() {
            this.productMetaBox();
            this.dashboardActions();
            this.settingsPage();
        },
        
        /**
         * Product meta box functionality
         */
        productMetaBox: function() {
            var self = this;
            
            // Garment image preview
            $('#rwpvto_garment_image').on('change', function() {
                var imageUrl = $(this).val();
                var $preview = $('#rwpvto_garment_preview');
                
                if (imageUrl) {
                    $preview.attr('src', imageUrl).show();
                } else {
                    $preview.hide();
                }
            });
            
            // Visual Model Picker Modal
            self.initModelPickerModal();
            
            // Model image preview (for hidden select - backwards compatibility)
            $('#rwpvto_model_image').on('change', function() {
                var imageUrl = $(this).val();
                var $preview = $('#rwpvto_model_preview');
                
                if (imageUrl) {
                    $preview.attr('src', imageUrl).show();
                    $('#rwpvto_custom_model_url').val('');
                    $('.rwpvto-clear-model-btn').hide();
                } else {
                    $preview.hide();
                }
            });
            
            // WordPress Media Library picker for model image
            var modelMediaFrame;
            
            $(document).on('click', '.rwpvto-choose-model-btn', function(e) {
                e.preventDefault();
                
                // Check if wp.media is available
                if (typeof wp === 'undefined' || typeof wp.media === 'undefined') {
                    alert('WordPress Media Library is not loaded. Please refresh the page.');
                    return;
                }
                
                // If the media frame already exists, reopen it
                if (modelMediaFrame) {
                    modelMediaFrame.open();
                    return;
                }
                
                // Create the media frame
                modelMediaFrame = wp.media({
                    title: 'Select Model Image',
                    button: {
                        text: 'Use this image'
                    },
                    multiple: false,
                    library: {
                        type: 'image'
                    }
                });
                
                // When an image is selected
                modelMediaFrame.on('select', function() {
                    var attachment = modelMediaFrame.state().get('selection').first().toJSON();
                    
                    // Set the custom URL field
                    $('#rwpvto_custom_model_url').val(attachment.url);
                    
                    // Clear the dropdown
                    $('#rwpvto_model_image').val('');
                    
                    // Show preview
                    $('#rwpvto_model_preview').attr('src', attachment.url).show();
                    
                    // Show clear button
                    $('.rwpvto-clear-model-btn').show();
                });
                
                // Open the media frame
                modelMediaFrame.open();
            });
            
            // Clear custom model
            $('.rwpvto-clear-model-btn').on('click', function(e) {
                e.preventDefault();
                $('#rwpvto_custom_model_url').val('');
                $('#rwpvto_model_preview').hide();
                $(this).hide();
            });
            
            // Custom model URL manual input (make it editable on click)
            $('#rwpvto_custom_model_url').on('click', function() {
                $(this).prop('readonly', false).css('background', '#fff');
            });
            
            $('#rwpvto_custom_model_url').on('blur', function() {
                var customUrl = $(this).val();
                if (customUrl) {
                    $(this).prop('readonly', true).css('background', '#f5f5f5');
                }
            });
            
            $('#rwpvto_custom_model_url').on('input', function() {
                var customUrl = $(this).val();
                var $modelSelect = $('#rwpvto_model_image');
                var $preview = $('#rwpvto_model_preview');
                
                if (customUrl) {
                    $modelSelect.val('');
                    $preview.attr('src', customUrl).show();
                    $('.rwpvto-clear-model-btn').show();
                } else {
                    $preview.hide();
                    $('.rwpvto-clear-model-btn').hide();
                }
            });
            
            // Generate button
            $('.rwpvto-generate-btn').on('click', function(e) {
                e.preventDefault();
                
                var $button = $(this);
                var productId = $button.data('product-id');
                var garmentImage = $('#rwpvto_garment_image').val();
                var modelImage = $('#rwpvto_model_image').val();
                var customModelUrl = $('#rwpvto_custom_model_url').val();
                var category = $('#rwpvto_category').val();
                var garmentDescription = $('#rwpvto_garment_description').val();
                var customFilename = $('#rwpvto_custom_filename').val();
                var autoCrop = $('#rwpvto_auto_crop').is(':checked');
                
                // Use custom model URL if provided
                if (customModelUrl) {
                    modelImage = customModelUrl;
                }
                
                // Remove any existing validation notices
                $('.rwpvto-validation-notice').remove();
                
                // Validate
                if (!garmentImage) {
                    self.showValidationError('Please select a garment image.');
                    return;
                }
                
                if (!modelImage) {
                    self.showValidationError('Please select a model or enter a custom model URL.');
                    return;
                }
                
                // Get model metadata
                var modelGender = $('#rwpvto_model_image option:selected').data('gender') || '';
                
                // Disable button and show loading
                $button.addClass('loading').prop('disabled', true);
                $button.html('<span class="dashicons dashicons-update rwpvto-spinning"></span> ' + rwpvtoAdmin.strings.generating);
                
                // Show loading message
                var $result = $('.rwpvto-result');
                var $message = $('.rwpvto-result-message');
                $result.removeClass('success error').addClass('loading').show();
                $message.html('<strong>⏳ ' + rwpvtoAdmin.strings.generating + '</strong><br><span style="color: #666; font-size: 12px;">This may take up to 5 minutes. Please be patient...</span>');
                $('.rwpvto-result-image').html('');
                
                // Make AJAX request with extended timeout
                $.ajax({
                    url: rwpvtoAdmin.ajaxUrl,
                    type: 'POST',
                    timeout: 330000, // 5.5 minutes timeout (330 seconds) - slightly longer than PHP polling
                    data: {
                        action: 'rwpvto_generate_tryon',
                        nonce: rwpvtoAdmin.nonce,
                        product_id: productId,
                        garment_image: garmentImage,
                        model_image: modelImage,
                        category: category,
                        garment_description: garmentDescription,
                        custom_filename: customFilename,
                        model_gender: modelGender,
                        auto_crop: autoCrop ? 1 : 0
                    },
                    success: function(response) {
                        self.handleGenerateResponse(response, $button);
                    },
                    error: function(xhr, status, error) {
                        if (status === 'timeout') {
                            self.handleGenerateTimeout($button);
                        } else {
                            self.handleGenerateError($button, xhr, status, error);
                        }
                    }
                });
            });
            
            // Add to gallery from product editor
            $(document).on('click', '.rwpvto-add-to-gallery-product-btn', function(e) {
                e.preventDefault();
                
                var $button = $(this);
                var imageId = $button.data('image-id');
                var productId = $button.data('product-id');
                
                // Remove any existing notices in product editor
                $('.rwpvto-result .rwpvto-inline-notice').remove();
                
                // Disable button and show loading
                $button.prop('disabled', true).html('<span class="dashicons dashicons-update rwpvto-spinning"></span> Adding to Gallery...');
                
                $.ajax({
                    url: rwpvtoAdmin.ajaxUrl,
                    type: 'POST',
                    timeout: 120000, // 2 minutes timeout
                    data: {
                        action: 'rwpvto_add_to_gallery',
                        nonce: rwpvtoAdmin.nonce,
                        image_id: imageId,
                        product_id: productId
                    },
                    success: function(response) {
                        if (response.success) {
                            $button.html('<span class="dashicons dashicons-yes-alt"></span> Added to Gallery!').css({
                                'background': '#00a32a',
                                'border-color': '#00a32a',
                                'color': '#fff'
                            });
                            
                            // Update WooCommerce gallery field if it exists
                            if (response.data.attachment_id) {
                                var $galleryField = $('#product_image_gallery');
                                if ($galleryField.length) {
                                    var currentGallery = $galleryField.val();
                                    var galleryIds = currentGallery ? currentGallery.split(',') : [];
                                    
                                    // Add new image ID if not already present
                                    if (galleryIds.indexOf(response.data.attachment_id.toString()) === -1) {
                                        galleryIds.push(response.data.attachment_id);
                                        $galleryField.val(galleryIds.join(',')).trigger('change');
                                        
                                        // Trigger WooCommerce gallery update if possible
                                        if (typeof window.wc_product_gallery !== 'undefined') {
                                            $(document.body).trigger('woocommerce-product-gallery-reset');
                                        }
                                    }
                                }
                            }
                            
                            // Show success notice
                            $('.rwpvto-result-message').prepend(
                                '<div class="rwpvto-inline-notice rwpvto-notice-success" style="margin-bottom: 10px;">' +
                                '<span class="dashicons dashicons-yes-alt"></span> ' +
                                response.data.message + ' <strong>Refresh the page to see it in the product gallery.</strong>' +
                                '</div>'
                            );
                            
                            // Scroll to notice
                            $('html, body').animate({
                                scrollTop: $('.rwpvto-result').offset().top - 100
                            }, 300);
                        } else {
                            $button.prop('disabled', false).html('<span class="dashicons dashicons-images-alt2"></span> Add to Product Gallery');
                            
                            // Show error notice
                            var errorMsg = response.data && response.data.message ? response.data.message : 'Unknown error occurred';
                            $('.rwpvto-result-message').prepend(
                                '<div class="rwpvto-inline-notice rwpvto-notice-error" style="margin-bottom: 10px;">' +
                                '<span class="dashicons dashicons-dismiss"></span> ' +
                                errorMsg +
                                '</div>'
                            );
                        }
                    },
                    error: function(xhr, status, error) {
                        $button.prop('disabled', false).html('<span class="dashicons dashicons-images-alt2"></span> Add to Product Gallery');
                        
                        var errorMsg = 'An error occurred. ';
                        if (status === 'timeout') {
                            errorMsg += 'The request timed out. The image might be too large or the connection is slow.';
                        } else if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                            errorMsg += xhr.responseJSON.data.message;
                        } else {
                            errorMsg += 'Please check your internet connection and try again.';
                        }
                        
                        // Show error notice
                        $('.rwpvto-result-message').prepend(
                            '<div class="rwpvto-inline-notice rwpvto-notice-error" style="margin-bottom: 10px;">' +
                            '<span class="dashicons dashicons-dismiss"></span> ' +
                            errorMsg +
                            '</div>'
                        );
                        
                        console.error('Add to gallery error:', status, error, xhr);
                    }
                });
            });
        },

        /**
         * Initialize Visual Model Picker Modal
         */
        initModelPickerModal: function() {
            var self = this;
            var $modal = $('#rwpvto-model-picker-modal');
            var $openButton = $('.rwpvto-open-model-picker');
            var $closeButton = $('.rwpvto-picker-modal-close');
            var $overlay = $('.rwpvto-picker-modal-overlay');
            var $modelItems = $('.rwpvto-model-item');
            var $modelSelect = $('#rwpvto_model_image');
            var $modelPreview = $('#rwpvto_model_preview');
            var $selectedText = $('#rwpvto_selected_model_text');
            
            // Open modal
            $openButton.on('click', function(e) {
                e.preventDefault();
                $modal.show();
                $('body').css('overflow', 'hidden');
            });
            
            // Close modal
            function closeModal() {
                $modal.hide();
                $('body').css('overflow', '');
            }
            
            $closeButton.on('click', closeModal);
            $overlay.on('click', closeModal);
            
            // ESC key to close
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape' && $modal.is(':visible')) {
                    closeModal();
                }
            });
            
            // Filter functionality
            var $genderFilterButtons = $('.rwpvto-gender-filter');
            var $categoryFilterButtons = $('.rwpvto-category-filter');
            var currentGenderFilter = 'all';
            var currentCategoryFilter = 'all';
            
            // Gender filter
            $genderFilterButtons.on('click', function() {
                var $this = $(this);
                var filter = $this.data('filter');
                
                // Update active state for gender filters only
                $genderFilterButtons.removeClass('active');
                $this.addClass('active');
                
                currentGenderFilter = filter;
                applyFilters();
            });
            
            // Category filter
            $categoryFilterButtons.on('click', function() {
                var $this = $(this);
                var filter = $this.data('filter');
                
                // Update active state for category filters only
                $categoryFilterButtons.removeClass('active');
                $this.addClass('active');
                
                currentCategoryFilter = filter;
                applyFilters();
            });
            
            // Apply both filters
            function applyFilters() {
                $modelItems.each(function() {
                    var $item = $(this);
                    var itemGender = $item.data('gender');
                    var itemCategories = $item.data('category');
                    
                    var genderMatch = (currentGenderFilter === 'all' || itemGender === currentGenderFilter);
                    
                    var categoryMatch = false;
                    if (currentCategoryFilter === 'all') {
                        categoryMatch = true;
                    } else {
                        // Split comma-separated categories and check if filter matches any
                        var categories = itemCategories ? itemCategories.split(',') : [];
                        categoryMatch = categories.indexOf(currentCategoryFilter) !== -1;
                    }
                    
                    if (genderMatch && categoryMatch) {
                        $item.show();
                    } else {
                        $item.hide();
                    }
                });
            }
            
            // Select model
            $modelItems.on('click', function() {
                var $this = $(this);
                var modelUrl = $this.data('model-url');
                
                // Update UI
                $modelItems.removeClass('selected');
                $this.addClass('selected');
                
                // Update hidden select
                $modelSelect.val(modelUrl);
                
                // Update preview
                $modelPreview.attr('src', modelUrl).show();
                
                // Update button text
                $selectedText.text('✓ Model Selected');
                $openButton.addClass('has-selection');
                
                // Clear custom model
                $('#rwpvto_custom_model_url').val('');
                $('.rwpvto-clear-model-btn').hide();
                
                // Close modal after short delay
                setTimeout(closeModal, 300);
            });
            
            // Mark currently selected model if any
            var currentModel = $modelSelect.val();
            if (currentModel) {
                $modelItems.each(function() {
                    if ($(this).data('model-url') === currentModel) {
                        $(this).addClass('selected');
                        $selectedText.text('✓ Model Selected');
                        $openButton.addClass('has-selection');
                    }
                });
            }
        },
        
        /**
         * Handle generate response
         */
        handleGenerateResponse: function(response, $button) {
            // Reset button
            $button.removeClass('loading').prop('disabled', false);
            $button.html('<span class="dashicons dashicons-camera"></span> Generate Try-On Image');
            
            var $result = $('.rwpvto-result');
            var $message = $('.rwpvto-result-message');
            var $image = $('.rwpvto-result-image');
            
            if (response.success) {
                $result.removeClass('error loading').addClass('success').show();
                $message.html('<strong>✅ ' + response.data.message + '</strong>');
                
                if (response.data.image_url) {
                    $image.html(
                        '<img src="' + response.data.image_url + '" alt="Generated Try-On" style="margin-top: 10px; max-width: 100%; border-radius: 4px;">' +
                        '<div class="rwpvto-product-actions" style="margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap;">' +
                        '<button type="button" class="button button-primary rwpvto-add-to-gallery-product-btn" ' +
                        'data-image-id="' + response.data.image_id + '" ' +
                        'data-product-id="' + $button.data('product-id') + '">' +
                        '<span class="dashicons dashicons-images-alt2"></span> Add to Product Gallery' +
                        '</button>' +
                        '<a href="' + response.data.image_url + '" target="_blank" class="button">' +
                        '<span class="dashicons dashicons-external"></span> View Full Size' +
                        '</a>' +
                        '</div>'
                    );
                }
            } else {
                $result.removeClass('success loading').addClass('error').show();
                $message.html('<strong>❌ Error:</strong> ' + (response.data && response.data.message ? response.data.message : rwpvtoAdmin.strings.error));
                $image.html('');
            }
        },
        
        /**
         * Handle generate error
         */
        handleGenerateError: function($button, xhr, status, error) {
            // Reset button
            $button.removeClass('loading').prop('disabled', false);
            $button.html('<span class="dashicons dashicons-camera"></span> Generate Try-On Image');
            
            var $result = $('.rwpvto-result');
            var $message = $('.rwpvto-result-message');
            
            var errorMsg = rwpvtoAdmin.strings.error;
            if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                errorMsg = xhr.responseJSON.data.message;
            } else if (error) {
                errorMsg += ' (' + error + ')';
            }
            
            $result.removeClass('success loading').addClass('error').show();
            $message.html('<strong>❌ Error:</strong> ' + errorMsg);
            $('.rwpvto-result-image').html('');
        },
        
        /**
         * Handle generate timeout
         */
        handleGenerateTimeout: function($button) {
            // Reset button
            $button.removeClass('loading').prop('disabled', false);
            $button.html('<span class="dashicons dashicons-camera"></span> Generate Try-On Image');
            
            var $result = $('.rwpvto-result');
            var $message = $('.rwpvto-result-message');
            
            $result.removeClass('success loading').addClass('error').show();
            $message.html('<strong>⏱️ Timeout:</strong> The image generation took longer than 5 minutes. This can happen if the Replicate API is busy. Please try again in a few moments.');
            $('.rwpvto-result-image').html('');
        },
        
        /**
         * Dashboard actions
         */
        dashboardActions: function() {
            var self = this;
            
            // View Toggle
            var $viewBtns = $('.rwpvto-view-btn');
            var $imagesGrid = $('.rwpvto-images-grid');
            
            // Load saved view preference
            var savedView = localStorage.getItem('rwpvto_dashboard_view') || 'grid';
            if (savedView === 'list') {
                $imagesGrid.addClass('list-view');
                $viewBtns.removeClass('active');
                $viewBtns.filter('[data-view="list"]').addClass('active');
            }
            
            // Handle view toggle
            $viewBtns.on('click', function() {
                var view = $(this).data('view');
                
                $viewBtns.removeClass('active');
                $(this).addClass('active');
                
                if (view === 'list') {
                    $imagesGrid.addClass('list-view');
                } else {
                    $imagesGrid.removeClass('list-view');
                }
                
                // Save preference
                localStorage.setItem('rwpvto_dashboard_view', view);
            });
            
            // View image
            $(document).on('click', '.rwpvto-view-image-btn', function(e) {
                e.preventDefault();
                var imageUrl = $(this).data('image-url');
                self.showImageModal(imageUrl);
            });
            
            // Add to gallery
            $(document).on('click', '.rwpvto-add-to-gallery-btn', function(e) {
                e.preventDefault();
                
                var $button = $(this);
                var $buttonText = $button.find('span:last-child');
                var $card = $button.closest('.rwpvto-image-card');
                var imageId = $button.data('image-id');
                var productId = $button.data('product-id');
                
                // Remove any existing notices
                $card.find('.rwpvto-inline-notice').remove();
                
                // Disable button and show loading
                $button.prop('disabled', true).addClass('loading');
                $buttonText.text('Downloading...');
                
                $.ajax({
                    url: rwpvtoAdmin.ajaxUrl,
                    type: 'POST',
                    timeout: 120000, // 2 minutes timeout
                    data: {
                        action: 'rwpvto_add_to_gallery',
                        nonce: rwpvtoAdmin.nonce,
                        image_id: imageId,
                        product_id: productId
                    },
                    success: function(response) {
                        if (response.success) {
                            $button.removeClass('loading').addClass('button-disabled');
                            $buttonText.text('✓ Added!');
                            $button.css({
                                'background': '#00a32a',
                                'color': '#fff',
                                'border-color': '#00a32a'
                            });
                            
                            // Show success notice
                            $card.find('.rwpvto-image-info').prepend(
                                '<div class="rwpvto-inline-notice rwpvto-notice-success">' +
                                '<span class="dashicons dashicons-yes-alt"></span> ' +
                                response.data.message +
                                '</div>'
                            );
                            
                            // Remove notice after 3 seconds
                            setTimeout(function() {
                                $card.find('.rwpvto-inline-notice').fadeOut(function() {
                                    $(this).remove();
                                });
                            }, 3000);
                        } else {
                            $button.prop('disabled', false).removeClass('loading');
                            $buttonText.text('Add to Gallery');
                            
                            // Show error notice
                            var errorMsg = response.data && response.data.message ? response.data.message : 'Unknown error occurred';
                            $card.find('.rwpvto-image-info').prepend(
                                '<div class="rwpvto-inline-notice rwpvto-notice-error">' +
                                '<span class="dashicons dashicons-dismiss"></span> ' +
                                errorMsg +
                                '</div>'
                            );
                        }
                    },
                    error: function(xhr, status, error) {
                        $button.prop('disabled', false).removeClass('loading');
                        $buttonText.text('Add to Gallery');
                        
                        var errorMsg = 'An error occurred. ';
                        if (status === 'timeout') {
                            errorMsg += 'The request timed out. The image might be too large or the connection is slow.';
                        } else if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                            errorMsg += xhr.responseJSON.data.message;
                        } else {
                            errorMsg += 'Please check your internet connection and try again.';
                        }
                        
                        // Show error notice
                        $card.find('.rwpvto-image-info').prepend(
                            '<div class="rwpvto-inline-notice rwpvto-notice-error">' +
                            '<span class="dashicons dashicons-dismiss"></span> ' +
                            errorMsg +
                            '</div>'
                        );
                        
                        console.error('Add to gallery error:', status, error, xhr);
                    }
                });
            });
            
            // Delete image
            $(document).on('click', '.rwpvto-delete-image-btn', function(e) {
                e.preventDefault();
                
                var $button = $(this);
                var $buttonText = $button.find('span:last-child');
                var imageId = $button.data('image-id');
                var $card = $button.closest('.rwpvto-image-card');
                
                // Show confirmation inline
                if (!$button.hasClass('confirm-delete')) {
                    $button.addClass('confirm-delete');
                    $buttonText.text('Are you sure?');
                    
                    // Reset after 3 seconds
                    setTimeout(function() {
                        if ($button.hasClass('confirm-delete')) {
                            $button.removeClass('confirm-delete');
                            $buttonText.text('Delete');
                        }
                    }, 3000);
                    
                    return;
                }
                
                // Actually delete
                $button.removeClass('confirm-delete').prop('disabled', true);
                $buttonText.text('Deleting...');
                
                $.ajax({
                    url: rwpvtoAdmin.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'rwpvto_delete_image',
                        nonce: rwpvtoAdmin.nonce,
                        image_id: imageId
                    },
                    success: function(response) {
                        if (response.success) {
                            $card.fadeOut(function() {
                                $(this).remove();
                                
                                // Check if grid is empty
                                if ($('.rwpvto-images-grid .rwpvto-image-card').length === 0) {
                                    location.reload();
                                }
                            });
                        } else {
                            $button.prop('disabled', false);
                            $buttonText.text('Delete');
                            
                            // Show error notice
                            $card.find('.rwpvto-image-info').prepend(
                                '<div class="rwpvto-inline-notice rwpvto-notice-error">' +
                                '<span class="dashicons dashicons-dismiss"></span> ' +
                                (response.data && response.data.message ? response.data.message : 'Failed to delete image') +
                                '</div>'
                            );
                        }
                    },
                    error: function() {
                        $button.prop('disabled', false);
                        $buttonText.text('Delete');
                        
                        // Show error notice
                        $card.find('.rwpvto-image-info').prepend(
                            '<div class="rwpvto-inline-notice rwpvto-notice-error">' +
                            '<span class="dashicons dashicons-dismiss"></span> ' +
                            'An error occurred. Please try again.' +
                            '</div>'
                        );
                    }
                });
            });
        },
        
        /**
         * Settings page functionality
         */
        settingsPage: function() {
            // Animate success messages
            if ($('.rwpvto-settings-wrap .notice, .rwpvto-settings-wrap .updated').length) {
                $('.rwpvto-settings-wrap .notice, .rwpvto-settings-wrap .updated').hide().slideDown(400);
                
                // Scroll to notice
                $('html, body').animate({
                    scrollTop: $('.rwpvto-settings-wrap .notice, .rwpvto-settings-wrap .updated').offset().top - 100
                }, 300);
            }
            
            // Toggle API key visibility
            $('.rwpvto-toggle-api-key').on('click', function() {
                var $input = $('#rwpvto_api_key');
                var $icon = $(this).find('.dashicons');
                
                if ($input.attr('type') === 'password') {
                    $input.attr('type', 'text');
                    $icon.removeClass('dashicons-visibility').addClass('dashicons-hidden');
                } else {
                    $input.attr('type', 'password');
                    $icon.removeClass('dashicons-hidden').addClass('dashicons-visibility');
                }
            });
            
            // Sync range slider with number input for steps
            var $stepsRange = $('#rwpvto_steps_range');
            var $stepsNumber = $('#rwpvto_default_steps');
            
            if ($stepsRange.length && $stepsNumber.length) {
                // Update number input when range changes
                $stepsRange.on('input', function() {
                    $stepsNumber.val($(this).val());
                });
                
                // Update range when number input changes
                $stepsNumber.on('input', function() {
                    var val = parseInt($(this).val());
                    if (!isNaN(val)) {
                        $stepsRange.val(val);
                    }
                });
            }
            
            // Test API connection
            $('.rwpvto-test-api-btn').on('click', function(e) {
                e.preventDefault();
                
                var $button = $(this);
                var $result = $('.rwpvto-test-result');
                var $icon = $button.find('.dashicons');
                var originalText = $button.text().trim();
                
                $button.prop('disabled', true);
                $icon.removeClass('dashicons-update').addClass('dashicons-update-alt').css('animation', 'rotation 1s infinite linear');
                
                $result.removeClass('success error').html('').hide();
                
                $.ajax({
                    url: rwpvtoAdmin.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'rwpvto_test_api',
                        nonce: rwpvtoAdmin.nonce
                    },
                    success: function(response) {
                        $button.prop('disabled', false);
                        $icon.removeClass('dashicons-update-alt').addClass('dashicons-update').css('animation', '');
                        
                        if (response.success) {
                            $result.addClass('success').html('✓ ' + response.data.message).fadeIn();
                        } else {
                            $result.addClass('error').html('✗ ' + response.data.message).fadeIn();
                        }
                    },
                    error: function() {
                        $button.prop('disabled', false);
                        $icon.removeClass('dashicons-update-alt').addClass('dashicons-update').css('animation', '');
                        $result.addClass('error').html('✗ Connection failed. Please check your API key and try again.').fadeIn();
                    }
                });
            });
        },
        
        /**
         * Show validation error
         */
        showValidationError: function(message) {
            $('.rwpvto-validation-notice').remove();
            
            var notice = $('<div class="rwpvto-validation-notice">' +
                '<span class="dashicons dashicons-warning"></span> ' +
                '<strong>Validation Error:</strong> ' + message +
                '</div>');
            
            $('.rwpvto-form-actions').before(notice);
            
            // Scroll to notice
            $('html, body').animate({
                scrollTop: notice.offset().top - 100
            }, 300);
            
            // Remove after 5 seconds
            setTimeout(function() {
                notice.fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);
        },
        
        /**
         * Show image in modal
         */
        showImageModal: function(imageUrl) {
            // Create modal if it doesn't exist
            if ($('#rwpvto-modal').length === 0) {
                $('body').append(
                    '<div id="rwpvto-modal" class="rwpvto-modal">' +
                    '<span class="rwpvto-modal-close">&times;</span>' +
                    '<img class="rwpvto-modal-content" id="rwpvto-modal-img">' +
                    '</div>'
                );
                
                // Close modal on click
                $(document).on('click', '.rwpvto-modal-close, .rwpvto-modal', function(e) {
                    if (e.target === this) {
                        $('#rwpvto-modal').hide();
                    }
                });
                
                // Close modal on ESC key
                $(document).on('keyup', function(e) {
                    if (e.key === 'Escape') {
                        $('#rwpvto-modal').hide();
                    }
                });
            }
            
            // Show modal with image
            $('#rwpvto-modal-img').attr('src', imageUrl);
            $('#rwpvto-modal').show();
        }
    };
    
})(jQuery);

