{{-- ═══════════════════════════════════════════════════════════════
     COMUNICADO POPUP CAROUSEL
     Se carga desde el layout público. Solo aparece si hay noticias/
     comunicados marcados como mostrar_popup=true y activos.
     Cookie: popup_visto_YYYY-MM-DD (no muestra más de 1 vez por día)
═══════════════════════════════════════════════════════════════ --}}

@php
    $popupItems = \App\Models\Noticia::paraPopup()->limit(8)->get();
@endphp

@if($popupItems->count() > 0)
<!-- ════════ POPUP OVERLAY ════════ -->
<div id="popupOverlay"
     style="display:none;position:fixed;inset:0;z-index:99999;background:rgba(10,10,30,.72);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);align-items:center;justify-content:center;padding:16px;">

    <!-- Popup Card -->
    <div id="popupCard"
         style="background:#fff;border-radius:22px;max-width:560px;width:100%;max-height:92vh;overflow:hidden;box-shadow:0 32px 80px rgba(0,0,0,.45);display:flex;flex-direction:column;position:relative;animation:popupIn .4s cubic-bezier(.34,1.56,.64,1);">

        <!-- Barra superior con color según tipo -->
        <div id="popupHeader"
             style="padding:18px 22px 14px;background:linear-gradient(135deg,#1a237e,#283593);display:flex;align-items:center;gap:12px;flex-shrink:0;">
            <div id="popupIcon"
                 style="width:40px;height:40px;border-radius:12px;background:rgba(255,224,130,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="bi bi-megaphone-fill" style="color:#ffe082;font-size:18px;"></i>
            </div>
            <div style="flex:1;min-width:0;">
                <div id="popupTipo"
                     style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:1.5px;color:#ffe082;margin-bottom:2px;">
                    Comunicado
                </div>
                <div id="popupTitulo"
                     style="color:#fff;font-weight:700;font-size:1rem;line-height:1.3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                </div>
            </div>
            <!-- Cerrar -->
            <button onclick="cerrarPopup()" title="Cerrar"
                    style="background:rgba(255,255,255,.15);border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;color:#fff;font-size:16px;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .2s;"
                    onmouseover="this.style.background='rgba(255,255,255,.3)'"
                    onmouseout="this.style.background='rgba(255,255,255,.15)'">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>

        <!-- Imagen opcional -->
        <div id="popupImgWrap" style="display:none;flex-shrink:0;max-height:200px;overflow:hidden;">
            <img id="popupImg" src="" alt="" style="width:100%;height:200px;object-fit:cover;">
        </div>

        <!-- Contenido del slide -->
        <div style="padding:20px 22px;overflow-y:auto;flex:1;">
            <p id="popupResumen"
               style="font-size:.95rem;color:#475569;line-height:1.7;margin:0 0 16px;"></p>

            <!-- Fecha -->
            <div id="popupFecha"
                 style="font-size:11.5px;color:#94a3b8;margin-bottom:14px;">
            </div>

            <!-- Botón "Leer más" -->
            <a id="popupVerMas" href="#"
               style="display:inline-flex;align-items:center;gap:6px;padding:9px 22px;border-radius:50px;background:linear-gradient(135deg,#1a237e,#283593);color:#fff;font-weight:700;font-size:13.5px;text-decoration:none;box-shadow:0 4px 16px #1a237e44;transition:transform .18s,box-shadow .18s;"
               onmouseover="this.style.transform='translateY(-2px)';this.style.boxShadow='0 8px 24px #1a237e66'"
               onmouseout="this.style.transform='';this.style.boxShadow='0 4px 16px #1a237e44'">
                <i class="bi bi-eye"></i> Ver publicación completa
            </a>
        </div>

        <!-- Carrusel navegación -->
        @if($popupItems->count() > 1)
        <div style="padding:14px 22px 18px;border-top:1px solid #f1f5f9;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;">
            <!-- Flechas -->
            <div style="display:flex;gap:8px;">
                <button onclick="popupPrev()" id="btnPrev"
                        style="background:#f1f5f9;border:none;border-radius:10px;width:36px;height:36px;cursor:pointer;color:#475569;font-size:15px;display:flex;align-items:center;justify-content:center;transition:all .15s;"
                        onmouseover="this.style.background='#e2e8f0'" onmouseout="this.style.background='#f1f5f9'">
                    <i class="bi bi-chevron-left"></i>
                </button>
                <button onclick="popupNext()" id="btnNext"
                        style="background:#1a237e;border:none;border-radius:10px;width:36px;height:36px;cursor:pointer;color:#fff;font-size:15px;display:flex;align-items:center;justify-content:center;transition:all .15s;"
                        onmouseover="this.style.opacity='.85'" onmouseout="this.style.opacity='1'">
                    <i class="bi bi-chevron-right"></i>
                </button>
            </div>

            <!-- Dots indicadores -->
            <div style="display:flex;gap:6px;align-items:center;" id="popupDots">
                @foreach($popupItems as $pi => $item)
                <button onclick="popupGoTo({{ $pi }})"
                        class="popup-dot"
                        data-idx="{{ $pi }}"
                        style="width:{{ $pi === 0 ? '24' : '8' }}px;height:8px;border-radius:50px;background:{{ $pi === 0 ? '#1a237e' : '#cbd5e1' }};border:none;cursor:pointer;transition:all .3s;padding:0;">
                </button>
                @endforeach
            </div>

            <!-- Contador -->
            <div style="font-size:12px;color:#94a3b8;font-weight:600;">
                <span id="popupCounter">1</span> / {{ $popupItems->count() }}
            </div>
        </div>
        @else
        <div style="padding:6px 22px 16px;"></div>
        @endif

        <!-- No mostrar hoy -->
        <div style="padding:0 22px 14px;display:flex;align-items:center;gap:6px;justify-content:center;">
            <label style="font-size:11.5px;color:#94a3b8;cursor:pointer;display:flex;align-items:center;gap:6px;user-select:none;">
                <input type="checkbox" id="chkNoMostrar" style="cursor:pointer;">
                No mostrar hoy
            </label>
        </div>

    </div>
