document.addEventListener('DOMContentLoaded', function () {
    console.log('Script Carregado e DOM Pronto');
    // alert('Checkout pronto para uso!'); // Descomente para teste radical

    const carousels = document.querySelectorAll('.carousel-container');

    carousels.forEach((carousel, carouselIndex) => {
        const slides = carousel.querySelectorAll('.carousel-slide');
        const prevBtn = carousel.querySelector('.carousel-btn.prev');
        const nextBtn = carousel.querySelector('.carousel-btn.next');
        const dotsContainer = carousel.querySelector('.carousel-dots');

        let currentIndex = 0;
        let autoPlayInterval;

        // Create dots
        slides.forEach((_, index) => {
            const dot = document.createElement('div');
            dot.classList.add('dot');
            if (index === 0) dot.classList.add('active');
            dot.addEventListener('click', () => {
                goToSlide(index);
                resetAutoPlay();
            });
            dotsContainer.appendChild(dot);
        });

        const dots = dotsContainer.querySelectorAll('.dot');

        function updateCarousel() {
            slides.forEach((slide, index) => {
                slide.classList.toggle('active', index === currentIndex);
            });
            dots.forEach((dot, index) => {
                dot.classList.toggle('active', index === currentIndex);
            });
        }

        function nextSlide() {
            currentIndex = (currentIndex + 1) % slides.length;
            updateCarousel();
        }

        function prevSlide() {
            currentIndex = (currentIndex - 1 + slides.length) % slides.length;
            updateCarousel();
        }

        function goToSlide(index) {
            currentIndex = index;
            updateCarousel();
        }

        function startAutoPlay() {
            autoPlayInterval = setInterval(nextSlide, 4000 + (carouselIndex * 500)); // Slightly offset intervals
        }

        function resetAutoPlay() {
            clearInterval(autoPlayInterval);
            startAutoPlay();
        }

        nextBtn?.addEventListener('click', () => {
            nextSlide();
            resetAutoPlay();
        });

        prevBtn?.addEventListener('click', () => {
            prevSlide();
            resetAutoPlay();
        });

        startAutoPlay();
    });

    console.log('Iniciando lógica de PIX...');

    // PIX and Upsell Logic
    const btnBuyBasic = document.getElementById('btn-buy-basic');
    const upsellModal = document.getElementById('upsell-modal');
    const btnDeclineUpsell = document.getElementById('btn-decline-upsell');
    const btnAcceptUpsell = document.getElementById('btn-accept-upsell');
    const btnBuyPremium = document.getElementById('btn-buy-premium');

    const pixModal = document.getElementById('pix-modal');
    const pixContainer = document.getElementById('pix-container');
    const pixUserData = document.getElementById('pix-user-data');
    const pixLoading = document.getElementById('pix-loading');
    const pixDetails = document.getElementById('pix-details');
    const pixErrorWrapper = document.getElementById('pix-error');
    const pixErrorMsg = document.getElementById('pix-error-msg');
    const btnGeneratePixFinal = document.getElementById('btn-generate-pix-final');

    // Configurações da API (Usando Proxy PHP para segurança e CORS)
    const PIX_PROXY_URL = 'pix.php';

    let currentOrder = { amount: 0, description: '' };
    let pollingInterval = null;

    if (btnBuyBasic && upsellModal) {
        btnBuyBasic.addEventListener('click', function (e) {
            e.preventDefault();
            upsellModal.classList.add('active');
        });
    }

    if (btnDeclineUpsell) {
        btnDeclineUpsell.addEventListener('click', function (e) {
            e.preventDefault();
            upsellModal.classList.remove('active');
            openCheckout(990, 'Plano Básico VIP');
        });
    }

    if (btnAcceptUpsell) {
        btnAcceptUpsell.addEventListener('click', function (e) {
            e.preventDefault();
            upsellModal.classList.remove('active');
            openCheckout(1490, 'Plano Básico + Upsell Premium');
        });
    }

    if (btnBuyPremium) {
        btnBuyPremium.addEventListener('click', function (e) {
            e.preventDefault();
            openCheckout(1990, 'Plano Premium VIP');
        });
    }

    function openCheckout(amount, description) {
        console.log('Abrindo checkout:', amount, description);
        currentOrder = { amount, description };
        pixModal.classList.add('active');
        pixContainer.style.display = 'block';
        pixUserData.style.display = 'block';
        pixLoading.style.display = 'none';
        pixDetails.style.display = 'none';
        pixErrorWrapper.style.display = 'none';
        document.getElementById('data-error').style.display = 'none';
    }

    btnGeneratePixFinal?.addEventListener('click', function () {
        console.log('Botão Gerar PIX clicado');
        const name = document.getElementById('cust-name').value;
        const email = document.getElementById('cust-email').value;
        const errorMsg = document.getElementById('data-error');

        if (!name || name.length < 3 || !email || !email.includes('@')) {
            console.warn('Validação falhou:', { name, email });
            errorMsg.style.display = 'block';
            return;
        }

        errorMsg.style.display = 'none';
        generatePix(currentOrder.amount, currentOrder.description, name, email);
    });

    document.getElementById('btn-close-pix')?.addEventListener('click', function () {
        pixModal.classList.remove('active');
        if (pollingInterval) clearInterval(pollingInterval);
    });

    document.getElementById('btn-copy-pix')?.addEventListener('click', function () {
        const copyText = document.getElementById('pix-copy-paste');
        copyText.select();
        copyText.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(copyText.value);

        const btn = this;
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i>';
        btn.style.backgroundColor = '#15803d';
        setTimeout(() => {
            btn.innerHTML = originalHtml;
            btn.style.backgroundColor = '';
        }, 2000);
    });

    async function generatePix(amountInCents, description, payerName, payerEmail) {
        console.log('Iniciando geração de PIX via:', PIX_PROXY_URL);
        pixUserData.style.display = 'none';
        pixLoading.style.display = 'block';

        document.getElementById('pix-amount').innerText = `R$ ${(amountInCents / 100).toFixed(2).replace('.', ',')}`;

        try {
            const externalId = 'order-' + Date.now();

            const response = await fetch(PIX_PROXY_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    amount: amountInCents,
                    external_id: externalId,
                    description: description,
                    payer: {
                        name: payerName,
                        email: payerEmail
                    }
                })
            }).catch(err => {
                console.error('Erro de conexão (Fetch failed):', err);
                throw new Error("Não foi possível conectar ao servidor. Verifique se o arquivo 'pix.php' foi enviado corretamente para a sua hospedagem.");
            });

            console.log('Resposta do servidor recebida. Status:', response.status);

            // Se o servidor deu erro (404, 500, etc)
            if (!response.ok) {
                let errorData;
                try {
                    errorData = await response.json();
                } catch (e) {
                    const errorText = await response.text();
                    console.error('Erro do Servidor (Texto):', errorText);
                    throw new Error(`Erro ${response.status}: O servidor não conseguiu processar o pedido.`);
                }
                console.error('Erro do Servidor (JSON):', errorData);
                throw new Error(errorData.message || `Erro ${response.status}: Problema no servidor.`);
            }

            const contentType = response.headers.get("content-type");
            if (!contentType || !contentType.includes("application/json")) {
                const textBody = await response.text();
                console.error('Resposta não é JSON:', textBody);
                throw new Error("Resposta inválida do servidor. O arquivo pix.php pode estar com erro de código ou o servidor não suporta PHP.");
            }

            const data = await response.json();
            console.log('Dados do PIX Recebidos:', data);

            if (!data.qr_code || !data.pix_copy_paste) {
                console.error('Dados incompletos da API:', data);
                throw new Error("A API retornou um sucesso, mas sem os dados do PIX. Verifique se sua conta na Veno está ativa.");
            }

            console.log('Link/Base64 do QR Code:', data.qr_code.substring(0, 50) + '...');

            const qrImg = document.getElementById('pix-qrcode');

            // Função para tentar gerar o QR code via API pública caso o da Veno falhe
            const setFallbackQr = () => {
                console.warn('Usando gerador de QR Code reserva...');
                qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=${encodeURIComponent(data.pix_copy_paste)}`;
            };

            qrImg.src = data.qr_code;
            qrImg.onerror = setFallbackQr;

            qrImg.onload = () => console.log('Imagem do QR Code pronta!');

            document.getElementById('pix-copy-paste').value = data.pix_copy_paste;
            document.getElementById('pix-status').innerText = 'Aguardando pagamento...';
            document.getElementById('pix-status').style.color = '#f97316';

            pixLoading.style.display = 'none';
            pixDetails.style.display = 'block';

            startPolling(data.id);

        } catch (error) {
            console.error('Erro PIX Detalhado:', error);
            pixLoading.style.display = 'none';
            pixErrorWrapper.style.display = 'block';
            pixErrorMsg.innerText = error.message;

            // Botão "Tentar Novamente" se der erro
            setTimeout(() => {
                const retryBtn = document.createElement('button');
                retryBtn.innerText = 'Voltar e Corrigir Dados';
                retryBtn.className = 'cta-button outline';
                retryBtn.style.marginTop = '10px';
                retryBtn.onclick = () => {
                    pixErrorWrapper.style.display = 'none';
                    pixUserData.style.display = 'block';
                    retryBtn.remove();
                };
                pixErrorWrapper.appendChild(retryBtn);
            }, 500);
        }
    }

    function startPolling(pixId) {
        console.log('Iniciando Polling para ID:', pixId);
        if (pollingInterval) clearInterval(pollingInterval);

        pollingInterval = setInterval(async () => {
            try {
                // Chama o proxy PHP para verificar o status
                const response = await fetch(`${PIX_PROXY_URL}?id=${pixId}`);

                if (response.ok) {
                    const contentType = response.headers.get("content-type");
                    if (contentType && contentType.includes("application/json")) {
                        const data = await response.json();
                        console.log('Status Polling:', data.status);

                        if (data.status === 'paid') {
                            clearInterval(pollingInterval);
                            document.getElementById('pix-status').innerText = 'Pagamento Confirmado! 🎉';
                            document.getElementById('pix-status').style.color = '#15803d';

                            setTimeout(() => {
                                alert('Acesso VIP liberado com sucesso!');
                                // TODO: Add logic to redirect user to members area
                                // window.location.href = "area_membros.html";
                            }, 2000);
                        } else if (data.status === 'expired' || data.status === 'cancelled') {
                            clearInterval(pollingInterval);
                            document.getElementById('pix-status').innerText = 'PIX Expirado ou Cancelado.';
                            document.getElementById('pix-status').style.color = '#ef4444';
                        }
                    }
                }
            } catch (error) {
                console.error('Erro ao consultar status:', error);
            }
        }, 5000);
    }
});
