/**
 * AI Product Content & Image Generator - Admin JavaScript
 * Handles dashboard interactions and AJAX requests
 */

(function($) {
    'use strict';

    // Main plugin object
    const APCIG = {
        // Configuration
        config: {
            ajaxUrl: (typeof apcig_admin !== 'undefined') ? apcig_admin.ajax_url : '',
            nonce: (typeof apcig_admin !== 'undefined') ? apcig_admin.nonce : '',
            currentPage: (typeof apcig_admin !== 'undefined') ? (apcig_admin.current_page || 'dashboard') : 'dashboard',
            strings: (typeof apcig_admin !== 'undefined') ? apcig_admin.strings : {}
        },

        // Initialize the plugin
        init: function() {
            console.log('APCIG: Initializing plugin...');
            this.bindEvents();
            this.initComponents();
            this.loadDashboardStats();
            console.log('APCIG: Plugin initialized successfully');
        },

        // Bind event listeners
        bindEvents: function() {
            // Navigation
            $(document).on('click', '.apcig-nav a', this.handleNavigation.bind(this));
            
            // Tab functionality
            $(document).on('click', '.apcig-tab-button', this.handleTabSwitch.bind(this));
            $(document).on('click', '.apcig-method-tab', this.handleMethodTabSwitch.bind(this));
            
            // Content generation
            $(document).on('click', '.apcig-generate-content', this.generateContent.bind(this));
            $(document).on('click', '.apcig-generate-bulk', this.generateBulkContent.bind(this));
            
            // Image generation
            $(document).on('click', '.apcig-generate-image', this.generateImage.bind(this));
            $(document).on('click', '.apcig-enhance-image', this.enhanceImage.bind(this));
            
            // Settings
            $(document).on('click', '.apcig-save-settings', this.saveSettings.bind(this));
            $(document).on('click', '.apcig-test-api', this.testApiConnection.bind(this));
            $(document).on('click', '#reset-settings', this.resetSettings.bind(this));
            $(document).on('click', '#export-settings', this.exportSettings.bind(this));
            $(document).on('click', '#import-settings', this.importSettings.bind(this));
            
            // Form submissions - prevent default for settings form
            $(document).on('submit', '#apcig-settings-form', this.handleSettingsFormSubmit.bind(this));
            // Note: Specific form handlers are bound in their respective init functions
            // Generic form handler removed to prevent conflicts
            
            // Bulk processing controls
            $(document).on('click', '.apcig-select-all', this.selectAllProducts.bind(this));
            $(document).on('click', '.apcig-select-none', this.selectNoneProducts.bind(this));
            $(document).on('click', '.apcig-select-missing-content', this.selectMissingContent.bind(this));
            $(document).on('click', '.apcig-select-missing-images', this.selectMissingImages.bind(this));
            $(document).on('change', '.apcig-product-checkbox', this.updateSelectedCount.bind(this));
            $(document).on('change', '.apcig-product-radio', this.updateSelectedCount.bind(this));
            $(document).on('click', '.apcig-start-bulk', this.startBulkProcessing.bind(this));
            $(document).on('click', '.apcig-pause-bulk', this.pauseBulkProcess.bind(this));
            $(document).on('click', '.apcig-stop-bulk', this.stopBulkProcess.bind(this));
            
            // Progress tracking
            $(document).on('click', '.apcig-cancel-process', this.cancelProcess.bind(this));
            
            // Alert dismiss functionality
            $(document).on('click', '.apcig-alert-close', this.dismissAlert.bind(this));
        },

        // Initialize components
        initComponents: function() {
            this.initTooltips();
            this.initProgressBars();
            this.initFormValidation();
            this.initFileUploads();
            this.initSliders();
            this.initToggleSwitches();
            this.initImageGeneration();
            this.initFileUploadAreas();
            this.initPageSpecificComponents();
        },
        handleNavigation: function(e) {
            // Let WordPress handle the navigation normally
            // Remove preventDefault to allow normal page navigation
            const $link = $(e.currentTarget);
            const page = $link.data('page');
            
            if (page) {
                // Update current page for any cleanup needed
                this.config.currentPage = page;
            }
        },

        // Handle tab switching
        handleTabSwitch: function(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const tabId = $button.data('tab');
            
            if (!tabId) return;
            
            // Remove active class from all tab buttons and content
            $button.closest('.apcig-tabs').find('.apcig-tab-button').removeClass('active');
            $button.closest('.apcig-tabs').find('.apcig-tab-content').removeClass('active');
            
            // Add active class to clicked button and corresponding content
            $button.addClass('active');
            $('#' + tabId).addClass('active');
            
            // Store current tab
            this.currentTab = tabId;
        },

        // Handle method tab switching (for bulk processing)
        handleMethodTabSwitch: function(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const method = $button.data('method');
            
            if (!method) return;
            
            // Remove active class from all method tabs and panels
            $button.closest('.apcig-selection-methods').find('.apcig-method-tab').removeClass('active');
            $button.closest('.apcig-selection-methods').find('.apcig-method-panel').removeClass('active');
            
            // Add active class to clicked button and corresponding panel
            $button.addClass('active');
            $('#method-' + method).addClass('active');
            
            // Store current method
            this.currentMethod = method;
        },

        // Update navigation active state
        updateNavigation: function(activePage) {
            $('.apcig-nav a').removeClass('current');
            $(`.apcig-nav a[data-page="${activePage}"]`).addClass('current');
        },

        // Generate content for a single product
        generateContent: function(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const productId = $button.data('product-id');
            const contentType = $button.data('content-type') || 'description';
            const tone = $('#apcig-tone').val() || 'professional';
            
            if (!productId) {
                this.showAlert('error', 'Product ID is required');
                return;
            }
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_generate_content',
                    product_id: productId,
                    content_type: contentType,
                    tone: tone,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.displayGeneratedContent(response.data);
                        this.showAlert('success', 'Content generated successfully!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to generate content');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },

        // Generate content for multiple products
        generateBulkContent: function(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const selectedProducts = this.getSelectedProducts();
            
            if (selectedProducts.length === 0) {
                this.showAlert('error', 'Please select at least one product');
                return;
            }
            
            if (selectedProducts.length > 50) {
                this.showAlert('error', 'Maximum 50 products can be processed at once');
                return;
            }
            
            this.startBulkProcess($button, 'content', selectedProducts);
        },

        // Generate image for a product
        generateImage: function(e) {
            e.preventDefault();
            const $form = $(e.currentTarget).closest('form');
            const $button = $form.find('button[type="submit"]');
            
            // Get form data
            const productId = $form.find('[name="product_id"]').val();
            const description = $form.find('[name="description"]').val();
            const style = $form.find('[name="style"]:checked').val();
            const size = $form.find('[name="size"]').val() || '1024x1024';
            const count = $form.find('[name="count"]').val() || 1;
            const provider = $form.find('[name="provider"]').val() || 'openai';
            
            // Validate required fields
            if (!productId) {
                this.showAlert('error', 'Please select a product');
                return;
            }
            
            if (!description) {
                this.showAlert('error', 'Please enter an image description');
                return;
            }
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                timeout: 180000, // 3 minutes timeout
                data: {
                    action: 'apcig_generate_image',
                    product_id: productId,
                    description: description,
                    style: style,
                    size: size,
                    count: count,
                    provider: provider,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.displayGeneratedImages(response.data);
                        this.showAlert('success', 'Images generated successfully!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to generate images');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },

        // Enhance existing image
        enhanceImage: function(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const imageId = $button.data('image-id');
            const enhanceType = $button.data('enhance-type') || 'quality';
            
            if (!imageId) {
                this.showAlert('error', 'Image ID is required');
                return;
            }
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                timeout: 180000, // 3 minutes timeout
                data: {
                    action: 'apcig_enhance_image',
                    image_id: imageId,
                    enhance_type: enhanceType,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.displayEnhancedImage(response.data);
                        this.showAlert('success', 'Image enhanced successfully!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to enhance image');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },

        // Save plugin settings
        saveSettings: function(e) {
            e.preventDefault();
            console.log('APCIG: Saving settings...');
            
            const $button = $(e.currentTarget);
            const $form = $button.closest('form');
            
            // Check if we have the required configuration
            if (!this.config.ajaxUrl) {
                console.error('APCIG: AJAX URL not configured');
                this.showAlert('error', 'Configuration error: AJAX URL not found');
                return;
            }
            
            if (!this.config.nonce) {
                console.error('APCIG: Nonce not configured');
                this.showAlert('error', 'Configuration error: Security nonce not found');
                return;
            }
            
            // Validate form first
            if (!this.validateForm($form)) {
                this.showAlert('error', 'Please fill in all required fields');
                return;
            }
            
            // Serialize form data into settings object
            const settings = {};
            $form.find('input, select, textarea').each(function() {
                const $field = $(this);
                const name = $field.attr('name');
                if (name && name !== 'apcig_settings_nonce' && name !== '_wp_http_referer') {
                    if ($field.attr('type') === 'checkbox') {
                        settings[name] = $field.is(':checked') ? 1 : 0;
                    } else {
                        settings[name] = $field.val();
                    }
                }
            });
            
            console.log('APCIG: Settings to save:', settings);
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_save_settings',
                    settings: settings,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    console.log('APCIG: Settings save response:', response);
                    if (response.success) {
                        this.showAlert('success', 'Settings saved successfully!');
                        // Update provider status indicators
                        this.updateProviderStatus(settings);
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to save settings');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('APCIG: Settings save error:', {xhr, status, error});
                    this.showAlert('error', 'Network error occurred while saving settings');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },

        // Update provider status indicators after saving
        updateProviderStatus: function(settings) {
            const providers = ['openai', 'claude', 'gemini', 'openrouter'];
            
            providers.forEach(provider => {
                const apiKey = settings[provider + '_api_key'];
                const $status = $('#' + provider + '-status .apcig-status-indicator');
                
                if (apiKey && apiKey.trim() !== '') {
                    $status.removeClass('disconnected').addClass('connected')
                           .html('<span class="dashicons dashicons-yes-alt"></span> Connected');
                } else {
                    $status.removeClass('connected').addClass('disconnected')
                           .html('<span class="dashicons dashicons-warning"></span> Not Connected');
                }
            });
        },

        // Test API connection
        testApiConnection: function(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const provider = $button.data('provider');
            const apiKey = $(`input[name="${provider}_api_key"]`).val();
            
            if (!apiKey || apiKey.trim() === '') {
                this.showAlert('error', 'API key is required');
                return;
            }
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_test_api_connection',
                    provider: provider,
                    api_key: apiKey,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showAlert('success', `${provider} API connection successful!`);
                    } else {
                        this.showAlert('error', response.data.message || 'API connection failed');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },

        // Handle settings form submission
        handleSettingsFormSubmit: function(e) {
            e.preventDefault();
            // Trigger the save settings function
            this.saveSettings(e);
        },

        // Handle form submissions
        // Note: Form submission is now handled by specific handlers in their respective init functions
        // This generic handler has been removed to prevent conflicts and duplicate submissions

        // Initialize page-specific components
        initPageSpecificComponents: function() {
            const currentPage = this.config.currentPage;
            
            // Also check URL parameters and page content to determine current page
            const urlParams = new URLSearchParams(window.location.search);
            const pageParam = urlParams.get('page');
            
            // Check if we're on a content generator page
            if (pageParam === 'ai-product-content' || currentPage === 'content-generator' || $('.apcig-content-generator').length > 0) {
                this.initContentGenerator();
            }
            // Check if we're on an image generator page
            else if (pageParam === 'ai-product-images' || currentPage === 'image-generator' || $('.apcig-image-generator').length > 0) {
                this.initImageGenerator();
            }
            // Check if we're on a settings page
            else if (pageParam === 'ai-product-settings' || currentPage === 'settings' || $('.apcig-settings').length > 0) {
                this.initSettings();
            }
            // Check if we're on a bulk processing page
            else if (pageParam === 'apcig-bulk-processor' || currentPage === 'bulk-processing' || $('.apcig-bulk-processing').length > 0) {
                this.initBulkProcessor();
            }
        },
        
        // Bulk Processor specific functionality
        initBulkProcessor: function() {
            console.log('APCIG: Initializing Bulk Processor');
            
            // Handle action type changes
            $(document).on('change', 'input[name="bulk_action"]', this.handleBulkActionChange.bind(this));
            
            // Handle method tab changes
            $(document).on('click', '.apcig-method-tab', this.handleMethodTabChange.bind(this));
            
            // Handle category selection
            $(document).on('change', 'input[name="categories[]"]', this.handleCategorySelection.bind(this));
            
            // Handle filter application
            $(document).on('change', 'input[name="filters[]"]', this.handleFilterSelection.bind(this));
            
            // Handle load more
            $(document).on('click', '#load-more-products', this.handleLoadMoreProducts.bind(this));
            
            // Initialize with content settings visible (with small delay to ensure DOM is ready)
            setTimeout(() => {
                this.handleBulkActionChange();
            }, 100);
        },
        
        // Handle bulk action type change
        handleBulkActionChange: function() {
            const selectedAction = $('input[name="bulk_action"]:checked').val();
            
            console.log('APCIG: Bulk action changed to:', selectedAction);
            
            // Remove active class from all settings
            $('.apcig-action-settings').removeClass('active').hide();
            
            // Show appropriate settings based on action
            if (selectedAction === 'generate_content') {
                $('#content-settings').addClass('active').show();
                console.log('APCIG: Showing content settings');
            } else if (selectedAction === 'generate_images') {
                $('#image-settings').addClass('active').show();
                console.log('APCIG: Showing image settings');
            }
        },
        
        // Handle method tab change
        handleMethodTabChange: function(e) {
            const $tab = $(e.currentTarget);
            const method = $tab.data('method');
            
            // Update active tab
            $('.apcig-method-tab').removeClass('active');
            $tab.addClass('active');
            
            // Show corresponding content
            $('.apcig-method-content').removeClass('active');
            $(`#${method}-selection`).addClass('active');
            
            console.log('APCIG: Method changed to:', method);
        },
        
        // Handle category selection
        handleCategorySelection: function() {
            const selectedCategories = $('input[name="categories[]"]:checked').map(function() {
                return $(this).val();
            }).get();
            
            if (selectedCategories.length > 0) {
                this.loadProductsByCategory(selectedCategories);
            }
        },
        
        // Load products by category
        loadProductsByCategory: function(categoryIds) {
            console.log('APCIG: Loading products for categories:', categoryIds);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_get_products_by_category',
                    category_ids: categoryIds,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.displayProducts(response.data.products);
                    }
                },
                error: () => {
                    this.showAlert('error', 'Failed to load products by category');
                }
            });
        },
        
        // Handle filter selection
        handleFilterSelection: function() {
            const selectedFilters = $('input[name="filters[]"]:checked').map(function() {
                return $(this).val();
            }).get();
            
            const priceMin = $('input[name="price_min"]').val();
            const priceMax = $('input[name="price_max"]').val();
            const dateFrom = $('input[name="date_from"]').val();
            const dateTo = $('input[name="date_to"]').val();
            
            if (selectedFilters.length > 0 || priceMin || priceMax || dateFrom || dateTo) {
                this.loadProductsByFilters({
                    filters: selectedFilters,
                    price_min: priceMin,
                    price_max: priceMax,
                    date_from: dateFrom,
                    date_to: dateTo
                });
            }
        },
        
        // Load products by filters
        loadProductsByFilters: function(filterData) {
            console.log('APCIG: Loading products with filters:', filterData);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_get_products_by_filters',
                    filters: filterData,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.displayProducts(response.data.products);
                    }
                },
                error: () => {
                    this.showAlert('error', 'Failed to load products by filters');
                }
            });
        },
        
        // Handle load more products
        handleLoadMoreProducts: function() {
            const currentCount = $('.apcig-product-item').length;
            const $button = $('#load-more-products');
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_load_more_products',
                    offset: currentCount,
                    limit: 50,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success && response.data.products) {
                        this.appendProducts(response.data.products);
                        
                        // Hide button if no more products
                        if (!response.data.has_more) {
                            $button.hide();
                        }
                    }
                },
                error: () => {
                    this.showAlert('error', 'Failed to load more products');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },
        
        // Display products in list
        displayProducts: function(products) {
            const $list = $('#products-list');
            $list.empty();
            
            products.forEach(product => {
                const productHTML = this.createProductHTML(product);
                $list.append(productHTML);
            });
            
            this.updateSelectedCount();
        },
        
        // Append products to list
        appendProducts: function(products) {
            const $list = $('#products-list');
            
            products.forEach(product => {
                const productHTML = this.createProductHTML(product);
                $list.append(productHTML);
            });
        },
        
        // Create product HTML
        createProductHTML: function(product) {
            return `
                <div class="apcig-product-item" data-product-id="${product.id}">
                    <label class="apcig-product-checkbox-label">
                        <input type="checkbox" class="apcig-product-checkbox" value="${product.id}">
                        <div class="apcig-product-info">
                            <div class="apcig-product-image">
                                ${product.image_url ? `<img src="${product.image_url}" alt="${product.name}">` : '<div class="apcig-no-image"><span class="dashicons dashicons-format-image"></span></div>'}
                            </div>
                            <div class="apcig-product-details">
                                <h4 class="apcig-product-title">${product.name}</h4>
                                <div class="apcig-product-meta">
                                    <span class="apcig-product-price">${product.price_html}</span>
                                    ${product.sku ? `<span class="apcig-product-sku">SKU: ${product.sku}</span>` : ''}
                                </div>
                                <div class="apcig-content-status">
                                    <span class="apcig-status-badge ${product.has_short_description ? 'success' : 'missing'}">Short Desc</span>
                                    <span class="apcig-status-badge ${product.has_description ? 'success' : 'missing'}">Long Desc</span>
                                    <span class="apcig-status-badge ${product.has_tags ? 'success' : 'missing'}">Tags</span>
                                </div>
                            </div>
                        </div>
                    </label>
                </div>
            `;
        },

        // Content Generator specific functionality
        initContentGenerator: function() {
            console.log('APCIG: Initializing Content Generator');
            this.initProductSearch();
            this.initProductSelection();
            this.initStepNavigation();
            
            // Handle load more for content generator
            $(document).on('click', '#load-more-content-products', this.handleLoadMoreContentProducts.bind(this));
        },
        
        // Handle load more products in content generator
        handleLoadMoreContentProducts: function() {
            const currentCount = $('#products-grid .apcig-product-card').length;
            const $button = $('#load-more-content-products');
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_load_more_products',
                    offset: currentCount,
                    limit: 20,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success && response.data.products) {
                        this.appendContentProducts(response.data.products);
                        
                        // Update count
                        $('.apcig-products-count').text(`Showing ${currentCount + response.data.products.length} of ${response.data.total} products`);
                        
                        // Hide button if no more products
                        if (!response.data.has_more) {
                            $button.hide();
                        }
                    }
                },
                error: () => {
                    this.showAlert('error', 'Failed to load more products');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },
        
        // Append products to content generator grid
        appendContentProducts: function(products) {
            const $grid = $('#products-grid');
            
            products.forEach(product => {
                const productHTML = `
                    <div class="apcig-product-card" data-product-id="${product.id}">
                        <div class="apcig-product-radio-wrapper">
                            <input type="radio" name="selected_product" class="apcig-product-radio" value="${product.id}" id="product-${product.id}">
                            <label for="product-${product.id}"></label>
                        </div>
                        
                        <div class="apcig-product-image">
                            ${product.image_url ? `<img src="${product.image_url}" alt="${product.name}">` : '<div class="apcig-no-image"><span class="dashicons dashicons-format-image"></span></div>'}
                        </div>
                        
                        <div class="apcig-product-info">
                            <h4 class="apcig-product-title">${product.name}</h4>
                            <div class="apcig-product-price">${product.price_html}</div>
                            ${product.sku ? `<div class="apcig-product-sku"><small>SKU: ${product.sku}</small></div>` : ''}
                            
                            <div class="apcig-content-status">
                                <span class="apcig-status-badge ${product.has_short_description ? 'success' : 'missing'}">Short Desc</span>
                                <span class="apcig-status-badge ${product.has_description ? 'success' : 'missing'}">Long Desc</span>
                                <span class="apcig-status-badge ${product.has_tags ? 'success' : 'missing'}">Tags</span>
                            </div>
                        </div>
                    </div>
                `;
                $grid.append(productHTML);
            });
        },

        // Image Generator specific functionality
        initImageGenerator: function() {
            console.log('APCIG: Initializing Image Generator');
            
            // Handle product selection to show current product image
            $(document).on('change', '#image-generation-form select[name="product_id"]', this.handleProductImagePreview.bind(this));
            
            // Initialize file upload areas
            this.initImageUploadArea('#image-upload-area', '#image-upload', '#image-preview-list', '#image-enhancement-form button[type="submit"]');
            this.initImageUploadArea('#bg-removal-upload-area', '#bg-removal-upload', '#bg-removal-preview-list', '#background-removal-form button[type="submit"]');
            
            // Handle custom color picker visibility
            $(document).on('change', 'input[name="background"]', this.handleBackgroundTypeChange.bind(this));
            
            // Handle enhancement strength slider
            $(document).on('input', '#enhancement-strength', function() {
                $('#strength-value').text($(this).val());
            });
            
            // Handle clear history
            $(document).on('click', '#clear-history', this.handleClearImageHistory.bind(this));
            
            // Load generation history
            this.loadImageGenerationHistory();
        },
        
        // Load image generation history
        loadImageGenerationHistory: function() {
            const history = localStorage.getItem('apcig_image_history');
            if (history) {
                try {
                    const historyData = JSON.parse(history);
                    this.displayImageHistory(historyData);
                } catch (e) {
                    console.error('Failed to parse image history:', e);
                }
            }
        },
        
        // Display image history
        displayImageHistory: function(historyData) {
            const $historyGrid = $('#generation-history');
            
            if (!historyData || historyData.length === 0) {
                return;
            }
            
            $historyGrid.empty();
            
            // Show last 12 items
            const recentItems = historyData.slice(-12).reverse();
            
            recentItems.forEach(item => {
                const historyHTML = `
                    <div class="apcig-history-item">
                        <div class="apcig-history-image">
                            <img src="${item.url}" alt="${item.product_name}">
                        </div>
                        <div class="apcig-history-info">
                            <h5>${item.product_name}</h5>
                            <small>${item.timestamp}</small>
                        </div>
                    </div>
                `;
                $historyGrid.append(historyHTML);
            });
        },
        
        // Save to image history
        saveToImageHistory: function(imageData) {
            let history = [];
            const stored = localStorage.getItem('apcig_image_history');
            
            if (stored) {
                try {
                    history = JSON.parse(stored);
                } catch (e) {
                    history = [];
                }
            }
            
            history.push({
                url: imageData.url,
                product_name: imageData.product_name || 'Unknown Product',
                timestamp: new Date().toLocaleString()
            });
            
            // Keep only last 50 items
            if (history.length > 50) {
                history = history.slice(-50);
            }
            
            localStorage.setItem('apcig_image_history', JSON.stringify(history));
            this.displayImageHistory(history);
        },
        
        // Handle clear image history
        handleClearImageHistory: function(e) {
            e.preventDefault();
            
            if (confirm('Are you sure you want to clear the generation history?')) {
                localStorage.removeItem('apcig_image_history');
                $('#generation-history').html(`
                    <div class="apcig-history-placeholder">
                        <span class="dashicons dashicons-clock"></span>
                        <p>Your recent image generations will appear here</p>
                    </div>
                `);
                this.showAlert('success', 'Generation history cleared');
            }
        },
        
        // Handle product image preview
        handleProductImagePreview: function(e) {
            const productId = $(e.currentTarget).val();
            
            if (!productId) {
                $('#product-image-preview').hide();
                return;
            }
            
            // Get product data to show current image
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_get_product_data',
                    product_id: productId,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success && response.data.image_url) {
                        $('#current-product-image').attr('src', response.data.image_url);
                        $('#product-image-preview').fadeIn();
                    } else {
                        $('#product-image-preview').hide();
                        this.showAlert('warning', 'This product does not have an image. Please add a product image first.');
                    }
                },
                error: () => {
                    console.error('Failed to load product data');
                }
            });
        },
        


        // Settings specific functionality
        initSettings: function() {
            console.log('APCIG: Initializing Settings');
            
            // Handle clear generation history
            $(document).on('click', '#clear-generation-history', this.handleClearGenerationHistory.bind(this));
            
            // Handle clear all data
            $(document).on('click', '#clear-all-data', this.handleClearAllData.bind(this));
        },
        
        // Handle clear generation history
        handleClearGenerationHistory: function(e) {
            e.preventDefault();
            
            if (!confirm('Are you sure you want to clear the generation history? This action cannot be undone.')) {
                return;
            }
            
            const $button = $(e.currentTarget);
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_clear_generation_history',
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showAlert('success', 'Generation history cleared successfully');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to clear history');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },
        
        // Handle clear all data
        handleClearAllData: function(e) {
            e.preventDefault();
            
            if (!confirm('WARNING: This will delete ALL plugin data including history, statistics, and batch jobs. This action cannot be undone. Are you absolutely sure?')) {
                return;
            }
            
            const $button = $(e.currentTarget);
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_clear_all_data',
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showAlert('success', 'All plugin data cleared successfully');
                        // Reload page after 2 seconds
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000);
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to clear data');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },

        // Bulk Processor specific functionality
        initBulkProcessor: function() {
            console.log('APCIG: Initializing Bulk Processor');
            // Bulk processor functionality will be added here
        },

        // Initialize sliders
        initSliders: function() {
            // Max tokens slider
            $('#max-tokens-slider').on('input', function() {
                $('#max-tokens-value').text($(this).val());
            });

            // Temperature slider
            $('#temperature-slider').on('input', function() {
                $('#temperature-value').text($(this).val());
            });
        },

        // Initialize toggle switches
        initToggleSwitches: function() {
            $('.apcig-toggle-option input[type="checkbox"]').on('change', function() {
                const $toggle = $(this).closest('.apcig-toggle-option');
                if ($(this).is(':checked')) {
                    $toggle.addClass('active');
                } else {
                    $toggle.removeClass('active');
                }
            });

            // Set initial state
            $('.apcig-toggle-option input[type="checkbox"]:checked').each(function() {
                $(this).closest('.apcig-toggle-option').addClass('active');
            });
        },

        // Load dashboard statistics
        loadDashboardStats: function() {
            if (this.config.currentPage !== 'dashboard') {
                return;
            }
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_get_stats',
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.updateDashboardStats(response.data);
                    }
                }
            });
        },

        // Update dashboard statistics
        updateDashboardStats: function(stats) {
            $('.apcig-stat-number').each(function() {
                const $stat = $(this);
                const statType = $stat.data('stat');
                if (stats[statType] !== undefined) {
                    $stat.text(stats[statType]);
                }
            });
        },

        // Utility functions
        getSelectedProducts: function() {
            const selected = [];
            // Check if we're on content generator page (uses radio buttons)
            if ($('.apcig-product-radio').length > 0) {
                const selectedRadio = $('.apcig-product-radio:checked').val();
                if (selectedRadio) {
                    selected.push(selectedRadio);
                }
            } else {
                // Bulk processing page (uses checkboxes)
                $('.apcig-product-checkbox:checked').each(function() {
                    selected.push($(this).val());
                });
            }
            return selected;
        },

        selectAllProducts: function() {
            $('.apcig-product-checkbox:visible').prop('checked', true);
            this.updateSelectedCount();
        },

        selectNoneProducts: function() {
            $('.apcig-product-checkbox').prop('checked', false);
            this.updateSelectedCount();
        },

        selectMissingContent: function() {
            $('.apcig-product-checkbox').each(function() {
                const $product = $(this).closest('.apcig-product-item');
                const hasContent = $product.find('.apcig-status-badge.success').length > 0;
                $(this).prop('checked', !hasContent);
            });
            this.updateSelectedCount();
        },

        selectMissingImages: function() {
            $('.apcig-product-checkbox').each(function() {
                const $product = $(this).closest('.apcig-product-item');
                const hasImages = $product.find('.apcig-status-badge.success').length > 1;
                $(this).prop('checked', !hasImages);
            });
            this.updateSelectedCount();
        },

        updateSelectedCount: function() {
            // For bulk processing (checkboxes)
            const count = $('.apcig-product-checkbox:checked').length;
            $('#selected-count').text(count);
            $('.apcig-start-bulk').prop('disabled', count === 0);
            
            // For content generator (radio buttons)
            const radioSelected = $('.apcig-product-radio:checked').length > 0;
            $('#continue-to-step-2').prop('disabled', !radioSelected);
        },

        setButtonLoading: function($button, loading) {
            if (loading) {
                $button.prop('disabled', true)
                       .addClass('apcig-loading')
                       .prepend('<span class="apcig-spinner"></span>');
            } else {
                $button.prop('disabled', false)
                       .removeClass('apcig-loading')
                       .find('.apcig-spinner').remove();
            }
        },

        showLoading: function() {
            $('.apcig-main-content').addClass('apcig-loading-overlay');
        },

        hideLoading: function() {
            $('.apcig-main-content').removeClass('apcig-loading-overlay');
        },

        showAlert: function(type, message) {
            const alertHtml = `
                <div class="apcig-alert apcig-alert-${type}">
                    <span class="dashicons dashicons-${this.getAlertIcon(type)}"></span>
                    <span>${message}</span>
                    <button type="button" class="apcig-alert-close">
                        <span class="dashicons dashicons-no-alt"></span>
                    </button>
                </div>
            `;
            
            // Use settings-specific container if on settings page, otherwise use main container
            let $container = $('.apcig-settings-alerts');
            if ($container.length === 0) {
                $container = $('.apcig-alerts-container');
            }
            
            $container.prepend(alertHtml);
            
            // Auto-hide success alerts
            if (type === 'success') {
                setTimeout(() => {
                    $('.apcig-alert-success').first().fadeOut();
                }, 5000);
            }
        },

        getAlertIcon: function(type) {
            const icons = {
                success: 'yes-alt',
                error: 'warning',
                warning: 'info',
                info: 'info'
            };
            return icons[type] || 'info';
        },

        // Dismiss alert
        dismissAlert: function(e) {
            e.preventDefault();
            $(e.currentTarget).closest('.apcig-alert').fadeOut();
        },

        validateForm: function($form) {
            let isValid = true;
            
            $form.find('[required]').each(function() {
                const $field = $(this);
                if (!$field.val().trim()) {
                    $field.addClass('apcig-error');
                    isValid = false;
                } else {
                    $field.removeClass('apcig-error');
                }
            });
            
            return isValid;
        },

        initTooltips: function() {
            $('[data-tooltip]').each(function() {
                $(this).attr('title', $(this).data('tooltip'));
            });
        },

        initProgressBars: function() {
            $('.apcig-progress-bar').each(function() {
                const $bar = $(this);
                const percentage = $bar.data('percentage') || 0;
                $bar.css('width', percentage + '%');
            });
        },

        initFormValidation: function() {
            $('.apcig-input, .apcig-select, .apcig-textarea').on('blur', function() {
                const $field = $(this);
                if ($field.attr('required') && !$field.val().trim()) {
                    $field.addClass('apcig-error');
                } else {
                    $field.removeClass('apcig-error');
                }
            });
        },

        initFileUploads: function() {
            $('.apcig-file-upload').on('change', function() {
                const $input = $(this);
                const $label = $input.next('label');
                const fileName = $input[0].files[0]?.name || 'Choose file';
                $label.text(fileName);
            });
        },

        // Initialize product search functionality
        initProductSearch: function() {
            const $searchInput = $('#product-search');
            const $categoryFilter = $('#category-filter');
            const $statusFilter = $('#status-filter');
            const $applyFilters = $('#apply-filters');
            const $resetFilters = $('#reset-filters');
            
            // Bind search events
            $applyFilters.on('click', this.searchProducts.bind(this));
            $resetFilters.on('click', this.resetProductFilters.bind(this));
            
            // Search on Enter key
            $searchInput.on('keypress', (e) => {
                if (e.which === 13) {
                    this.searchProducts();
                }
            });
        },

        // Initialize product selection functionality
        initProductSelection: function() {
            // Update selected count when checkboxes change
            $(document).on('change', '.apcig-product-checkbox', this.updateSelectedCount.bind(this));
            
            // Enable/disable continue button based on selection
            $(document).on('change', '.apcig-product-checkbox', this.updateContinueButton.bind(this));
        },

        // Initialize step navigation
        initStepNavigation: function() {
            // Step navigation buttons
            $(document).on('click', '#continue-to-step-2', () => this.goToStep(2));
            $(document).on('click', '#continue-to-step-3', () => this.goToStep(3));
            $(document).on('click', '#continue-to-step-4', () => this.goToStep(4));
            $(document).on('click', '#back-to-step-1', () => this.goToStep(1));
            $(document).on('click', '#back-to-step-2', () => this.goToStep(2));
            $(document).on('click', '#back-to-step-3', () => this.goToStep(3));
            
            // Generate preview button
            $(document).on('click', '#continue-to-step-3', this.generateContentPreview.bind(this));
            
            // Apply content button
            $(document).on('click', '#apply-content', this.applyGeneratedContent.bind(this));
        },

        // Search products with filters
        searchProducts: function() {
            const search = $('#product-search').val();
            const category = $('#category-filter').val();
            const status = $('#status-filter').val();
            
            console.log('APCIG: Searching products with filters:', {search, category, status});
            
            this.showLoading();
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_search_products',
                    search: search,
                    category: category,
                    status: status,
                    page: 1,
                    per_page: 50,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.updateProductsGrid(response.data.products);
                    } else {
                        this.showAlert('error', response.data.message || 'Search failed');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred during search');
                },
                complete: () => {
                    this.hideLoading();
                }
            });
        },

        // Reset product filters
        resetProductFilters: function() {
            $('#product-search').val('');
            $('#category-filter').val('');
            $('#status-filter').val('');
            
            // Reload all products
            this.searchProducts();
        },

        // Update products grid with search results
        updateProductsGrid: function(products) {
            const $grid = $('#products-grid');
            $grid.empty();
            
            if (products.length === 0) {
                $grid.html('<div class="apcig-no-products"><p>No products found matching your criteria.</p></div>');
                return;
            }
            
            products.forEach(product => {
                const productHtml = this.createProductCardHtml(product);
                $grid.append(productHtml);
            });
            
            // Update selected count
            this.updateSelectedCount();
        },

        // Create product card HTML
        createProductCardHtml: function(product) {
            const imageHtml = product.image_url ? 
                `<img src="${product.image_url}" alt="${product.name}">` :
                '<div class="apcig-no-image"><span class="dashicons dashicons-format-image"></span></div>';
            
            const skuHtml = product.sku ? 
                `<div class="apcig-product-sku"><small>SKU: ${product.sku}</small></div>` : '';
            
            return `
                <div class="apcig-product-card" data-product-id="${product.id}">
                    <div class="apcig-product-checkbox-wrapper">
                        <input type="checkbox" class="apcig-product-checkbox" value="${product.id}" id="product-${product.id}">
                        <label for="product-${product.id}"></label>
                    </div>
                    <div class="apcig-product-image">${imageHtml}</div>
                    <div class="apcig-product-info">
                        <h4 class="apcig-product-title">${product.name}</h4>
                        <div class="apcig-product-price">${product.price_html}</div>
                        ${skuHtml}
                        <div class="apcig-content-status">
                            <span class="apcig-status-badge ${product.has_short_description ? 'success' : 'missing'}">Short Desc</span>
                            <span class="apcig-status-badge ${product.has_description ? 'success' : 'missing'}">Long Desc</span>
                            <span class="apcig-status-badge ${product.has_tags ? 'success' : 'missing'}">Tags</span>
                        </div>
                    </div>
                </div>
            `;
        },

        // Update continue button state
        updateContinueButton: function() {
            const selectedCount = $('.apcig-product-checkbox:checked').length;
            $('#continue-to-step-2').prop('disabled', selectedCount === 0);
        },

        // Navigate to specific step
        goToStep: function(stepNumber) {
            // Update step progress
            $('.apcig-step').removeClass('active completed');
            $('.apcig-step-content').removeClass('active').hide();
            
            // Mark previous steps as completed
            for (let i = 1; i < stepNumber; i++) {
                $(`.apcig-step[data-step="${i}"]`).addClass('completed');
            }
            
            // Activate current step
            $(`.apcig-step[data-step="${stepNumber}"]`).addClass('active');
            $(`#step-${stepNumber}`).addClass('active').show();
        },

        // Generate content preview
        generateContentPreview: function() {
            const selectedProducts = this.getSelectedProducts();
            const contentTypes = $('input[name="content_types[]"]:checked').map(function() {
                return $(this).val();
            }).get();
            const provider = $('select[name="provider"]').val();
            const tone = $('select[name="tone"]').val();
            const language = $('select[name="language"]').val();
            const customPrompt = $('textarea[name="custom_prompt"]').val();
            
            if (selectedProducts.length === 0) {
                this.showAlert('error', 'Please select at least one product');
                return;
            }
            
            if (contentTypes.length === 0) {
                this.showAlert('error', 'Please select at least one content type');
                return;
            }
            
            console.log('APCIG: Generating content for all products:', {
                products: selectedProducts,
                contentTypes: contentTypes,
                provider: provider,
                tone: tone,
                language: language,
                customPrompt: customPrompt
            });
            
            // Store generation settings
            this.generationSettings = {
                provider: provider,
                tone: tone,
                language: language,
                customPrompt: customPrompt,
                contentTypes: contentTypes
            };
            
            // Initialize storage for generated content
            this.generatedContent = {};
            
            // Show loading spinner with progress
            const totalItems = selectedProducts.length * contentTypes.length;
            this.showGenerationProgress(totalItems);
            
            // Generate content for all products and all content types
            this.generateAllContent(selectedProducts, 0, contentTypes, () => {
                // All content generated, show preview
                this.displayContentPreview(selectedProducts, contentTypes);
                this.goToStep(3);
                this.hideGenerationProgress();
            });
        },
        
        // Show generation progress
        showGenerationProgress: function(totalItems) {
            const progressHTML = `
                <div class="apcig-generation-overlay" id="generation-overlay">
                    <div class="apcig-generation-modal">
                        <div class="apcig-spinner-large"></div>
                        <h3>Generating Content...</h3>
                        <p>Please wait while we generate content for your products</p>
                        <div class="apcig-progress">
                            <div class="apcig-progress-bar" id="generation-progress-bar" style="width: 0%">0%</div>
                        </div>
                        <p class="apcig-progress-text" id="generation-progress-text">Starting...</p>
                    </div>
                </div>
            `;
            $('body').append(progressHTML);
            this.generationProgress = {
                total: totalItems,
                completed: 0
            };
        },
        
        // Update generation progress
        updateGenerationProgress: function(message) {
            if (!this.generationProgress) return;
            
            this.generationProgress.completed++;
            const percentage = Math.round((this.generationProgress.completed / this.generationProgress.total) * 100);
            
            $('#generation-progress-bar').css('width', percentage + '%').text(percentage + '%');
            $('#generation-progress-text').text(message || `Processing ${this.generationProgress.completed} of ${this.generationProgress.total}...`);
        },
        
        // Hide generation progress
        hideGenerationProgress: function() {
            $('#generation-overlay').fadeOut(300, function() {
                $(this).remove();
            });
            this.generationProgress = null;
        },
        
        // Generate all content for all products
        generateAllContent: function(products, productIndex, contentTypes, callback) {
            if (productIndex >= products.length) {
                // All products processed
                callback();
                return;
            }
            
            const productId = products[productIndex];
            
            // Initialize storage for this product
            this.generatedContent[productId] = {};
            
            // Generate content for all types for this product
            this.generateContentForProduct(productId, contentTypes, 0, () => {
                // Move to next product
                this.generateAllContent(products, productIndex + 1, contentTypes, callback);
            });
        },
        
        // Generate content for a single product (all types)
        generateContentForProduct: function(productId, contentTypes, typeIndex, callback) {
            if (typeIndex >= contentTypes.length) {
                // All content types generated for this product
                callback();
                return;
            }
            
            const contentType = contentTypes[typeIndex];
            const settings = this.generationSettings;
            
            console.log(`APCIG: Generating ${contentType} for product ${productId}`);
            
            // Update progress message
            this.updateGenerationProgress(`Generating ${contentType} for product ${productId}...`);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_generate_content',
                    product_id: productId,
                    content_type: contentType,
                    tone: settings.tone,
                    provider: settings.provider,
                    language: settings.language,
                    custom_instructions: settings.customPrompt,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success && response.data.content) {
                        // Store the generated content
                        this.generatedContent[productId][contentType] = {
                            content: response.data.content,
                            word_count: response.data.word_count,
                            success: true
                        };
                        console.log(`APCIG: Generated ${contentType} for product ${productId} (${response.data.word_count} words)`);
                    } else {
                        // Store the error
                        this.generatedContent[productId][contentType] = {
                            success: false,
                            error: response.data?.message || 'Failed to generate content'
                        };
                        console.error(`APCIG: Failed to generate ${contentType} for product ${productId}`);
                    }
                    
                    // Generate next content type
                    this.generateContentForProduct(productId, contentTypes, typeIndex + 1, callback);
                },
                error: (xhr, status, error) => {
                    // Store the error
                    this.generatedContent[productId][contentType] = {
                        success: false,
                        error: 'Network error: ' + error
                    };
                    console.error(`APCIG: Network error generating ${contentType} for product ${productId}`);
                    
                    // Generate next content type
                    this.generateContentForProduct(productId, contentTypes, typeIndex + 1, callback);
                }
            });
        },

        // Display content preview
        displayContentPreview: function(selectedProducts, contentTypes) {
            const $container = $('#content-preview-container');
            
            // Count successful generations
            let totalGenerated = 0;
            let totalFailed = 0;
            
            selectedProducts.forEach(productId => {
                contentTypes.forEach(contentType => {
                    if (this.generatedContent[productId] && this.generatedContent[productId][contentType]) {
                        if (this.generatedContent[productId][contentType].success) {
                            totalGenerated++;
                        } else {
                            totalFailed++;
                        }
                    }
                });
            });
            
            // Get first product's content as sample
            const firstProductId = selectedProducts[0];
            const firstProductContent = this.generatedContent[firstProductId] || {};
            
            let previewHtml = `
                <div class="apcig-preview-summary">
                    <h4>Content Generation Complete</h4>
                    <p><strong>Products:</strong> ${selectedProducts.length}</p>
                    <p><strong>Content Types:</strong> ${contentTypes.join(', ')}</p>
                    <p><strong>Successfully Generated:</strong> ${totalGenerated}</p>
                    ${totalFailed > 0 ? `<p style="color: #d63638;"><strong>Failed:</strong> ${totalFailed}</p>` : ''}
                </div>
                <div class="apcig-preview-sample">
                    <h4>Sample Generated Content (Product ID: ${firstProductId})</h4>
            `;
            
            // Show samples for each content type
            contentTypes.forEach(contentType => {
                const contentData = firstProductContent[contentType];
                if (contentData && contentData.success) {
                    const label = contentType.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
                    previewHtml += `
                        <div class="apcig-preview-content" style="margin-bottom: 20px;">
                            <h5>${label}</h5>
                            <div class="apcig-generated-text" style="background: #f5f5f5; padding: 15px; border-radius: 4px;">
                                ${contentData.content}
                            </div>
                            <small style="color: #666;">Word count: ${contentData.word_count || 'N/A'}</small>
                        </div>
                    `;
                } else if (contentData) {
                    const label = contentType.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
                    previewHtml += `
                        <div class="apcig-preview-content" style="margin-bottom: 20px;">
                            <h5>${label}</h5>
                            <div style="color: #d63638; padding: 15px; background: #fef0f0; border-radius: 4px;">
                                Error: ${contentData.error}
                            </div>
                        </div>
                    `;
                }
            });
            
            previewHtml += `
                </div>
                <div class="apcig-preview-actions">
                    <button type="button" class="apcig-btn apcig-btn-secondary" id="regenerate-preview">
                        <span class="dashicons dashicons-update"></span>
                        Regenerate All Content
                    </button>
                </div>
            `;
            
            $container.html(previewHtml);
            
            // Bind regenerate button
            $('#regenerate-preview').off('click').on('click', () => {
                this.goToStep(2);
            });
        },

        // Apply generated content
        applyGeneratedContent: function() {
            // Check if we have generated content
            if (!this.generatedContent || Object.keys(this.generatedContent).length === 0) {
                this.showAlert('error', 'No generated content found. Please generate content first.');
                return;
            }
            
            const selectedProducts = this.getSelectedProducts();
            
            console.log('APCIG: Applying stored content to products:', {
                products: selectedProducts,
                generatedContent: this.generatedContent
            });
            
            // Show progress
            $('#apply-progress').show();
            $('#apply-results').hide();
            $('#apply-progress-bar').css('width', '0%');
            $('.apcig-apply-notice').hide();
            
            // Store results
            this.applyResults = {
                success: [],
                failed: []
            };
            
            // Process products one by one
            this.applyStoredContent(selectedProducts, 0);
        },

        // Apply stored content to products sequentially
        applyStoredContent: function(products, index) {
            if (index >= products.length) {
                // All products processed - show results
                this.showApplyResults();
                return;
            }
            
            const productId = products[index];
            const progress = ((index + 1) / products.length) * 100;
            
            $('#apply-progress-bar').css('width', progress + '%');
            $('#apply-progress-text').text(`Applying content to product ${index + 1} of ${products.length}...`);
            
            // Get the generated content for this product
            const productContent = this.generatedContent[productId];
            
            if (!productContent || Object.keys(productContent).length === 0) {
                this.applyResults.failed.push({
                    productId: productId,
                    contentType: 'all',
                    error: 'No generated content found for this product'
                });
                // Move to next product
                this.applyStoredContent(products, index + 1);
                return;
            }
            
            // Build content_data object with only successful generations
            const contentData = {};
            let hasContent = false;
            
            for (const contentType in productContent) {
                if (productContent[contentType].success && productContent[contentType].content) {
                    contentData[contentType] = {
                        success: true,
                        content: productContent[contentType].content
                    };
                    hasContent = true;
                }
            }
            
            if (!hasContent) {
                this.applyResults.failed.push({
                    productId: productId,
                    contentType: 'all',
                    error: 'No successful content generation for this product'
                });
                // Move to next product
                this.applyStoredContent(products, index + 1);
                return;
            }
            
            console.log(`APCIG: Applying content to product ${productId}:`, contentData);
            
            // Apply all content types at once
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_apply_content',
                    product_id: productId,
                    content_data: contentData,
                    backup_original: false,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    console.log(`APCIG: Apply response for product ${productId}:`, response);
                    
                    if (response.success) {
                        // Record success for each content type
                        for (const contentType in contentData) {
                            this.applyResults.success.push({
                                productId: productId,
                                contentType: contentType
                            });
                        }
                    } else {
                        // Record failure
                        this.applyResults.failed.push({
                            productId: productId,
                            contentType: 'all',
                            error: response.data?.message || 'Failed to apply content'
                        });
                    }
                    
                    // Move to next product
                    this.applyStoredContent(products, index + 1);
                },
                error: (xhr, status, error) => {
                    console.error(`APCIG: Apply error for product ${productId}:`, {xhr, status, error});
                    
                    // Record failure
                    this.applyResults.failed.push({
                        productId: productId,
                        contentType: 'all',
                        error: 'Network error: ' + error
                    });
                    
                    // Move to next product
                    this.applyStoredContent(products, index + 1);
                }
            });
        },

        
        // Show apply results
        showApplyResults: function() {
            $('#apply-progress').hide();
            
            const successCount = this.applyResults.success.length;
            const failedCount = this.applyResults.failed.length;
            const totalCount = successCount + failedCount;
            
            let resultsHtml = '';
            
            if (successCount > 0) {
                resultsHtml += `
                    <div class="apcig-alert apcig-alert-success" style="margin-bottom: 15px;">
                        <span class="dashicons dashicons-yes-alt"></span>
                        <span><strong>Success!</strong> Applied content to ${successCount} product${successCount > 1 ? 's' : ''}.</span>
                    </div>
                `;
            }
            
            if (failedCount > 0) {
                resultsHtml += `
                    <div class="apcig-alert apcig-alert-error" style="margin-bottom: 15px;">
                        <span class="dashicons dashicons-warning"></span>
                        <span><strong>Error!</strong> Failed to apply content to ${failedCount} product${failedCount > 1 ? 's' : ''}.</span>
                    </div>
                `;
                
                // Show details of failures
                resultsHtml += '<div class="apcig-error-details" style="margin-top: 10px;"><h4>Failed Items:</h4><ul>';
                this.applyResults.failed.forEach(item => {
                    resultsHtml += `<li>Product ID ${item.productId} - ${item.contentType}: ${item.error}</li>`;
                });
                resultsHtml += '</ul></div>';
            }
            
            $('#apply-results').html(resultsHtml).show();
            
            // Show appropriate alert at the top
            if (failedCount === 0) {
                this.showAlert('success', `Content successfully applied to all ${successCount} products!`);
            } else if (successCount === 0) {
                this.showAlert('error', `Failed to apply content to all ${failedCount} products. Please check the errors below.`);
            } else {
                this.showAlert('warning', `Partially completed: ${successCount} succeeded, ${failedCount} failed.`);
            }
        },

        // Reset settings to defaults
        resetSettings: function(e) {
            e.preventDefault();
            
            if (!confirm('Are you sure you want to reset all settings to their default values? This action cannot be undone.')) {
                return;
            }
            
            const $button = $(e.currentTarget);
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_reset_settings',
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showAlert('success', 'Settings reset to defaults successfully!');
                        // Reload the page to show default values
                        setTimeout(() => {
                            location.reload();
                        }, 1500);
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to reset settings');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred while resetting settings');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },

        // Export settings
        exportSettings: function(e) {
            e.preventDefault();
            
            const $button = $(e.currentTarget);
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_export_settings',
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        // Create and download the settings file
                        const dataStr = JSON.stringify(response.data.settings, null, 2);
                        const dataBlob = new Blob([dataStr], {type: 'application/json'});
                        const url = URL.createObjectURL(dataBlob);
                        
                        const link = document.createElement('a');
                        link.href = url;
                        link.download = `apcig-settings-${new Date().toISOString().split('T')[0]}.json`;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        URL.revokeObjectURL(url);
                        
                        this.showAlert('success', 'Settings exported successfully!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to export settings');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred while exporting settings');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },

        // Import settings
        importSettings: function(e) {
            e.preventDefault();
            
            // Create file input
            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.accept = '.json';
            fileInput.style.display = 'none';
            
            fileInput.onchange = (event) => {
                const file = event.target.files[0];
                if (!file) return;
                
                const reader = new FileReader();
                reader.onload = (e) => {
                    try {
                        const settings = JSON.parse(e.target.result);
                        this.processImportedSettings(settings);
                    } catch (error) {
                        this.showAlert('error', 'Invalid settings file format');
                    }
                };
                reader.readAsText(file);
            };
            
            document.body.appendChild(fileInput);
            fileInput.click();
            document.body.removeChild(fileInput);
        },

        // Process imported settings
        processImportedSettings: function(settings) {
            if (!confirm('Are you sure you want to import these settings? This will overwrite your current settings.')) {
                return;
            }
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_import_settings',
                    settings: settings,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showAlert('success', 'Settings imported successfully!');
                        // Reload the page to show imported values
                        setTimeout(() => {
                            location.reload();
                        }, 1500);
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to import settings');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred while importing settings');
                }
            });
        },

        // Initialize image generation functionality
        initImageGeneration: function() {
            // Handle image generation form submissions with higher priority
            // Use off() first to prevent duplicate bindings
            $(document).off('submit', '#image-generation-form').on('submit', '#image-generation-form', this.handleImageGenerationSubmit.bind(this));
            $(document).off('submit', '#image-enhancement-form').on('submit', '#image-enhancement-form', this.handleImageEnhancementSubmit.bind(this));
            $(document).off('submit', '#background-removal-form').on('submit', '#background-removal-form', this.handleBackgroundRemovalSubmit.bind(this));
            
            // Image actions
            $(document).on('click', '.apcig-apply-image', this.applyImageToProduct.bind(this));
            $(document).on('click', '.apcig-regenerate-image', this.regenerateImage.bind(this));
            $(document).on('click', '.apcig-download-image', this.downloadImage.bind(this));
        },
        
        // Initialize file upload areas with drag and drop
        initFileUploadAreas: function() {
            $('.apcig-upload-area').each(function() {
                const $area = $(this);
                const $input = $area.find('input[type="file"]');
                
                // Click to select files
                $area.on('click', function() {
                    $input.click();
                });
                
                // Drag and drop events
                $area.on('dragover', function(e) {
                    e.preventDefault();
                    $(this).addClass('dragover');
                });
                
                $area.on('dragleave', function(e) {
                    e.preventDefault();
                    $(this).removeClass('dragover');
                });
                
                $area.on('drop', function(e) {
                    e.preventDefault();
                    $(this).removeClass('dragover');
                    
                    const files = e.originalEvent.dataTransfer.files;
                    if (files.length > 0) {
                        $input[0].files = files;
                        APCIG.handleFileSelection($input, files);
                    }
                });
                
                // File selection change
                $input.on('change', function() {
                    const files = this.files;
                    if (files.length > 0) {
                        APCIG.handleFileSelection($(this), files);
                    }
                });
            });
        },
        
        // Handle file selection
        handleFileSelection: function($input, files) {
            const $uploadArea = $input.closest('.apcig-upload-area');
            const $placeholder = $uploadArea.find('.apcig-upload-placeholder');
            
            if (files.length === 1) {
                $placeholder.html(`
                    <span class="dashicons dashicons-yes-alt"></span>
                    <p>Selected: ${files[0].name}</p>
                    <small>Click to select different file</small>
                `);
            } else if (files.length > 1) {
                $placeholder.html(`
                    <span class="dashicons dashicons-yes-alt"></span>
                    <p>Selected ${files.length} files</p>
                    <small>Click to select different files</small>
                `);
            }
            
            $uploadArea.addClass('has-files');
        },
        
        // Initialize image upload area with drag & drop
        initImageUploadArea: function(areaSelector, inputSelector, previewSelector, submitButtonSelector) {
            const $area = $(areaSelector);
            const $input = $(inputSelector);
            const $preview = $(previewSelector);
            const $submitButton = $(submitButtonSelector);
            
            if ($area.length === 0) return;
            
            // Click to upload
            $area.on('click', function(e) {
                if (!$(e.target).closest('.apcig-image-preview-remove').length) {
                    $input.click();
                }
            });
            
            // File input change
            $input.on('change', function(e) {
                const files = e.target.files;
                if (files.length > 0) {
                    APCIG.displayImagePreviews(files, $preview, $submitButton);
                }
            });
            
            // Drag & drop
            $area.on('dragover', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).addClass('dragover');
            });
            
            $area.on('dragleave', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('dragover');
            });
            
            $area.on('drop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('dragover');
                
                const files = e.originalEvent.dataTransfer.files;
                if (files.length > 0) {
                    // Set files to input
                    $input[0].files = files;
                    APCIG.displayImagePreviews(files, $preview, $submitButton);
                }
            });
        },
        
        // Display image previews
        displayImagePreviews: function(files, $preview, $submitButton) {
            $preview.empty().show();
            $preview.prev('.apcig-upload-placeholder').hide();
            
            Array.from(files).forEach((file, index) => {
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const previewHtml = `
                            <div class="apcig-image-preview-item" data-index="${index}">
                                <img src="${e.target.result}" alt="${file.name}">
                                <button type="button" class="apcig-image-preview-remove" data-index="${index}">×</button>
                            </div>
                        `;
                        $preview.append(previewHtml);
                    };
                    reader.readAsDataURL(file);
                }
            });
            
            // Enable submit button
            $submitButton.prop('disabled', false);
            
            // Handle remove button
            $(document).off('click', '.apcig-image-preview-remove').on('click', '.apcig-image-preview-remove', function(e) {
                e.stopPropagation();
                $(this).closest('.apcig-image-preview-item').remove();
                
                // If no more images, hide preview and show placeholder
                if ($preview.find('.apcig-image-preview-item').length === 0) {
                    $preview.hide();
                    $preview.prev('.apcig-upload-placeholder').show();
                    $submitButton.prop('disabled', true);
                }
            });
        },
        
        // Handle image generation form submission
        handleImageGenerationSubmit: function(e) {
            e.preventDefault();
            const $form = $(e.currentTarget);
            const $button = $form.find('button[type="submit"]');
            
            // Validate form
            if (!this.validateImageGenerationForm($form)) {
                return;
            }
            
            // Get form data
            const formData = {
                product_id: $form.find('[name="product_id"]').val(),
                description: $form.find('[name="description"]').val(),
                style: $form.find('[name="style"]:checked').val(),
                size: $form.find('[name="size"]').val(),
                count: $form.find('[name="count"]').val(),
                provider: $form.find('[name="provider"]').val(),
                nonce: this.config.nonce
            };
            
            console.log('APCIG: Generating images with data:', formData);
            
            this.setButtonLoading($button, true);
            this.showImageGenerationProgress();
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_generate_image',
                    ...formData
                },
                success: (response) => {
                    if (response.success) {
                        this.displayGeneratedImages(response.data);
                        this.showAlert('success', 'Images generated successfully!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to generate images');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('APCIG: Image generation error:', {xhr, status, error});
                    this.showAlert('error', 'Network error occurred during image generation');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                    this.hideImageGenerationProgress();
                }
            });
        },
        
        // Handle image enhancement form submission
        handleImageEnhancementSubmit: function(e) {
            e.preventDefault();
            const $form = $(e.currentTarget);
            const $button = $form.find('button[type="submit"]');
            const $input = $form.find('#image-upload');
            
            if (!$input[0].files || $input[0].files.length === 0) {
                this.showAlert('error', 'Please select images to enhance');
                return;
            }
            
            const enhancements = [];
            $form.find('input[name="enhancements[]"]:checked').each(function() {
                enhancements.push($(this).val());
            });
            
            if (enhancements.length === 0) {
                this.showAlert('error', 'Please select at least one enhancement option');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'apcig_enhance_image');
            formData.append('nonce', this.config.nonce);
            formData.append('strength', $form.find('[name="strength"]').val());
            
            // Add selected files
            for (let i = 0; i < $input[0].files.length; i++) {
                formData.append('images[]', $input[0].files[i]);
            }
            
            // Add enhancements
            enhancements.forEach(enhancement => {
                formData.append('enhancements[]', enhancement);
            });
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: (response) => {
                    if (response.success) {
                        this.displayEnhancedImages(response.data);
                        this.showAlert('success', 'Images enhanced successfully!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to enhance images');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred during image enhancement');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },
        
        // Handle background removal form submission
        handleBackgroundRemovalSubmit: function(e) {
            e.preventDefault();
            const $form = $(e.currentTarget);
            const $button = $form.find('button[type="submit"]');
            const $input = $form.find('#bg-removal-upload');
            
            if (!$input[0].files || $input[0].files.length === 0) {
                this.showAlert('error', 'Please select images for background removal');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'apcig_remove_background');
            formData.append('nonce', this.config.nonce);
            formData.append('background', $form.find('[name="background"]:checked').val());
            
            // Add selected files
            for (let i = 0; i < $input[0].files.length; i++) {
                formData.append('images[]', $input[0].files[i]);
            }
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: (response) => {
                    if (response.success) {
                        this.displayProcessedImages(response.data, 'Background removed from');
                        this.showAlert('success', 'Background removed successfully!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to remove background');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred during background removal');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },
        
        // Validate image generation form
        validateImageGenerationForm: function($form) {
            const productId = $form.find('[name="product_id"]').val();
            const description = $form.find('[name="description"]').val();
            
            if (!productId) {
                this.showAlert('error', 'Please select a product');
                return false;
            }
            
            if (!description.trim()) {
                this.showAlert('error', 'Please enter an image description');
                $form.find('[name="description"]').focus();
                return false;
            }
            
            return true;
        },
        
        // Show image generation progress
        showImageGenerationProgress: function() {
            const $previewArea = $('#image-preview-area');
            $previewArea.html(`
                <div class="apcig-generation-progress">
                    <div class="apcig-spinner"></div>
                    <h4>Generating Images...</h4>
                    <p>Please wait while AI creates your images. This may take a few moments.</p>
                </div>
            `);
        },
        
        // Hide image generation progress
        hideImageGenerationProgress: function() {
            // Progress will be replaced by generated images
        },
        
        // Display generated images
        displayGeneratedImages: function(data) {
            console.log('Generated images:', data);
            const $previewArea = $('#image-preview-area');
            
            if (!data.images || data.images.length === 0) {
                $previewArea.html('<div class="apcig-error">No images were generated</div>');
                return;
            }
            
            // Save to history
            data.images.forEach(image => {
                this.saveToImageHistory({
                    url: image.url,
                    product_name: data.product_name || 'Product #' + data.product_id,
                    timestamp: new Date().toLocaleString()
                });
            });
            
            let imagesHtml = '<div class="apcig-images-grid">';
            
            data.images.forEach((image, index) => {
                imagesHtml += `
                    <div class="apcig-image-item" data-image-id="${image.attachment_id}">
                        <img src="${image.url}" alt="Generated product image" loading="lazy">
                        <div class="apcig-image-actions">
                            <button type="button" class="apcig-btn apcig-btn-sm apcig-btn-primary apcig-apply-image" 
                                    data-image-id="${image.attachment_id}" data-product-id="${data.product_id}">
                                <span class="dashicons dashicons-yes"></span>
                                Apply to Product
                            </button>
                            <button type="button" class="apcig-btn apcig-btn-sm apcig-btn-secondary apcig-download-image" 
                                    data-image-url="${image.url}">
                                <span class="dashicons dashicons-download"></span>
                                Download
                            </button>
                        </div>
                    </div>
                `;
            });
            
            imagesHtml += '</div>';
            $previewArea.html(imagesHtml);
        },
        
        // Display enhanced images
        displayEnhancedImages: function(data) {
            console.log('Enhanced images:', data);
            const $previewArea = $('#image-preview-area');
            
            if (!data.enhanced_images || data.enhanced_images.length === 0) {
                $previewArea.html('<div class="apcig-error">No images were enhanced</div>');
                return;
            }
            
            let imagesHtml = '<div class="apcig-images-grid">';
            
            data.enhanced_images.forEach((image, index) => {
                if (image.error) {
                    imagesHtml += `
                        <div class="apcig-image-item error">
                            <div class="apcig-error">Error: ${image.error}</div>
                        </div>
                    `;
                } else {
                    imagesHtml += `
                        <div class="apcig-image-item" data-image-id="${image.attachment_id}">
                            <img src="${image.url}" alt="Enhanced product image" loading="lazy">
                            <div class="apcig-image-actions">
                                <button type="button" class="apcig-btn apcig-btn-sm apcig-btn-primary apcig-apply-image" 
                                        data-image-id="${image.attachment_id}">
                                    <span class="dashicons dashicons-yes"></span>
                                    Apply to Product
                                </button>
                                <button type="button" class="apcig-btn apcig-btn-sm apcig-btn-secondary apcig-download-image" 
                                        data-image-url="${image.url}">
                                    <span class="dashicons dashicons-download"></span>
                                    Download
                                </button>
                            </div>
                        </div>
                    `;
                }
            });
            
            imagesHtml += '</div>';
            $previewArea.html(imagesHtml);
        },
        
        // Display processed images (for background removal)
        displayProcessedImages: function(data, actionText) {
            console.log('Processed images:', data);
            const $previewArea = $('#image-preview-area');
            
            if (!data.processed_images || data.processed_images.length === 0) {
                $previewArea.html('<div class="apcig-error">No images were processed</div>');
                return;
            }
            
            let imagesHtml = '<div class="apcig-images-grid">';
            
            data.processed_images.forEach((image, index) => {
                if (image.error) {
                    imagesHtml += `
                        <div class="apcig-image-item error">
                            <div class="apcig-error">Error: ${image.error}</div>
                        </div>
                    `;
                } else {
                    imagesHtml += `
                        <div class="apcig-image-item" data-image-id="${image.attachment_id}">
                            <img src="${image.url}" alt="${actionText} image" loading="lazy">
                            <div class="apcig-image-actions">
                                <button type="button" class="apcig-btn apcig-btn-sm apcig-btn-primary apcig-apply-image" 
                                        data-image-id="${image.attachment_id}">
                                    <span class="dashicons dashicons-yes"></span>
                                    Apply to Product
                                </button>
                                <button type="button" class="apcig-btn apcig-btn-sm apcig-btn-secondary apcig-download-image" 
                                        data-image-url="${image.url}">
                                    <span class="dashicons dashicons-download"></span>
                                    Download
                                </button>
                            </div>
                        </div>
                    `;
                }
            });
            
            imagesHtml += '</div>';
            $previewArea.html(imagesHtml);
        },
        
        // Apply image to product
        applyImageToProduct: function(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const imageId = $button.data('image-id');
            const productId = $button.data('product-id');
            
            if (!imageId || !productId) {
                this.showAlert('error', 'Missing image or product information');
                return;
            }
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_apply_image',
                    image_id: imageId,
                    product_id: productId,
                    set_as_featured: true,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showAlert('success', 'Image applied to product successfully!');
                        $button.text('Applied').prop('disabled', true);
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to apply image to product');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred while applying image');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },
        
        // Regenerate image
        regenerateImage: function(e) {
            e.preventDefault();
            const $form = $('#image-generation-form');
            if ($form.length) {
                this.handleImageGenerationSubmit({currentTarget: $form[0], preventDefault: function(){}});
            }
        },
        
        // Download image
        downloadImage: function(e) {
            e.preventDefault();
            const imageUrl = $(e.currentTarget).data('image-url');
            
            if (imageUrl) {
                const link = document.createElement('a');
                link.href = imageUrl;
                link.download = 'apcig-generated-image-' + Date.now() + '.png';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        },
        
        // Display generated content
        displayGeneratedContent: function(data) {
            console.log('Generated content:', data);
            
            const $container = $('#content-preview-container');
            if ($container.length === 0) return;
            
            // Store the generated content for later use
            if (!window.APCIG_GENERATED_CONTENT) {
                window.APCIG_GENERATED_CONTENT = {};
            }
            window.APCIG_GENERATED_CONTENT[data.product_id] = {
                content: data.content,
                content_type: data.content_type,
                provider: data.provider,
                word_count: data.word_count
            };
            
            // Display the content
            const contentHtml = `
                <div class="apcig-generated-content-preview">
                    <div class="apcig-preview-header">
                        <h4>Generated ${data.content_type.replace('_', ' ').toUpperCase()}</h4>
                        <div class="apcig-preview-meta">
                            <span class="apcig-meta-item">
                                <span class="dashicons dashicons-admin-users"></span>
                                Provider: ${data.provider}
                            </span>
                            <span class="apcig-meta-item">
                                <span class="dashicons dashicons-text"></span>
                                Words: ${data.word_count || 0}
                            </span>
                        </div>
                    </div>
                    <div class="apcig-preview-content">
                        <div class="apcig-content-display">${this.escapeHtml(data.content)}</div>
                    </div>
                    <div class="apcig-preview-actions">
                        <button type="button" class="apcig-btn apcig-btn-secondary" onclick="APCIG.regenerateContent(${data.product_id}, '${data.content_type}')">
                            <span class="dashicons dashicons-update"></span>
                            Regenerate
                        </button>
                        <button type="button" class="apcig-btn apcig-btn-primary" onclick="APCIG.applyContentToProduct(${data.product_id}, '${data.content_type}')">
                            <span class="dashicons dashicons-yes"></span>
                            Apply to Product
                        </button>
                    </div>
                </div>
            `;
            
            $container.html(contentHtml);
        },
        
        // Escape HTML for display
        escapeHtml: function(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML.replace(/\n/g, '<br>');
        },
        
        // Apply content to product
        applyContentToProduct: function(productId, contentType) {
            if (!window.APCIG_GENERATED_CONTENT || !window.APCIG_GENERATED_CONTENT[productId]) {
                this.showAlert('error', 'No generated content found. Please generate content first.');
                return;
            }
            
            const contentData = window.APCIG_GENERATED_CONTENT[productId];
            
            if (!confirm('Are you sure you want to apply this content to the product? This will replace the existing content.')) {
                return;
            }
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_apply_content',
                    product_id: productId,
                    content_type: contentType,
                    content: contentData.content,
                    backup_original: true,
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showAlert('success', 'Content applied successfully to product!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to apply content');
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred while applying content');
                }
            });
        },
        
        // Regenerate content
        regenerateContent: function(productId, contentType) {
            // Trigger content generation again
            const $form = $('#content-generation-form');
            if ($form.length > 0) {
                $form.find('[name="product_id"]').val(productId);
                $form.find('[name="content_type"]').val(contentType);
                $form.submit();
            }
        },

        displayEnhancedImage: function(data) {
            console.log('Enhanced image:', data);
        },

        // Start bulk processing
        startBulkProcessing: function(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const selectedProducts = this.getSelectedProducts();
            
            if (selectedProducts.length === 0) {
                this.showAlert('error', 'Please select at least one product');
                return;
            }
            
            // Get form data
            const bulkAction = $('input[name="bulk_action"]:checked').val();
            const contentTypes = $('input[name="content_types[]"]:checked').map(function() {
                return $(this).val();
            }).get();
            const provider = $('select[name="provider"]').val();
            const tone = $('select[name="tone"]').val();
            const batchSize = $('select[name="batch_size"]').val() || 10;
            const backupOriginal = $('input[name="backup_original"]').is(':checked');
            const validateContent = $('input[name="validate_content"]').is(':checked');
            const skipExisting = $('input[name="skip_existing"]').is(':checked');
            const autoApply = $('input[name="auto_apply"]').is(':checked');
            
            console.log('APCIG: Starting bulk processing:', {
                action: bulkAction,
                products: selectedProducts,
                contentTypes: contentTypes,
                provider: provider,
                tone: tone,
                batchSize: batchSize
            });
            
            this.setButtonLoading($button, true);
            
            // Show progress card
            $('#progress-card').show();
            $('.apcig-bulk-setup').hide();
            
            // Start the bulk process
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'apcig_bulk_process',
                    action_type: bulkAction,
                    product_ids: selectedProducts,
                    settings: {
                        content_types: contentTypes,
                        provider: provider,
                        tone: tone,
                        batch_size: batchSize,
                        backup_original: backupOriginal,
                        validate_content: validateContent,
                        skip_existing: skipExisting,
                        auto_apply: autoApply
                    },
                    nonce: this.config.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showAlert('success', 'Bulk processing started successfully!');
                        this.trackBulkProgress(response.data.batch_id);
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to start bulk processing');
                        $('#progress-card').hide();
                        $('.apcig-bulk-setup').show();
                    }
                },
                error: () => {
                    this.showAlert('error', 'Network error occurred while starting bulk processing');
                    $('#progress-card').hide();
                    $('.apcig-bulk-setup').show();
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },

        // Track bulk processing progress
        trackBulkProgress: function(batchId) {
            const checkProgress = () => {
                $.ajax({
                    url: this.config.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'apcig_get_bulk_status',
                        batch_id: batchId,
                        nonce: this.config.nonce
                    },
                    success: (response) => {
                        if (response.success) {
                            const status = response.data;
                            this.updateBulkProgress(status);
                            
                            if (status.status === 'completed' || status.status === 'failed') {
                                this.showBulkResults(status);
                            } else if (status.status === 'processing') {
                                setTimeout(checkProgress, 2000); // Check again in 2 seconds
                            }
                        }
                    },
                    error: () => {
                        console.error('Failed to check bulk processing status');
                        setTimeout(checkProgress, 5000); // Retry in 5 seconds
                    }
                });
            };
            
            checkProgress();
        },

        // Update bulk processing progress display
        updateBulkProgress: function(status) {
            const progress = (status.completed / status.total) * 100;
            $('#batch-progress-fill').css('width', progress + '%');
            $('#batch-progress-text').text(`${status.completed} of ${status.total} products processed`);
            
            // Add log entry if there's a current item
            if (status.current_item) {
                const logEntry = `<div class="apcig-log-entry">Processing: ${status.current_item}</div>`;
                $('#processing-log').append(logEntry);
                $('#processing-log').scrollTop($('#processing-log')[0].scrollHeight);
            }
        },

        // Show bulk processing results
        showBulkResults: function(status) {
            $('#progress-card').hide();
            $('#results-summary').show();
            
            $('#successful-count').text(status.successful || 0);
            $('#failed-count').text(status.failed || 0);
            $('#skipped-count').text(status.skipped || 0);
            $('#total-time').text(status.total_time || '0s');
            
            if (status.status === 'completed') {
                this.showAlert('success', 'Bulk processing completed successfully!');
            } else {
                this.showAlert('warning', 'Bulk processing completed with some errors');
            }
        },

        startBulkProcess: function($button, type, products) {
            console.log('Starting bulk process:', type, products);
        },

        pauseBulkProcess: function() {
            console.log('Pausing bulk process');
        },

        stopBulkProcess: function() {
            console.log('Stopping bulk process');
        },

        cancelProcess: function() {
            console.log('Cancelling process');
        },


        
        // Handle background type change
        handleBackgroundTypeChange: function(e) {
            const value = $(e.currentTarget).val();
            if (value === 'custom') {
                $('#custom-color-picker').show();
            } else {
                $('#custom-color-picker').hide();
            }
        },
        
        // Handle image enhancement form submission
        handleImageEnhancementSubmit: function(e) {
            e.preventDefault();
            const $form = $(e.currentTarget);
            const $button = $form.find('button[type="submit"]');
            
            const formData = new FormData($form[0]);
            formData.append('action', 'apcig_enhance_image');
            formData.append('nonce', this.config.nonce);
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                timeout: 180000,
                success: (response) => {
                    if (response.success) {
                        this.displayEnhancedImages(response.data);
                        this.showAlert('success', 'Images enhanced successfully!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to enhance images');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Image enhancement error:', {xhr, status, error});
                    this.showAlert('error', 'Network error occurred. Please try again.');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },
        
        // Handle background removal form submission
        handleBackgroundRemovalSubmit: function(e) {
            e.preventDefault();
            const $form = $(e.currentTarget);
            const $button = $form.find('button[type="submit"]');
            
            const formData = new FormData($form[0]);
            formData.append('action', 'apcig_remove_background');
            formData.append('nonce', this.config.nonce);
            
            this.setButtonLoading($button, true);
            
            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                timeout: 180000,
                success: (response) => {
                    if (response.success) {
                        this.displayBackgroundRemovedImages(response.data);
                        this.showAlert('success', 'Backgrounds removed successfully!');
                    } else {
                        this.showAlert('error', response.data.message || 'Failed to remove backgrounds');
                    }
                },
                error: (xhr, status, error) => {
                    console.error('Background removal error:', {xhr, status, error});
                    this.showAlert('error', 'Network error occurred. Please try again.');
                },
                complete: () => {
                    this.setButtonLoading($button, false);
                }
            });
        },
        
        // Display enhanced images
        displayEnhancedImages: function(data) {
            const $preview = $('#enhanced-images-preview');
            const $grid = $('#enhanced-images-grid');
            
            $grid.empty();
            $preview.show();
            
            if (data.enhanced_images && data.enhanced_images.length > 0) {
                data.enhanced_images.forEach(image => {
                    const imageHtml = `
                        <div class="apcig-image-item">
                            <img src="${image.url}" alt="Enhanced Image">
                            <div class="apcig-image-actions">
                                <button type="button" class="apcig-btn apcig-btn-sm apcig-btn-secondary" onclick="window.open('${image.url}', '_blank')">
                                    <span class="dashicons dashicons-download"></span> Download
                                </button>
                            </div>
                        </div>
                    `;
                    $grid.append(imageHtml);
                });
            }
        },
        
        // Display background removed images
        displayBackgroundRemovedImages: function(data) {
            const $preview = $('#bg-removed-images-preview');
            const $grid = $('#bg-removed-images-grid');
            
            $grid.empty();
            $preview.show();
            
            if (data.processed_images && data.processed_images.length > 0) {
                data.processed_images.forEach(image => {
                    if (image.url) {
                        const imageHtml = `
                            <div class="apcig-image-item">
                                <img src="${image.url}" alt="Processed Image">
                                <div class="apcig-image-actions">
                                    <button type="button" class="apcig-btn apcig-btn-sm apcig-btn-secondary" onclick="window.open('${image.url}', '_blank')">
                                        <span class="dashicons dashicons-download"></span> Download
                                    </button>
                                </div>
                            </div>
                        `;
                        $grid.append(imageHtml);
                    }
                });
            }
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        APCIG.init();
    });

    // Make APCIG globally available
    window.APCIG = APCIG;

})(jQuery);