// smart_image.js - Smart image handler untuk semua environment
class SmartImageHandler {
    constructor() {
        this.currentBaseUrl = window.location.origin + window.location.pathname.split('/').slice(0, -1).join('/');
        this.fallbackBaseUrl = this.detectFallbackBaseUrl();
        this.init();
    }

    init() {
        console.log('🤖 SmartImageHandler initialized');
        this.fixAllImages();
        this.observeChanges();
    }

    detectFallbackBaseUrl() {
        // Coba detect base URL dari current location
        const protocol = window.location.protocol + '//';
        const host = window.location.host;
        const path = window.location.pathname;
        
        // Remove '/penguji/' atau '/admin/' dari path
        let basePath = path.replace(/\/\w+\//, '/');
        basePath = basePath.substring(0, basePath.lastIndexOf('/'));
        
        return protocol + host + basePath;
    }

    fixAllImages() {
        const images = document.querySelectorAll('img');
        console.log(`🔍 Checking ${images.length} images...`);
        
        images.forEach(img => {
            this.makeImageUniversal(img);
        });
    }

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

        // Jika sudah URL lengkap, biarkan
        if (src.startsWith('http') && this.isAccessibleUrl(src)) {
            return;
        }

        const filename = this.extractFilename(src);
        if (!filename) return;

        // Coba berbagai base URL
        const possibleUrls = [
            `${this.currentBaseUrl}/uploads/images/${filename}`,
            `${this.fallbackBaseUrl}/uploads/images/${filename}`,
            `${window.location.origin}/uploads/images/${filename}`,
            `/uploads/images/${filename}`,
            `../uploads/images/${filename}`
        ];

        this.tryImageUrls(img, possibleUrls, filename);
    }

    tryImageUrls(img, urls, filename) {
        let currentAttempt = 0;

        const tryNext = () => {
            if (currentAttempt >= urls.length) {
                // Semua URL gagal
                this.showImageError(img, filename);
                return;
            }

            const testUrl = urls[currentAttempt];
            console.log(`🔄 Attempt ${currentAttempt + 1}: ${testUrl}`);

            const testImage = new Image();
            testImage.onload = () => {
                // URL ini bekerja, gunakan untuk img utama
                img.src = testUrl;
                img.onload = () => {
                    console.log(`✅ Image loaded: ${filename}`);
                    img.style.border = '2px solid #27ae60';
                };
            };
            
            testImage.onerror = () => {
                currentAttempt++;
                tryNext();
            };
            
            testImage.src = testUrl;
        };

        tryNext();
    }

    extractFilename(path) {
        // Extract filename dari berbagai pattern
        const patterns = [
            /[^\/]+\.(jpg|jpeg|png|gif|webp)$/i, // Basic filename
            /uploads\/images\/([^\/]+\.(jpg|jpeg|png|gif|webp))$/i, // Dengan path uploads
            /\/admin\/uploads\/images\/([^\/]+)/i // Dari admin
        ];

        for (let pattern of patterns) {
            const match = path.match(pattern);
            if (match) {
                return match[0].includes('/') ? match[0].split('/').pop() : match[0];
            }
        }

        return path.split('/').pop(); // Fallback
    }

    isAccessibleUrl(url) {
        // Cek jika URL menggunakan host yang sama dengan current page
        try {
            const urlObj = new URL(url);
            const currentHost = window.location.host;
            return urlObj.host === currentHost;
        } catch {
            return false;
        }
    }

    showImageError(img, filename) {
        console.error(`❌ All image attempts failed for: ${filename}`);
        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;
        `;
    }

    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.makeImageUniversal(node);
                            }
                            const images = node.querySelectorAll?.('img') || [];
                            images.forEach(img => this.makeImageUniversal(img));
                        }
                    });
                }
            });
        });

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

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