{{--
    Composant Image avec Lazy Loading
    
    Usage:
    <x-lazy-image src="/storage/products/image.jpg" alt="Mon produit" class="img-fluid" />
    <x-lazy-image :src="$product->image_url" alt="{{ $product->name }}" width="300" height="200" />
--}}

@props([
    'src',
    'alt' => '',
    'class' => '',
    'width' => null,
    'height' => null,
    'placeholder' => null
])

@php
    // Placeholder par défaut (image grise floue en base64)
    $defaultPlaceholder = 'data:image/svg+xml;base64,' . base64_encode('
        <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
            <rect fill="#f3f4f6" width="100" height="100"/>
            <text fill="#9ca3af" font-family="sans-serif" font-size="12" x="50%" y="50%" text-anchor="middle" dy=".3em">⏳</text>
        </svg>
    ');
    
    $placeholderSrc = $placeholder ?? $defaultPlaceholder;
@endphp

<img 
    src="{{ $placeholderSrc }}"
    data-src="{{ $src }}"
    alt="{{ $alt }}"
    class="lazy-image {{ $class }}"
    loading="lazy"
    @if($width) width="{{ $width }}" @endif
    @if($height) height="{{ $height }}" @endif
    {{ $attributes }}
    onerror="this.onerror=null; this.src='{{ $placeholderSrc }}';"
/>

@once
@push('styles')
<style>
    .lazy-image {
        transition: opacity 0.3s ease-in-out;
        background-color: #f3f4f6;
    }
    .lazy-image.loaded {
        background-color: transparent;
    }
    .lazy-image:not(.loaded) {
        filter: blur(5px);
    }
</style>
@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Utiliser Intersection Observer pour le lazy loading
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    const src = img.dataset.src;
                    
                    if (src) {
                        img.src = src;
                        img.classList.add('loaded');
                        img.removeAttribute('data-src');
                        observer.unobserve(img);
                    }
                }
            });
        }, {
            rootMargin: '50px 0px', // Charger 50px avant d'être visible
            threshold: 0.01
        });

        document.querySelectorAll('img.lazy-image[data-src]').forEach(img => {
            imageObserver.observe(img);
        });
    } else {
        // Fallback pour anciens navigateurs
        document.querySelectorAll('img.lazy-image[data-src]').forEach(img => {
            img.src = img.dataset.src;
            img.classList.add('loaded');
        });
    }
});
</script>
@endpush
@endonce
