@php
    $announcementItems = collect($announcements ?? [])->values();
    $popupScope = $scope ?? 'global';
@endphp

@if($announcementItems->isNotEmpty())
    <style>
        .announcement-overlay { position: fixed; inset: 0; z-index: 80; display: flex; align-items: center; justify-content: center; padding: 16px; background: rgba(2, 6, 23, 0.68); backdrop-filter: blur(2px); }
        .announcement-overlay.hidden { display: none; }
        .announcement-card { width: min(92vw, 500px); border-radius: 16px; border: 1px solid #cbd5e1; background: #fff; box-shadow: 0 30px 80px rgba(15, 23, 42, 0.35); transform: translateY(12px) scale(0.98); opacity: 0; transition: transform .22s ease, opacity .22s ease; position: relative; }
        .announcement-card.show { transform: translateY(0) scale(1); opacity: 1; }
        .announcement-content { padding: 16px; }
        .announcement-title { font-size: 1.1rem; font-weight: 700; line-height: 1.3; }
        .announcement-text { margin-top: .5rem; font-size: .92rem; line-height: 1.45; color: #475569; }
        .announcement-media { margin-top: .8rem; width: 100%; max-height: 260px; border-radius: 12px; object-fit: cover; border: 1px solid #cbd5e1; }
        .announcement-video { background: #000; }
        .announcement-link { margin-top: .8rem; display: inline-block; border-radius: 10px; background: #0f172a; color: #fff; padding: 8px 12px; font-size: .82rem; text-decoration: none; }
        .announcement-actions { margin-top: .9rem; display: flex; align-items: center; justify-content: space-between; gap: 10px; }
        .announcement-remember { display: inline-flex; align-items: center; gap: 6px; font-size: .75rem; color: #64748b; }
        .announcement-btn { border-radius: 10px; border: 1px solid #cbd5e1; padding: 7px 12px; font-size: .8rem; font-weight: 600; color: #0f172a; background: #fff; }
        .announcement-close { position: absolute; right: 10px; top: 8px; border: 0; background: transparent; color: #64748b; font-size: 16px; line-height: 1; padding: 4px; cursor: pointer; }
    </style>

    <div class="announcement-overlay hidden" data-announcement-overlay data-scope="{{ $popupScope }}">
        @foreach($announcementItems as $announcement)
            <article
                class="announcement-card hidden"
                data-announcement-card
                data-announcement-id="{{ $announcement->id }}"
                data-show-once="{{ $announcement->show_once ? '1' : '0' }}"
            >
                <button type="button" class="announcement-close" data-announcement-close aria-label="Close announcement">x</button>
                <div class="announcement-content">
                    <div class="announcement-title">{{ $announcement->title }}</div>

                    @if($announcement->message)
                        <div class="announcement-text">{{ $announcement->message }}</div>
                    @endif

                    @if($announcement->media_type === 'image' && $announcement->media_url)
                        <img src="{{ $announcement->media_url }}" alt="{{ $announcement->title }}" class="announcement-media">
                    @elseif($announcement->media_type === 'video')
                        @if($announcement->media_url)
                            <video controls class="announcement-media announcement-video">
                                <source src="{{ $announcement->media_url }}">
                            </video>
                        @elseif($announcement->video_url)
                            <a href="{{ $announcement->video_url }}" target="_blank" rel="noopener noreferrer" class="announcement-link">
                                Watch Video
                            </a>
                        @endif
                    @endif

                    @if($announcement->cta_url)
                        <a href="{{ $announcement->cta_url }}" class="announcement-link">
                            {{ $announcement->cta_label ?: 'Learn More' }}
                        </a>
                    @endif

                    <div class="announcement-actions">
                        <label class="announcement-remember">
                            <input type="checkbox" data-announcement-remember>
                            Do not show again
                        </label>
                        <button type="button" class="announcement-btn" data-announcement-next>Close</button>
                    </div>
                </div>
            </article>
        @endforeach
    </div>

    <script>
        (() => {
            const overlay = document.querySelector(`[data-announcement-overlay][data-scope="{{ $popupScope }}"]`);
            if (!overlay) return;

            const cards = Array.from(overlay.querySelectorAll('[data-announcement-card]'));
            if (!cards.length) return;

            let currentIndex = -1;

            const rememberKey = (card) => `announcement_seen_{{ $popupScope }}_${card.dataset.announcementId}`;

            const shouldSkip = (card) => {
                if (card.dataset.showOnce !== '1') return false;
                return localStorage.getItem(rememberKey(card)) === '1';
            };

            const hideCard = (card) => {
                card.classList.add('hidden');
                card.classList.remove('show');
                card.querySelectorAll('video').forEach((videoEl) => {
                    videoEl.pause();
                });
            };

            const showCard = (index) => {
                cards.forEach(hideCard);

                if (index < 0 || index >= cards.length) {
                    overlay.classList.add('hidden');
                    overlay.classList.remove('show');
                    return;
                }

                currentIndex = index;
                const card = cards[currentIndex];
                overlay.classList.remove('hidden');
                overlay.classList.add('show');
                card.classList.remove('hidden');
                card.classList.add('show');
            };

            const showNext = () => {
                let next = currentIndex + 1;
                while (next < cards.length && shouldSkip(cards[next])) {
                    next += 1;
                }
                showCard(next < cards.length ? next : -1);
            };

            const closeCurrent = () => {
                if (currentIndex < 0) return;
                const card = cards[currentIndex];
                const remember = card.querySelector('[data-announcement-remember]');
                if (card.dataset.showOnce === '1' || (remember && remember.checked)) {
                    localStorage.setItem(rememberKey(card), '1');
                }
                showNext();
            };

            overlay.addEventListener('click', (event) => {
                if (event.target === overlay || event.target.matches('[data-announcement-close]')) {
                    closeCurrent();
                }
            });

            overlay.querySelectorAll('[data-announcement-next]').forEach((button) => {
                button.addEventListener('click', closeCurrent);
            });

            setTimeout(() => showNext(), 420);
        })();
    </script>
@endif
