<div class="modal fade" id="systemAlertModal" tabindex="-1" aria-labelledby="systemAlertModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="systemAlertModalLabel"></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="text-muted" id="systemAlertModalBody"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary d-none" id="systemAlertEnableSoundBtn"></button>
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">{{ __('common.close') }}</button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
    <script>
        (() => {
            const pollUrl = "{{ route('notifications.poll') }}";
            const queue = [];
            let isShowing = false;
            let audioCtx = null;
            let audioUnlocked = false;
            const shownKey = 'system_alert_shown_ids';
            const enableSoundLabelAr = 'تفعيل الصوت';
            const enableSoundLabelEn = 'Enable sound';

            function getEnableSoundLabel() {
                return document.documentElement.getAttribute('lang') === 'ar'
                    ? enableSoundLabelAr
                    : enableSoundLabelEn;
            }

            function getEnableSoundButton() {
                return document.getElementById('systemAlertEnableSoundBtn');
            }

            async function ensureAudioUnlocked(interactive) {
                const AudioContext = window.AudioContext || window.webkitAudioContext;
                if (!AudioContext) return;

                try {
                    audioCtx = audioCtx || new AudioContext();
                    await audioCtx.resume();
                    audioUnlocked = true;
                    const btn = getEnableSoundButton();
                    if (btn) btn.classList.add('d-none');
                    return true;
                } catch (e) {
                    audioUnlocked = false;
                    const btn = getEnableSoundButton();
                    if (btn) {
                        btn.textContent = getEnableSoundLabel();
                        btn.classList.remove('d-none');
                    }
                    if (interactive) return false;
                    return false;
                }
            }

            function setupAudioUnlock() {
                const unlockOnGesture = () => {
                    ensureAudioUnlocked(false);
                };
                window.addEventListener('pointerdown', unlockOnGesture, { once: true });
                window.addEventListener('keydown', unlockOnGesture, { once: true });

                const btn = getEnableSoundButton();
                if (btn) {
                    btn.textContent = getEnableSoundLabel();
                    btn.addEventListener('click', async () => {
                        const ok = await ensureAudioUnlocked(true);
                        if (ok) {
                            await playChime(true);
                        }
                    });
                }
            }

            function getShownMap() {
                try {
                    const raw = sessionStorage.getItem(shownKey);
                    if (!raw) return {};
                    const parsed = JSON.parse(raw);
                    if (parsed && typeof parsed === 'object') return parsed;
                    return {};
                } catch (e) {
                    return {};
                }
            }

            function markShown(id) {
                const map = getShownMap();
                map[String(id)] = 1;
                try {
                    sessionStorage.setItem(shownKey, JSON.stringify(map));
                } catch (e) {}
            }

            async function playChime(interactive) {
                try {
                    const ok = await ensureAudioUnlocked(interactive);
                    if (!ok || !audioCtx) return;
                    const ctx = audioCtx;
                    const master = ctx.createGain();
                    master.gain.value = 0.0001;
                    master.connect(ctx.destination);

                    const now = ctx.currentTime + 0.03;
                    master.gain.setValueAtTime(0.0001, now);
                    master.gain.exponentialRampToValueAtTime(0.18, now + 0.02);
                    master.gain.exponentialRampToValueAtTime(0.0001, now + 1.2);

                    const o1 = ctx.createOscillator();
                    const o2 = ctx.createOscillator();
                    o1.type = 'triangle';
                    o2.type = 'sine';
                    o1.frequency.setValueAtTime(659.25, now);
                    o2.frequency.setValueAtTime(880.00, now);
                    o1.connect(master);
                    o2.connect(master);
                    o1.start(now);
                    o2.start(now + 0.03);
                    o1.stop(now + 1.2);
                    o2.stop(now + 1.2);
                } catch (e) {}
            }

            async function playChatChime(interactive) {
                try {
                    const ok = await ensureAudioUnlocked(interactive);
                    if (!ok || !audioCtx) return;
                    const ctx = audioCtx;
                    
                    const master = ctx.createGain();
                    master.connect(ctx.destination);
                    
                    const now = ctx.currentTime;
                    // Tone 1
                    master.gain.setValueAtTime(0, now);
                    master.gain.linearRampToValueAtTime(0.2, now + 0.02);
                    master.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
                    
                    const osc1 = ctx.createOscillator();
                    osc1.type = 'sine';
                    osc1.frequency.setValueAtTime(659.25, now); // E5
                    osc1.connect(master);
                    osc1.start(now);
                    osc1.stop(now + 0.15);

                    // Tone 2
                    const master2 = ctx.createGain();
                    master2.connect(ctx.destination);
                    master2.gain.setValueAtTime(0, now + 0.15);
                    master2.gain.linearRampToValueAtTime(0.2, now + 0.17);
                    master2.gain.exponentialRampToValueAtTime(0.001, now + 0.4);

                    const osc2 = ctx.createOscillator();
                    osc2.type = 'sine';
                    osc2.frequency.setValueAtTime(880.00, now + 0.15); // A5
                    osc2.connect(master2);
                    osc2.start(now + 0.15);
                    osc2.stop(now + 0.4);
                } catch (e) {}
            }

            function showNext() {
                if (isShowing) return;
                const next = queue.shift();
                if (!next) return;

                const titleEl = document.getElementById('systemAlertModalLabel');
                const bodyEl = document.getElementById('systemAlertModalBody');
                const modalEl = document.getElementById('systemAlertModal');
                if (!titleEl || !bodyEl || !modalEl) return;

                titleEl.textContent = next.title || '';
                bodyEl.textContent = next.body || '';
                const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
                isShowing = true;
                playChime(false);
                modal.show();
            }

            function enqueue(items) {
                const shown = getShownMap();
                items.forEach((it) => {
                    if (!it || !it.id) return;
                    if (shown[String(it.id)] === 1) return;
                    markShown(it.id);
                    queue.push(it);
                });
                showNext();
            }

            let previousChatUnread = null;

            async function poll() {
                try {
                    const res = await fetch(pollUrl, { headers: { 'X-Requested-With': 'XMLHttpRequest' }, credentials: 'same-origin' });
                    if (!res.ok) return;
                    const data = await res.json();
                    const items = Array.isArray(data.items) ? data.items : [];
                    if (items.length) enqueue(items);

                    if (data.chat_unread !== undefined) {
                        const currentUnread = parseInt(data.chat_unread, 10) || 0;
                        const badge = document.getElementById('header-chat-badge');
                        
                        if (badge) {
                            if (currentUnread > 0) {
                                badge.textContent = currentUnread;
                                badge.classList.remove('d-none');
                            } else {
                                badge.classList.add('d-none');
                            }
                        }

                        if (previousChatUnread !== null && currentUnread > previousChatUnread) {
                            playChatChime(false);
                        }
                        previousChatUnread = currentUnread;
                    }
                } catch (e) {}
            }

            setupAudioUnlock();

            document.addEventListener('DOMContentLoaded', () => {
                const modalEl = document.getElementById('systemAlertModal');
                if (!modalEl) return;

                modalEl.addEventListener('hidden.bs.modal', () => {
                    isShowing = false;
                    showNext();
                });

                poll();
                setInterval(poll, 2000);
            });
        })();
    </script>
@endpush
