@php
    $popupBanners = collect($banners ?? [])->filter(fn ($b) => $b->type === 'popup');
@endphp
@foreach($popupBanners as $banner)
@php
    $bg = preg_match('/^#[0-9A-Fa-f]{6}$/', (string) ($banner->background_color ?? '')) ? $banner->background_color : '#e84600';
@endphp
<div id="banner-popup-{{ $banner->id }}" class="banner-popup fixed inset-0 z-[9996] hidden items-center justify-center bg-black/50 p-4" role="dialog" aria-modal="true">
    <div class="bg-white rounded-2xl shadow-xl max-w-md w-full overflow-hidden" style="border-top: 4px solid {{ $bg }};">
        <div class="p-6">
            @if($banner->image)
            <img src="{{ str_starts_with($banner->image, 'http') || str_starts_with($banner->image, '/') ? $banner->image : asset('storage/'.$banner->image) }}" alt="" class="w-full h-40 object-cover rounded-lg mb-4">
            @endif
            <div class="text-slate-800 prose prose-slate prose-sm max-w-none">{!! \App\Support\SafeHtml::richText($banner->content) !!}</div>
            @if($banner->link_url)
            <a href="{{ $banner->link_url }}" class="inline-block mt-4 px-5 py-2.5 rounded-xl font-medium text-white transition" style="background-color: {{ $bg }};">{{ $banner->link_text ?? 'Voir' }}</a>
            @endif
        </div>
        <div class="p-4 border-t border-slate-100 flex justify-end">
            <button type="button" class="banner-popup-close px-4 py-2 text-slate-500 hover:text-slate-700 text-sm" data-banner-id="{{ $banner->id }}">Fermer</button>
        </div>
    </div>
</div>
<script>
(function() {
    var key = 'banner_popup_{{ $banner->id }}_closed';
    var popup = document.getElementById('banner-popup-{{ $banner->id }}');
    if (!popup) return;
    try {
        if (localStorage.getItem(key)) return;
    } catch (e) {}
    popup.classList.remove('hidden');
    popup.classList.add('flex');
    popup.querySelector('.banner-popup-close')?.addEventListener('click', function() {
        popup.classList.add('hidden');
        popup.classList.remove('flex');
        try { localStorage.setItem(key, '1'); } catch (e) {}
    });
    popup.addEventListener('click', function(e) {
        if (e.target === popup) {
            popup.classList.add('hidden');
            popup.classList.remove('flex');
            try { localStorage.setItem(key, '1'); } catch (e) {}
        }
    });
})();
</script>
@endforeach
