<div id="wa-qr-modal" class="fixed inset-0 z-[9999] hidden items-center justify-center bg-black/60 p-4">
    <div class="w-full max-w-md rounded-2xl bg-white p-5 shadow-2xl dark:bg-gray-900">
        <div class="mb-4 flex items-start justify-between">
            <div>
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Koneksi WhatsApp</h3>
                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                    Scan QR di bawah ini untuk menghubungkan WhatsApp.
                </p>
            </div>
            <button type="button" onclick="closeWaModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                ✕
            </button>
        </div>

        <div class="rounded-xl border border-gray-200 p-4 text-center dark:border-gray-700">
            <div id="wa-qr-loading" class="py-10 text-sm text-gray-500 dark:text-gray-400">
                Menyiapkan QR...
            </div>

            <img id="wa-qr-image" src="" alt="QR WhatsApp" class="mx-auto hidden w-64 max-w-full rounded-lg border border-gray-200 p-2 dark:border-gray-700" />

            <div id="wa-qr-status" class="mt-4 text-sm font-medium text-brand-600 dark:text-brand-400">
                Menunggu scan...
            </div>
        </div>

        <div class="mt-4 flex items-center justify-between gap-2">
            <button type="button"
                    onclick="logoutWaSession()"
                    class="rounded-lg border border-red-300 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50 dark:border-red-800 dark:text-red-400 dark:hover:bg-red-900/20">
                Logout WA
            </button>

            <div class="flex gap-2">
                <button type="button"
                        onclick="refreshWaQr()"
                        class="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800">
                    Refresh QR
                </button>
                <button type="button"
                        onclick="closeWaModal()"
                        class="rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    let waPendingSendUrl = null;
    let waStatusPoller = null;

    function openWaModal(sendUrl = null) {
        waPendingSendUrl = sendUrl || null;

        const modal = document.getElementById('wa-qr-modal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');

        refreshWaQr();
        startWaPolling();
    }

    function closeWaModal() {
        const modal = document.getElementById('wa-qr-modal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');

        if (waStatusPoller) {
            clearInterval(waStatusPoller);
            waStatusPoller = null;
        }
    }

    async function refreshWaQr() {
        document.getElementById('wa-qr-loading').classList.remove('hidden');
        document.getElementById('wa-qr-image').classList.add('hidden');
        document.getElementById('wa-qr-status').textContent = 'Menyiapkan QR...';

        try {
            const res = await fetch("{{ route('wa.qr') }}");
            const data = await res.json();

            if (data.connected) {
                document.getElementById('wa-qr-loading').classList.add('hidden');
                document.getElementById('wa-qr-status').textContent = 'WhatsApp sudah terhubung.';
                if (waPendingSendUrl) {
                    const sendUrl = waPendingSendUrl;
                    waPendingSendUrl = null;
                    await sendWaNow(sendUrl);
                }
                return;
            }

            if (data.qr) {
                const img = document.getElementById('wa-qr-image');
                img.src = data.qr;
                img.classList.remove('hidden');
                document.getElementById('wa-qr-loading').classList.add('hidden');
                document.getElementById('wa-qr-status').textContent = 'Silakan scan QR dengan WhatsApp.';
            } else {
                document.getElementById('wa-qr-status').textContent = 'QR belum tersedia, coba refresh.';
            }
        } catch (e) {
            document.getElementById('wa-qr-status').textContent = 'Gagal mengambil QR.';
            alert('Route wa.qr atau gateway WA belum aktif.');
        }
    }

    function startWaPolling() {
        if (waStatusPoller) clearInterval(waStatusPoller);

        waStatusPoller = setInterval(async () => {
            try {
                const res = await fetch("{{ route('wa.status') }}");
                const data = await res.json();

                if (data.connected) {
                    document.getElementById('wa-qr-status').textContent = 'WhatsApp terhubung.';
                    if (waPendingSendUrl) {
                        const sendUrl = waPendingSendUrl;
                        waPendingSendUrl = null;
                        await sendWaNow(sendUrl);
                    }
                }
            } catch (e) {}
        }, 2500);
    }

    async function logoutWaSession() {
        if (!confirm('Logout WhatsApp sekarang?')) return;

        try {
            const res = await fetch("{{ route('wa.logout') }}", {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json'
                }
            });

            const data = await res.json();
            alert(data.message || 'WhatsApp logout.');
            refreshWaQr();
        } catch (e) {
            alert('Gagal logout WhatsApp.');
        }
    }

    async function sendWaNow(url, badgeId = null, btnEl = null) {
        try {
            const res = await fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json'
                }
            });

            const data = await res.json();

            if (data.need_scan) {
                openWaModal(url);
                return false;
            }

            if (!data.ok) {
                alert(data.message || 'Gagal mengirim WhatsApp.');
                return false;
            }

            if (badgeId) {
                const badge = document.getElementById(badgeId);
                if (badge) badge.style.display = 'inline-flex';
            }

            if (btnEl) {
                btnEl.dataset.sent = '1';
                btnEl.classList.remove('bg-success-500', 'hover:bg-success-600');
                btnEl.classList.add('bg-gray-400', 'cursor-not-allowed', 'opacity-80');
                btnEl.style.pointerEvents = 'none';

                const label = btnEl.querySelector('[data-wa-label]');
                if (label) label.textContent = 'TERKIRIM';
            }

            closeWaModal();
            alert(data.message || 'WhatsApp berhasil dikirim.');
            return true;
        } catch (e) {
            alert('Gagal menghubungi server WhatsApp.');
            return false;
        }
    }
</script>