</div>

<!-- ════════ ESTILOS ════════ -->
<style>
@keyframes popupIn {
    from { opacity:0; transform:scale(.88) translateY(30px); }
    to   { opacity:1; transform:scale(1) translateY(0); }
}
@keyframes slideLeft {
    from { opacity:0; transform:translateX(40px); }
    to   { opacity:1; transform:translateX(0); }
}
@keyframes slideRight {
    from { opacity:0; transform:translateX(-40px); }
    to   { opacity:1; transform:translateX(0); }
}
.popup-dot { outline:none; }
#popupCard { animation: popupIn .4s cubic-bezier(.34,1.56,.64,1); }
</style>

<!-- ════════ SCRIPT ════════ -->
@php
    $popupSlides = $popupItems->map(function($n) {
        return [
            'titulo'  => $n->titulo,
            'resumen' => $n->resumen ?? '',
            'imagen'  => $n->imagen ? asset('storage/' . $n->imagen) : null,
            'fecha'   => $n->fecha_publicacion->format('d/m/Y'),
            'tipo'    => ucfirst($n->tipo),
            'slug'    => $n->slug,
            'color'   => $n->tipo === 'comunicado' ? '#ad1457' : '#1a237e',
        ];
    })->values()->toArray();
@endphp
<script>
(function () {
    // Datos del servidor
    const slides = @json($popupSlides);

    let current   = 0;
    let autoTimer = null;
    const total   = slides.length;

    // ── Verificar cookie ──────────────────────────────────────
    function getCookie(name) {
        return document.cookie.split(';').some(c => c.trim().startsWith(name + '='));
    }
    function setCookie(name, days) {
        const d = new Date();
        d.setTime(d.getTime() + days * 864e5);
        document.cookie = name + '=1;expires=' + d.toUTCString() + ';path=/';
    }

    const cookieName = 'popup_visto_{{ date("Y-m-d") }}';
    if (getCookie(cookieName)) return; // Ya visto hoy

    // ── Mostrar popup ─────────────────────────────────────────
    window.addEventListener('load', function () {
        setTimeout(function () {
            const ov = document.getElementById('popupOverlay');
            if (ov) {
                ov.style.display = 'flex';
                renderSlide(0, 'none');
                startAuto();
            }
        }, 1200); // Espera 1.2s antes de mostrar
    });

    // ── Renderizar slide ──────────────────────────────────────
    function renderSlide(idx, dir) {
        const s  = slides[idx];
        const hdr = document.getElementById('popupHeader');

        // Color del header según tipo
        if (s.tipo.toLowerCase() === 'comunicado') {
            hdr.style.background = 'linear-gradient(135deg,#ad1457,#880e4f)';
        } else {
            hdr.style.background = 'linear-gradient(135deg,#1a237e,#283593)';
        }

        document.getElementById('popupTipo').textContent    = s.tipo;
        document.getElementById('popupTitulo').textContent  = s.titulo;
        document.getElementById('popupResumen').textContent = s.resumen || 'Sin descripción.';
        document.getElementById('popupFecha').textContent   = '📅 ' + s.fecha;
        document.getElementById('popupVerMas').href         = '/paginaweb/public/noticia/' + s.slug;

        // Imagen
        const imgWrap = document.getElementById('popupImgWrap');
        const img     = document.getElementById('popupImg');
        if (s.imagen) {
            img.src = s.imagen;
            imgWrap.style.display = 'block';
        } else {
            imgWrap.style.display = 'none';
        }

        // Animación
        const content = document.getElementById('popupResumen').parentElement;
        if (dir !== 'none') {
            content.style.animation = 'none';
            void content.offsetWidth;
            content.style.animation = dir === 'next' ? 'slideLeft .3s ease' : 'slideRight .3s ease';
        }

        // Dots
        document.querySelectorAll('.popup-dot').forEach((dot, i) => {
            dot.style.width     = i === idx ? '24px' : '8px';
            dot.style.background = i === idx ? s.color : '#cbd5e1';
        });

        // Contador
        const counter = document.getElementById('popupCounter');
        if (counter) counter.textContent = idx + 1;

        current = idx;
    }

    // ── Navegación ────────────────────────────────────────────
    window.popupNext = function () {
        resetAuto();
        renderSlide((current + 1) % total, 'next');
    };
    window.popupPrev = function () {
        resetAuto();
        renderSlide((current - 1 + total) % total, 'prev');
    };
    window.popupGoTo = function (idx) {
        resetAuto();
        renderSlide(idx, idx > current ? 'next' : 'prev');
    };

    // ── Auto-play cada 5s ────────────────────────────────────
    function startAuto() {
        if (total > 1) {
            autoTimer = setInterval(() => popupNext(), 5000);
        }
    }
    function resetAuto() {
        clearInterval(autoTimer);
        startAuto();
    }

    // ── Cerrar ────────────────────────────────────────────────
    window.cerrarPopup = function () {
        const ov = document.getElementById('popupOverlay');
        if (ov) ov.style.display = 'none';
        clearInterval(autoTimer);

        // "No mostrar hoy"
        if (document.getElementById('chkNoMostrar')?.checked) {
            setCookie(cookieName, 1);
        }
    };

    // Cerrar al hacer clic en el overlay (fuera del card)
    document.getElementById('popupOverlay')?.addEventListener('click', function (e) {
        if (e.target === this) cerrarPopup();
    });

    // Tecla Escape
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') cerrarPopup();
    });

})();
</script>
@endif
