/**
 * Image Loader Utility - Enhanced with Carousel Handler
 * Handles dynamic image path resolution and fallback loading
 * Fixes broken image paths automatically
 * Special support for: carousels, sliders, galleries, dynamically added images
 * Carousel images without extensions are routed to carousel_image_handler.php
 */

(function() {
    'use strict';
    
    // Image directories to search
    const imageDirs = [
        'sport-pics/',
        'sport-pics/soccer/',
        'sport-pics/tennis/',
        'sport-pics/rugby/',
        'pics/',
        'pics_ecom/',
        'uploads/'
    ];
    
    // Base URL for handlers
    const baseUrl = window.location.protocol + '//' + window.location.host + '/emporio/';
    const carouselHandlerUrl = baseUrl + 'carousel_image_handler.php';
    
    /**
     * Fix image paths by trying multiple locations
     * @param {HTMLImageElement} img - The image element
     */
    function fixImagePath(img) {
        const originalSrc = img.dataset.originalSrc || img.src;
        img.dataset.originalSrc = originalSrc;
        
        // Extract just the filename
        let filename = originalSrc.split('/').pop().split('?')[0];
        
        if (!filename) return;
        
        console.log(`[Image Loader] Attempting to fix: ${filename}`);
        
        // Try each directory
        for (let dir of imageDirs) {
            const newSrc = dir + filename;
            
            // Create a test image to check if this path works
            const testImg = new Image();
            testImg.onload = function() {
                // Found working path, update original image
                img.src = newSrc;
                img.style.display = 'block';
                console.log('✓ Image loaded: ' + newSrc);
            };
            testImg.onerror = null;
            
            // Start test
            testImg.src = newSrc;
        }
        
        // Also try the image handler as fallback
        setTimeout(() => {
            if (!img.complete || img.naturalHeight === 0) {
                console.log(`[Image Loader] Using image_handler_v3.php for: ${filename}`);
                img.src = 'image_handler_v3.php?img=' + encodeURIComponent(filename);
            }
        }, 1000);
    }
    
    /**
     * Handle carousel images without extensions using carousel_image_handler
     * @param {HTMLImageElement} img - The image element
     * @param {string} imageId - The image ID (like "ai1" or "ai1-xxx")
     */
    function handleCarouselImage(img, imageId) {
        // Fetch the actual image path from carousel handler
        fetch(carouselHandlerUrl + '?action=find&id=' + encodeURIComponent(imageId))
            .then(response => response.json())
            .then(data => {
                if (data.success && data.path) {
                    console.log(`[Carousel] Found image: ${data.path}`);
                    img.src = data.path;
                    img.style.display = 'block';
                } else {
                    console.warn(`[Carousel] Image not found: ${imageId}`);
                    // Fallback to image_handler
                    img.src = 'image_handler_v3.php?img=' + encodeURIComponent(imageId);
                }
            })
            .catch(err => {
                console.error(`[Carousel] Handler error: ${err}`);
                // Fallback to image_handler
                img.src = 'image_handler_v3.php?img=' + encodeURIComponent(imageId);
            });
    }
    
    /**
     * Initialize image loader on page load
     */
    function initImageLoader() {
        // Get all images on the page
        const images = document.querySelectorAll('img');
        
        images.forEach(img => {
            // Check if image is broken
            if (!img.complete || img.naturalHeight === 0) {
                const src = img.src || '';
                console.warn('[Image Loader] Broken image detected: ' + src);
                
                // Check if this is a carousel/slider image without extension
                // Pattern: pics/xxx, pics_ecom/xxx, uploads/xxx (no file extension)
                const isCarouselImage = /\b(pics|pics_ecom|sport-pics|uploads)\/[^.\/\?]+$/.test(src);
                
                if (isCarouselImage) {
                    // Extract just the ID part (e.g., "ai1" from "pics/ai1")
                    const parts = src.split('/');
                    const imageId = parts[parts.length - 1];
                    console.log('[Carousel] Detected carousel image: ' + imageId);
                    handleCarouselImage(img, imageId);
                } else {
                    // Regular image path fixing
                    fixImagePath(img);
                }
            }
            
            // Also add error handler for future broken images
            img.addEventListener('error', function() {
                const src = this.src || '';
                console.warn('[Image Loader] Image load error: ' + src);
                
                // Check if this is a carousel image
                const isCarouselImage = /\b(pics|pics_ecom|sport-pics|uploads)\/[^.\/\?]+$/.test(src);
                
                if (isCarouselImage) {
                    const parts = src.split('/');
                    const imageId = parts[parts.length - 1];
                    console.log('[Carousel] Error loading carousel image: ' + imageId);
                    handleCarouselImage(this, imageId);
                } else {
                    fixImagePath(this);
                }
            });
        });
    }
    
    /**
     * Watch for dynamically added images (carousels, AJAX-loaded content, etc.)
     */
    function setupMutationObserver() {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.addedNodes.length) {
                    mutation.addedNodes.forEach(function(node) {
                        if (node.nodeType === 1) { // Element node
                            // Check if this is an img tag
                            if (node.tagName === 'IMG') {
                                console.log('[Image Loader] Detected new image: ' + node.src);
                                
                                // Add error handler with carousel detection
                                node.addEventListener('error', function() {
                                    const src = this.src || '';
                                    console.warn('[Image Loader] Dynamic image error: ' + src);
                                    
                                    const isCarouselImage = /\b(pics|pics_ecom|sport-pics|uploads)\/[^.\/\?]+$/.test(src);
                                    if (isCarouselImage) {
                                        const parts = src.split('/');
                                        const imageId = parts[parts.length - 1];
                                        handleCarouselImage(this, imageId);
                                    } else {
                                        fixImagePath(this);
                                    }
                                });
                                
                                // Check if it's already broken
                                if (!node.complete || node.naturalHeight === 0) {
                                    const src = node.src || '';
                                    const isCarouselImage = /\b(pics|pics_ecom|sport-pics|uploads)\/[^.\/\?]+$/.test(src);
                                    if (isCarouselImage) {
                                        const parts = src.split('/');
                                        const imageId = parts[parts.length - 1];
                                        handleCarouselImage(node, imageId);
                                    } else {
                                        fixImagePath(node);
                                    }
                                }
                            }
                            
                            // Also check for images within this node
                            const childImages = node.querySelectorAll('img');
                            childImages.forEach(img => {
                                console.log('[Image Loader] Detected image in new content: ' + img.src);
                                
                                img.addEventListener('error', function() {
                                    const src = this.src || '';
                                    console.warn('[Image Loader] Image error: ' + src);
                                    
                                    const isCarouselImage = /\b(pics|pics_ecom|sport-pics|uploads)\/[^.\/\?]+$/.test(src);
                                    if (isCarouselImage) {
                                        const parts = src.split('/');
                                        const imageId = parts[parts.length - 1];
                                        handleCarouselImage(this, imageId);
                                    } else {
                                        fixImagePath(this);
                                    }
                                });
                                
                                if (!img.complete || img.naturalHeight === 0) {
                                    const src = img.src || '';
                                    const isCarouselImage = /\b(pics|pics_ecom|sport-pics|uploads)\/[^.\/\?]+$/.test(src);
                                    if (isCarouselImage) {
                                        const parts = src.split('/');
                                        const imageId = parts[parts.length - 1];
                                        handleCarouselImage(img, imageId);
                                    } else {
                                        fixImagePath(img);
                                    }
                                }
                            });
                        }
                    });
                }
            });
        });
        
        // Watch entire body for changes
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }
    
    /**
     * Setup image interception for common patterns
     */
    function setupImageInterception() {
        // Find all elements with common image attributes
        // This catches: img tags, picture elements, divs with background images, etc.
        const imageElements = document.querySelectorAll(
            'img, [data-src], [data-image], .carousel-item, .slide, .slider-image, ' +
            '[style*="background-image"], [style*="backgroundImage"]'
        );
        
        imageElements.forEach(element => {
            // Handle img tags
            if (element.tagName === 'IMG') {
                let src = element.src || element.getAttribute('data-src');
                if (src && handleImageSrc(src)) {
                    element.src = processImagePath(src);
                }
            }
            
            // Handle data-src (lazy loading)
            const dataSrc = element.getAttribute('data-src');
            if (dataSrc && handleImageSrc(dataSrc)) {
                element.setAttribute('data-src', processImagePath(dataSrc));
                // Also set as src if not already set
                if (!element.src) {
                    element.src = processImagePath(dataSrc);
                }
            }
            
            // Handle data-image
            const dataImg = element.getAttribute('data-image');
            if (dataImg && handleImageSrc(dataImg)) {
                element.setAttribute('data-image', processImagePath(dataImg));
            }
            
            // Handle carousel/slider classes
            if (element.classList.contains('carousel-item') || 
                element.classList.contains('slide') ||
                element.classList.contains('slider-image')) {
                const src = element.src || element.getAttribute('data-src');
                if (src && handleImageSrc(src)) {
                    if (element.src) element.src = processImagePath(src);
                    element.setAttribute('data-src', processImagePath(src));
                }
            }

            // Handle inline background-image or computed background-image
            try {
                let bg = '';
                if (element.style && element.style.backgroundImage && element.style.backgroundImage !== 'none') {
                    bg = element.style.backgroundImage;
                } else {
                    const comp = window.getComputedStyle(element);
                    if (comp && comp.backgroundImage && comp.backgroundImage !== 'none') bg = comp.backgroundImage;
                }

                if (bg) {
                    const m = bg.match(/url\(["']?(.*?)["']?\)/);
                    if (m && m[1]) {
                        const url = m[1];
                        if (handleImageSrc(url)) {
                            const newUrl = processImagePath(url);
                            element.style.backgroundImage = 'url("' + newUrl + '")';
                        }
                    }
                }
            } catch (e) {
                // ignore
            }
        });
    }
    
    /**
     * Check if this looks like an image path that needs processing
     */
    function handleImageSrc(src) {
        if (!src) return false;
        // If it's just a filename or missing directory, it needs processing
        return !src.includes('/') || src.split('/').pop().includes('.');
    }
    
    /**
     * Process image path and return corrected version
     */
    function processImagePath(src) {
        if (!src) return src;
        
        const filename = src.split('/').pop().split('?')[0];
        
        // If no directory prefix, try image handler first
        if (!src.includes('/') || src.split('/').length === 1) {
            return 'image_handler_v3.php?img=' + encodeURIComponent(filename);
        }
        
        return src;
    }
    
    /**
     * Periodically check for broken carousel images
     */
    function setupCarouselWatcher() {
        setInterval(() => {
            // Check carousel, slider, and gallery images
            const carouselSelectors = [
                '.carousel img',
                '.carousel-item img',
                '.slider img',
                '.slide img',
                '[class*="carousel"] img',
                '[class*="slider"] img',
                '.gallery img'
            ];
            
            carouselSelectors.forEach(selector => {
                try {
                    const images = document.querySelectorAll(selector);
                    images.forEach(img => {
                        // If image failed to load, try to fix it
                        if (!img.complete || img.naturalHeight === 0) {
                            const src = img.src || img.getAttribute('data-src');
                            if (src && !src.includes('image_handler')) {
                                console.log('[Image Loader] Fixing carousel image: ' + src);
                                fixImagePath(img);
                            }
                        }
                    });
                } catch (e) {
                    // Silently catch selector errors
                }
            });
        }, 500); // Check every 500ms for carousel images
    }
    
    /**
     * Initialize everything when page loads
     */
    function initializeImageLoader() {
        console.log('[Image Loader] Initializing...');
        
        // Setup interception first
        setupImageInterception();
        
        // Setup mutation observer for dynamic content
        setupMutationObserver();
        
        // Setup carousel watcher
        setupCarouselWatcher();
        
        // Initial scan
        initImageLoader();
    }
    
    // Run on document ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeImageLoader);
    } else {
        initializeImageLoader();
    }
    
    // Also run on page load for images added late
    window.addEventListener('load', function() {
        console.log('[Image Loader] Page fully loaded, running final check...');
        initImageLoader();
    });
    
    // Export for external use
    window.ImageLoader = {
        fixImage: fixImagePath,
        processPath: processImagePath,
        reinitialize: initializeImageLoader
    };
    
})();
