/**
 * client-side processing for image alt tags
 * Version: 1.4.1-performance (2025-09-17)
 */
(function() {
    // Version identifier for debugging
    var SCRIPT_VERSION = '1.4.1-performance';
    
    // Track processed images to avoid duplicates
    var processedImages = new WeakSet();
    var isProcessing = false;
    var debugMode = window.location.search.includes('rank_debug=1');
    
    
    function log(message, data) {
        if (debugMode) {
            console.log('[Rank Alt Tags] ' + message, data || '');
        }
    }
    
    function scheduleProcessing(reason) {
        log('scheduleProcessing called', {reason: reason, isProcessing: isProcessing});
        
        if (isProcessing) {
            log('Already processing, skipping');
            return;
        }
        
        requestAnimationFrame(function() {
            processAltTags(reason);
        });
    }
    
    // Initial load events with minimal retry mechanism
    document.addEventListener('DOMContentLoaded', function() {
        scheduleProcessing('dom-ready');
        
        // Quick retry for images that might load shortly after DOM ready
        setTimeout(function() {
            scheduleProcessing('dom-ready-delayed');
        }, 100);
    });
    
    window.addEventListener('load', function() {
        scheduleProcessing('window-load');
        
        // Final quick retry - still within crawler window
        setTimeout(function() {
            scheduleProcessing('window-load-delayed');
        }, 300);
    });
    
    // Also try when images finish loading
    document.addEventListener('DOMContentLoaded', function() {
        var images = document.querySelectorAll('img');
        var loadedCount = 0;
        var totalImages = images.length;
        
        if (totalImages === 0) return;
        
        function checkAllLoaded() {
            loadedCount++;
            if (loadedCount === totalImages) {
                log('All images loaded, processing alt tags');
                scheduleProcessing('images-loaded');
            }
        }
        
        for (var i = 0; i < images.length; i++) {
            var img = images[i];
            if (img.complete) {
                checkAllLoaded();
            } else {
                img.addEventListener('load', checkAllLoaded);
                img.addEventListener('error', checkAllLoaded); // Count errors too
            }
        }
    });
    
    // Enhanced AJAX detection for infinite scroll
    if (window.jQuery) {
        jQuery(document).ajaxComplete(function(event, xhr, settings) {
            var url = settings.url || '';
            var data = settings.data || '';
            
            // Convert data to string if it's not already (handles objects, FormData, etc.)
            if (typeof data !== 'string') {
                if (data instanceof FormData) {
                    // FormData doesn't have a simple toString, check URL instead
                    data = url;
                } else if (typeof data === 'object' && data !== null) {
                    // Convert object to query string format
                    data = Object.keys(data).map(function(key) {
                        return key + '=' + encodeURIComponent(data[key]);
                    }).join('&');
                } else {
                    data = String(data);
                }
            }
            
            // Detect infinite scroll patterns
            if (url.includes('admin-ajax.php') && (
                data.includes('load_more') ||
                data.includes('infinite') ||
                data.includes('pagination') ||
                data.includes('next_page') ||
                data.includes('load-posts') ||
                // Common WordPress infinite scroll actions
                data.includes('action=load') ||
                data.includes('paged=') ||
                data.includes('offset=')
            )) {
                scheduleProcessing('ajax-content');
            }
        });
    }
    
    
    /**
     * Optimized processing with early exits and immediate scheduling
     */
    function processAltTags(reason) {
        log('processAltTags started', {reason: reason, isProcessing: isProcessing});
        
        if (isProcessing) {
            log('Already processing, exiting');
            return;
        }
        isProcessing = true;
        
        try {
            // Quick early exit - if no images without alt, exit immediately
            var quickCheck = document.querySelector('img:not([alt]), img[alt=""]');
            if (!quickCheck) {
                log('No images without alt found, exiting');
                return;
            }
            
            // Get all images without alt text or with empty alt
            var images = document.querySelectorAll('img:not([alt]), img[alt=""]');
            log('Found images without alt', {count: images.length});
            
            // Collect only truly new images
            var imageUrls = [];
            var imageMap = {}; // Map to track which elements correspond to which URLs
            var newImageCount = 0;
            var skippedCount = 0;
            
            for (var i = 0; i < images.length; i++) {
                var img = images[i];
                
                // Skip already processed images
                if (processedImages.has(img)) {
                    skippedCount++;
                    continue;
                }
                
                var src = img.getAttribute('src');
                if (src && src.trim()) {
                    // Check if image is actually visible and loaded
                    if (img.src && img.parentNode && img.complete) {
                        imageUrls.push(src);
                        newImageCount++;
                        
                        // Store reference to this element for this URL
                        if (!imageMap[src]) {
                            imageMap[src] = [];
                        }
                        imageMap[src].push(img);
                        
                        // Mark as processed to avoid duplicate processing
                        processedImages.add(img);
                    } else {
                        log('Skipping invisible/unloaded image', {src: src});
                    }
                }
            }
            
            log('Image processing stats', {
                total: images.length,
                newImages: newImageCount,
                skipped: skippedCount,
                urls: imageUrls.length
            });
            
            // Exit if no new images to process
            if (imageUrls.length === 0) {
                log('No new images to process, exiting');
                return;
            }
            
            log('Making AJAX request', {urls: imageUrls});
            
            // Single AJAX request for new images only
            fetch(rankAltTags.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_bulk_alt_tags&urls=' + encodeURIComponent(JSON.stringify(imageUrls)) +
                      '&post_id=' + rankAltTags.postId +
                      '&current_url=' + encodeURIComponent(window.location.href) +
                      '&trigger=' + encodeURIComponent(reason || 'unknown')
            })
            .then(function(response) {
                log('AJAX response received', {status: response.status});
                return response.json();
            })
            .then(function(data) {
                log('AJAX data parsed', {success: data.success, altTagsCount: Object.keys(data.alt_tags || {}).length});
                
                if (data.success) {
                    var appliedCount = 0;
                    // Apply alt tags to all matching images
                    Object.keys(data.alt_tags || {}).forEach(function(url) {
                        var altText = data.alt_tags[url];
                        
                        if (altText && imageMap[url]) {
                            // Apply to all elements with this URL
                            imageMap[url].forEach(function(img) {
                                // Double-check the image still exists and doesn't have alt
                                if (img.parentNode && (!img.hasAttribute('alt') || img.getAttribute('alt') === '')) {
                                    img.setAttribute('alt', altText);
                                    appliedCount++;
                                    log('Applied alt tag', {url: url, alt: altText});
                                }
                            });
                        }
                    });
                    log('Alt tags applied', {count: appliedCount});
                } else {
                    log('AJAX request failed', data);
                }
            })
            .catch(function(error) {
                console.error('Rank Alt Tags: Error in fetch:', error);
                log('AJAX error', error);
            });
            
        } finally {
            isProcessing = false;
        }
    }
    
    // No cleanup needed for requestAnimationFrame
})();