// image_fixer.js - Client-side image fixer
class ImageFixer {
    constructor() {
        this.baseUrl = window.location.origin + '/soca-osce-system';
        this.init();
    }

    init() {
        console.log('🖼️ ImageFixer initialized');
        this.fixAllImages();
        this.observeChanges();
        this.setupGlobalHandler();
    }

    fixAllImages() {
        const images = document.querySelectorAll('img');
        console.log(`🔍 Found ${images.length} images to check`);
        
        let fixedCount = 0;
        
        images.forEach(img => {
            if (this.fixSingleImage(img)) {
                fixedCount++;
            }
        });
        
        console.log(`✅ Fixed ${fixedCount} images`);
    }

    fixSingleImage(img) {
        const src = img.getAttribute('src');
        if (!src) return false;

        // Skip jika sudah URL lengkap
        if (src.startsWith('http') || src.startsWith('data:') || src.startsWith('//')) {
            return false;
        }

        let newSrc = src;
        let fixed = false;

        // CASE 1: Path seperti "../uploads/images/xxx.jpg"
        if (src.includes('../uploads/images/')) {
            newSrc = this.baseUrl + '/uploads/images/' + this.getFilename(src);
            fixed = true;
        }
        // CASE 2: Path dari admin "../admin/uploads/images/xxx.jpg"  
        else if (src.includes('/admin/uploads/images/')) {
            newSrc = this.baseUrl + '/uploads/images/' + this.getFilename(src);
            fixed = true;
        }
        // CASE 3: Hanya filename "xxx.jpg"
        else if (!src.includes('/') && src.includes('.')) {
            newSrc = this.baseUrl + '/uploads/images/' + src;
            fixed = true;
        }
        // CASE 4: Path relatif "uploads/images/xxx.jpg"
        else if (src.startsWith('uploads/images/')) {
            newSrc = this.baseUrl + '/' + src;
            fixed = true;
        }

        if (fixed && newSrc !== src) {
            console.log('🔄 Fixing image:', { from: src, to: newSrc });
            img.setAttribute('data-original-src', src);
            img.src = newSrc;
            
            // Add loading state
            img.style.opacity = '0.7';
            img.style.transition = 'opacity 0.3s';
            
            img.onload = () => {
                img.style.opacity = '1';
                img.style.border = '2px solid #27ae60';
                console.log('✅ Image loaded:', newSrc);
            };
            
            img.onerror = () => {
                console.error('❌ Failed to load:', newSrc);
                this.showFallback(img, src);
            };
            
            return true;
        }
        
        return false;
    }

    getFilename(path) {
        return path.split('/').pop();
    }

    showFallback(img, originalSrc) {
        const filename = this.getFilename(originalSrc);
        
        // Try alternative URLs
        const alternatives = [
            `${this.baseUrl}/uploads/images/${filename}`,
            `${window.location.origin}/uploads/images/${filename}`,
            `/soca-osce-system/uploads/images/${filename}`,
            `/uploads/images/${filename}`
        ];
        
        let currentAttempt = 0;
        
        const tryNext = () => {
            if (currentAttempt < alternatives.length) {
                console.log(`🔄 Attempt ${currentAttempt + 1}:`, alternatives[currentAttempt]);
                img.src = alternatives[currentAttempt];
                currentAttempt++;
            } else {
                // All attempts failed
                img.alt = `Gambar tidak dapat dimuat: ${filename}`;
                img.style.cssText = `
                    border: 2px solid #e74c3c !important;
                    background: #f8d7da !important;
                    padding: 20px !important;
                    min-height: 80px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #721c24;
                    font-weight: bold;
                    font-size: 14px;
                `;
                img.outerHTML = `<div style="border: 2px solid #e74c3c; background: #f8d7da; padding: 20px; text-align: center;">
                    <strong>❌ Gambar Tidak Dapat Dimuat</strong><br>
                    <small>File: ${filename}</small><br>
                    <small>URL: ${originalSrc}</small>
                </div>`;
            }
        };
        
        img.onerror = tryNext;
        tryNext();
    }

    observeChanges() {
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach((node) => {
                        if (node.nodeType === 1) {
                            if (node.tagName === 'IMG') {
                                this.fixSingleImage(node);
                            }
                            const images = node.querySelectorAll?.('img') || [];
                            images.forEach(img => this.fixSingleImage(img));
                        }
                    });
                }
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    setupGlobalHandler() {
        // Global error handler untuk images
        window.addEventListener('error', (e) => {
            if (e.target.tagName === 'IMG') {
                console.log('🌍 Global image error:', e.target.src);
            }
        }, true);
    }
}

// Auto-initialize
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        window.imageFixer = new ImageFixer();
    });
} else {
    window.imageFixer = new ImageFixer();
}

// Manual functions
window.fixAllImages = function() {
    if (window.imageFixer) {
        window.imageFixer.fixAllImages();
    }
};

window.debugImages = function() {
    const images = document.querySelectorAll('img');
    console.log('=== 🖼️ IMAGE DEBUG ===');
    images.forEach((img, index) => {
        console.log(`Image ${index + 1}:`, {
            src: img.src,
            currentSrc: img.currentSrc,
            complete: img.complete,
            naturalWidth: img.naturalWidth,
            naturalHeight: img.naturalHeight,
            alt: img.alt
        });
    });
};