@if(($newsletter_enabled ?? false) && ($newsletter_popup_enabled ?? false))
@php
    $popupMode = $newsletter_popup_mode ?? 'auto';
    $popupTitle = $newsletter_popup_title ?? 'Restez informé';
    $popupContent = $newsletter_popup_content ?? 'Inscrivez-vous à notre newsletter pour recevoir nos actualités et offres exclusives.';
    $popupImage = $newsletter_popup_image ?? null;
    $popupCta = $newsletter_popup_cta ?? "S'inscrire";
    $popupDelay = (int) ($newsletter_popup_delay_seconds ?? 3);
    $popupRepeatDays = (int) ($newsletter_popup_repeat_days ?? 7);
    $isTodayAllowed = empty($popupDays) || in_array((int) date('w'), $popupDays, true);
@endphp
<div id="newsletter-popup" class="newsletter-popup fixed inset-0 z-[9995] hidden items-center justify-center bg-black/50 p-4" role="dialog" aria-modal="true" aria-labelledby="newsletter-popup-title" @if(session('newsletter_success') || session('newsletter_info')) data-show-success @endif>
    <div class="bg-white rounded-2xl shadow-xl max-w-md w-full overflow-hidden">
        @if($popupImage)
        <img src="{{ str_starts_with($popupImage, 'http') || str_starts_with($popupImage, '/') ? $popupImage : asset('storage/'.$popupImage) }}" alt="" class="w-full h-40 object-cover">
        @endif
        <div class="p-6">
            <h2 id="newsletter-popup-title" class="text-xl font-semibold text-slate-900 mb-2">{{ $popupTitle }}</h2>
            <div class="text-slate-600 text-sm mb-4 prose prose-slate prose-sm max-w-none">{!! \App\Support\SafeHtml::richText($popupContent) !!}</div>
            @if(session('newsletter_success'))
                <p class="text-emerald-600 text-sm font-medium">{{ session('newsletter_success') }}</p>
            @elseif(session('newsletter_info'))
                <p class="text-amber-600 text-sm">{{ session('newsletter_info') }}</p>
            @else
            <form method="POST" action="{{ route('newsletter.subscribe') }}" class="space-y-3">
                @csrf
                <input type="email" name="email" required placeholder="Votre email" class="w-full px-4 py-2.5 rounded-xl text-sm border border-slate-200 focus:ring-2 focus:ring-primary-500 focus:border-primary-500">
                <input type="text" name="name" placeholder="Nom (optionnel)" class="w-full px-4 py-2.5 rounded-xl text-sm border border-slate-200 focus:ring-2 focus:ring-primary-500 focus:border-primary-500">
                <input type="hidden" name="newsletter_popup" value="1">
                @include('partials.captcha-widget', ['context' => 'newsletter'])
                <button type="submit" class="w-full px-5 py-2.5 rounded-xl font-medium text-white transition text-sm" style="background: linear-gradient(135deg, {{ $primary_color ?? '#6366f1' }}, {{ $secondary_color ?? '#8b5cf6' }});">{{ $popupCta }}</button>
            </form>
            @endif
        </div>
        <div class="p-4 border-t border-slate-100 flex justify-end">
            <button type="button" class="newsletter-popup-close px-4 py-2 text-slate-500 hover:text-slate-700 text-sm">Fermer</button>
        </div>
    </div>
</div>
<script>
(function() {
    var key = 'newsletter_popup_closed';
    var repeatDays = {{ $popupRepeatDays }};
    var mode = '{{ $popupMode }}';
    var popup = document.getElementById('newsletter-popup');
    if (!popup) return;
    var forceShowSuccess = popup.hasAttribute('data-show-success');
    function shouldShow() {
        if (forceShowSuccess) return true;
        try {
            var closed = localStorage.getItem(key);
            if (!closed) return true;
            if (repeatDays <= 0) return false;
            var closedAt = parseInt(closed, 10);
            if (isNaN(closedAt)) return true;
            return (Date.now() - closedAt) > (repeatDays * 24 * 60 * 60 * 1000);
        } catch (e) { return true; }
    }
    function openPopup() {
        popup.classList.remove('hidden');
        popup.classList.add('flex');
    }
    function closePopup() {
        popup.classList.add('hidden');
        popup.classList.remove('flex');
        try { localStorage.setItem(key, Date.now().toString()); } catch (e) {}
    }
    if (mode === 'auto' && shouldShow()) {
        var delay = forceShowSuccess ? 0 : ({{ $popupDelay }} * 1000);
        setTimeout(openPopup, delay);
    }
    document.querySelectorAll('.newsletter-popup-trigger').forEach(function (el) {
        el.addEventListener('click', function(e) {
            e.preventDefault();
            openPopup();
        });
    });
    popup.querySelector('.newsletter-popup-close')?.addEventListener('click', closePopup);
    popup.addEventListener('click', function(e) {
        if (e.target === popup) closePopup();
    });
})();
</script>
@endif
