document.addEventListener('DOMContentLoaded', () => {
    const pixModal = document.getElementById('pixModal');
    const pixCodeInput = document.getElementById('pixCode');
    const pixQrCodeImg = document.getElementById('pixQrCodeImg');
    const pixExpiresAt = document.getElementById('pixExpiresAt');
    const pixAmount = document.getElementById('pixAmount');
    const copyPixCodeBtn = document.getElementById('copyPixCodeBtn');
    const closePixModalBtn = document.getElementById('closePixModalBtn');
    const pixStatusMessage = document.getElementById('pixStatusMessage');
    const pixStatusIcon = document.getElementById('pixStatusIcon');
    const pixStatusSpinner = document.getElementById('pixStatusSpinner');

    let countdownInterval;
    let statusCheckInterval;
    let currentTransactionId = null;

    function showPixModal(data) {
        pixModal.classList.remove('hidden');
        pixModal.classList.add('flex');

        const pixCode = data.pix_code || data.pixCode;
        const pixQrCode = data.pix_qr_code || data.pixQrCode;
        const expiresAt = data.expires_at;
        const amount = data.amount;
        const status = data.status || 'pending';
        currentTransactionId = data.transaction_id;

        pixCodeInput.value = pixCode;
        pixAmount.textContent = `R$ ${parseFloat(amount).toFixed(2).replace('.', ',')}`;

        if (pixQrCode) {
            // SplitEasy returns a URL for the QR code image
            pixQrCodeImg.src = pixQrCode;
            pixQrCodeImg.classList.remove('hidden');
        } else {
            // Fallback to generate QR code from pixCode if no image URL is provided
            try {
                new QRious({
                    element: pixQrCodeImg,
                    value: pixCode,
                    size: 200
                });
                pixQrCodeImg.classList.remove('hidden');
            } catch (e) {
                console.error("Erro ao gerar QR Code:", e);
                pixQrCodeImg.classList.add('hidden');
            }
        }

        updatePixStatus(status);
        startCountdown(expiresAt);
        startStatusMonitoring();
    }

    function closePixModal() {
        pixModal.classList.add('hidden');
        pixModal.classList.remove('flex');
        clearInterval(countdownInterval);
        clearInterval(statusCheckInterval);
        currentTransactionId = null;
    }

    function startCountdown(expiresAtString) {
        clearInterval(countdownInterval);
        const expiresAt = new Date(expiresAtString);

        countdownInterval = setInterval(() => {
            const now = new Date();
            const timeLeft = expiresAt.getTime() - now.getTime();

            if (timeLeft <= 0) {
                clearInterval(countdownInterval);
                pixExpiresAt.textContent = 'Expirado';
                updatePixStatus('expired');
                return;
            }

            const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

            pixExpiresAt.textContent = `Expira em: ${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }, 1000);
    }

    async function checkPaymentStatus() {
        if (!currentTransactionId) return;

        try {
            const response = await fetch('../../gerar-pix-spliteasy.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    action: 'verificar_status',
                    transaction_id: currentTransactionId
                })
            });
            const data = await response.json();

            if (data.success) {
                updatePixStatus(data.status);
                if (data.status === 'paid' || data.status === 'refused' || data.status === 'canceled' || data.status === 'expired') {
                    clearInterval(statusCheckInterval);
                }
            } else {
                console.error("Erro ao verificar status:", data.error);
            }
        } catch (error) {
            console.error("Erro de conexão ao verificar status:", error);
        }
    }

    function startStatusMonitoring() {
        clearInterval(statusCheckInterval);
        statusCheckInterval = setInterval(checkPaymentStatus, 5000); // Check every 5 seconds
    }

    function updatePixStatus(status) {
        pixStatusSpinner.classList.add('hidden');
        pixStatusIcon.classList.add('hidden');
        pixStatusMessage.className = 'font-semibold'; // Reset classes

        switch (status) {
            case 'paid':
                pixStatusMessage.textContent = 'Pagamento Confirmado!';
                pixStatusMessage.classList.add('text-green-600');
                pixStatusIcon.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-check-circle-2 text-green-600"><circle cx="12" cy="12" r="10"/><path d="m8 15 2 2 6-6"/></svg>`;
                pixStatusIcon.classList.remove('hidden');
                break;
            case 'refused':
                pixStatusMessage.textContent = 'Pagamento Recusado.';
                pixStatusMessage.classList.add('text-red-600');
                pixStatusIcon.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x-circle text-red-600"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>`;
                pixStatusIcon.classList.remove('hidden');
                break;
            case 'canceled':
                pixStatusMessage.textContent = 'Pagamento Cancelado.';
                pixStatusMessage.classList.add('text-red-600');
                pixStatusIcon.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x-circle text-red-600"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>`;
                pixStatusIcon.classList.remove('hidden');
                break;
            case 'expired':
                pixStatusMessage.textContent = 'Pagamento Expirado.';
                pixStatusMessage.classList.add('text-yellow-600');
                pixStatusIcon.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-timer-off text-yellow-600"><path d="M10 2h4"/><path d="M12 14v-4"/><path d="M4.93 4.93l.71.71"/><path d="M2 12h2"/><path d="M4.22 19.78l.71-.71"/><path d="M12 22v-2"/><path d="M19.07 19.07l-.71-.71M22 12h-2"/><path d="M19.78 4.22l-.71.71"/><path d="M17.89 17.89a10 10 0 0 1-5.17 2.34c-2.04.29-4.1-.06-5.8-.94"/><path d="M14.83 9.17a4 4 0 0 0-5.66 0"/><path d="m2 2 20 20"/></svg>`;
                pixStatusIcon.classList.remove('hidden');
                break;
            case 'pending':
            case 'processing':
            default:
                pixStatusMessage.textContent = 'Aguardando Pagamento...';
                pixStatusMessage.classList.add('text-blue-600');
                pixStatusSpinner.classList.remove('hidden');
                break;
        }
    }

    copyPixCodeBtn.addEventListener('click', () => {
        pixCodeInput.select();
        document.execCommand('copy');
        alert('Código PIX copiado!');
    });

    closePixModalBtn.addEventListener('click', closePixModal);

    // Expose showPixModal to global scope if needed by other scripts
    window.showPixModal = showPixModal;
});
