$(function() {
    // ========================================
    // INTEGRACAO COM DADOS DO CHECKOUT (UPSELL)
    // ========================================
    const upsellData = JSON.parse(localStorage.getItem('upsellData') || '{}');
    const clienteNome = upsellData.nome || 'Participante';
    const clientePagou = upsellData.pago === true;
    const transactionId = upsellData.transaction_id || null;

    // Log para debug
    console.log('🎁 Upsell Data:', upsellData);
    console.log('👤 Cliente:', clienteNome);
    console.log('💰 Pagou:', clientePagou);

    // Personalizar saudacao se tiver nome
    if (clienteNome && clienteNome !== 'Participante') {
        const primeiroNome = clienteNome.split(' ')[0];
        setTimeout(() => {
            const welcomeTitle = document.querySelector('#welcome-modal h2');
            if (welcomeTitle) {
                welcomeTitle.innerHTML = '🎊 PARABÉNS, ' + primeiroNome.toUpperCase() + '! 🎊';
            }
        }, 100);
    }

    const canvas = $('#scratch-canvas')[0];
    const ctx = canvas ? canvas.getContext('2d') : null;
    const area = $('#scratch-area')[0];

    let canScratch = false;
    let attempts = 5;
    let round = 1;
    
    // ===== WEB AUDIO API - ALTA PERFORMANCE =====
    let audioContext = null;
    let audioBuffer = null;
    let sourceNode = null;
    let gainNode = null;
    let isPlaying = false;
    let lastMoveTime = 0;
    let lastPosition = {x: 0, y: 0};
    
    // VELOCIDADE PARA RAF
    let currentSpeed = 0;
    let targetSpeed = 0;
    let isScratching = false;
    
    // Inicializar Web Audio API
    function initAudio() {
        if(!audioContext) {
            audioContext = new (window.AudioContext || window.webkitAudioContext)();
            gainNode = audioContext.createGain();
            gainNode.connect(audioContext.destination);
            
            fetch('sounds/scratch-realistic.mp3')
                .then(response => response.arrayBuffer())
                .then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
                .then(decodedBuffer => {
                    audioBuffer = decodedBuffer;
                    startAudioLoop(); // Iniciar loop RAF
                })
                .catch(e => console.log('Áudio não carregado'));
        }
    }
    
    // Calcular velocidade (chamado no mousemove)
    function updateSpeed(x, y) {
        const now = Date.now();
        const timeDelta = now - lastMoveTime;
        
        if(timeDelta === 0 || !lastMoveTime) {
            lastPosition = {x, y};
            lastMoveTime = now;
            targetSpeed = 0.3;
            return;
        }
        
        const dx = x - lastPosition.x;
        const dy = y - lastPosition.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        targetSpeed = Math.min(distance / Math.max(timeDelta, 1), 3);
        
        lastPosition = {x, y};
        lastMoveTime = now;
    }
    
    // LOOP DE ANIMAÇÃO - 60 FPS
    function startAudioLoop() {
        function audioFrame() {
            if(!audioBuffer || !audioContext) {
                requestAnimationFrame(audioFrame);
                return;
            }
            
            // Suavizar velocidade (lerp)
            currentSpeed += (targetSpeed - currentSpeed) * 0.3;
            
            if(isScratching && currentSpeed > 0.05) {
                if(!isPlaying) {
                    playAudio();
                }
                updateAudioParams(currentSpeed);
            } else if(isPlaying) {
                stopAudio();
            }
            
            // Decaimento de velocidade quando parado
            if(!isScratching) {
                targetSpeed *= 0.85;
            }
            
            requestAnimationFrame(audioFrame);
        }
        audioFrame();
    }
    
    // Tocar áudio
    function playAudio() {
        sourceNode = audioContext.createBufferSource();
        sourceNode.buffer = audioBuffer;
        sourceNode.loop = true;
        sourceNode.playbackRate.value = 1.0;
        sourceNode.connect(gainNode);
        
        gainNode.gain.value = 0;
        sourceNode.start(0);
        isPlaying = true;
    }
    
    // Atualizar parâmetros suavemente
    function updateAudioParams(speed) {
        if(!gainNode || !sourceNode) return;
        
        const now = audioContext.currentTime;
        
        // Volume suave (0.08 a 0.25)
        const targetVolume = Math.min(0.08 + speed * 0.05, 0.25);
        gainNode.gain.setTargetAtTime(targetVolume, now, 0.05);
        
        // Pitch shift orgânico (0.9 a 1.2)
        const targetRate = Math.min(0.9 + speed * 0.1, 1.2);
        sourceNode.playbackRate.setTargetAtTime(targetRate, now, 0.05);
    }
    
    // Parar áudio com fade-out
    function stopAudio() {
        if(gainNode && sourceNode) {
            const now = audioContext.currentTime;
            gainNode.gain.setTargetAtTime(0, now, 0.05);
            
            setTimeout(() => {
                if(sourceNode) {
                    try { sourceNode.stop(); } catch(e) {}
                    sourceNode.disconnect();
                    sourceNode = null;
                }
                isPlaying = false;
            }, 150);
        }
    }
    
    const items = {
        tv: { n: 'Smart TV 60" 4K', i: 'images/produtos/tv.png' },
        iphone: { n: 'iPhone 17 Pro Max', i: 'images/iphone17.png' },
        ps5: { n: 'PlayStation 5 Pro', i: 'images/produtos/ps5.png' },
        money: { n: 'R$ 10.000', i: 'images/produtos/dinheiro.svg' },
        notebook: { n: 'Notebook Gamer', i: 'images/notebookgamer.png' },
        airpods: { n: 'AirPods Pro', i: 'images/airpods.png' },
        ipad: { n: 'iPad Pro', i: 'images/produtos/ipad-pro.png' },
        trip: { n: 'Viagem', i: 'images/produtos/viagem.svg' }
    };
    
    let grid = [];
    
    function shuffle(a) {
        for(let i = a.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [a[i], a[j]] = [a[j], a[i]];
        }
    }
    
    function setup(r) {
        grid = [];
        const keys = Object.keys(items);

        if(r === 2) {
            // GANHA NA 2ª TENTATIVA - EXATAMENTE 3 TVS
            // Primeiro: adiciona 3 TVs
            grid = ['tv', 'tv', 'tv'];
            
            // Depois: preenche os outros 6 slots com itens diferentes
            // Nenhum outro item pode repetir 3x (máx 2 de cada)
            const others = keys.filter(k => k !== 'tv');
            const used = {};
            for(let i = 0; i < 6; i++) {
                let k;
                do {
                    k = others[Math.floor(Math.random() * others.length)];
                } while(used[k] >= 2); // Máximo 2 de cada outro item
                used[k] = (used[k] || 0) + 1;
                grid.push(k);
            }
            shuffle(grid); // Embaralha para ficar aleatório
        } else {
            // OUTRAS TENTATIVAS - NUNCA 3 IGUAIS (máx 2 de cada)
            const used = {};
            for(let i = 0; i < 9; i++) {
                let k;
                do {
                    k = keys[Math.floor(Math.random() * keys.length)];
                } while(used[k] >= 2); // MÁXIMO 2 de cada
                used[k] = (used[k] || 0) + 1;
                grid.push(k);
            }
            shuffle(grid);
        }
    }
    
    function load() {
        $('#grid').empty();
        grid.forEach(k => {
            const it = items[k];
            const slot = $('<div>').addClass('prize-slot bg-white rounded-xl p-4 flex items-center justify-center shadow-lg border-2 border-gray-200').css({
                'aspect-ratio': '1/1',
                'width': '100%',
                'height': '100%'
            });
            const img = $('<img>').attr('src', it.i).addClass('w-full h-full object-contain p-2');
            slot.append(img);
            $('#grid').append(slot);
        });
    }
    
    function initCanvas() {
        if(!canvas || !area) return;
        
        setup(round);
        load();
        
        canvas.width = area.offsetWidth;
        canvas.height = area.offsetHeight;
        
        const g = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        g.addColorStop(0, '#999');
        g.addColorStop(0.5, '#666');
        g.addColorStop(1, '#999');
        
        ctx.fillStyle = g;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        ctx.fillStyle = 'rgba(255,255,255,0.3)';
        ctx.font = 'bold 32px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('RASPE AQUI', canvas.width/2, canvas.height/2);
        
        updateProg(0);
        canScratch = true;
    }
    
    function scratchAt(x, y) {
        if(!canScratch || !ctx) return;
        
        // Apenas atualizar velocidade (RAF cuida do áudio)
        updateSpeed(x, y);
        
        ctx.globalCompositeOperation = 'destination-out';
        ctx.beginPath();
        ctx.arc(x, y, 35, 0, Math.PI * 2);
        ctx.fill();
        
        // Progresso otimizado (5%)
        if(Math.random() < 0.05) checkProg();
    }
    
    function checkProg() {
        if(!canScratch) return;
        
        const data = ctx.getImageData(0, 0, canvas.width, canvas.height);
        const px = data.data;
        let cleared = 0;
        
        // SUPER OTIMIZAÇÃO: Pular ainda mais pixels (a cada 16 pixels = i += 64)
        for(let i = 3; i < px.length; i += 64) {
            if(px[i] < 128) cleared++;
        }
        
        const p = Math.round((cleared / (canvas.width * canvas.height / 16)) * 100);
        updateProg(p);
        
        console.log('📊 Progresso:', p + '%');
        
        if(p >= 95) { // 95% ao invés de 100%
            console.log('✅ 95% atingido! Chamando check()...');
            // Parar raspagem
            isScratching = false;
            canScratch = false;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            updateProg(100);
            setTimeout(check, 600);
        }
    }
    
    function updateProg(p) {
        $('#progress').css('width', p + '%');
        $('#pct').text(p + '%');
    }
    
    let down = false;
    let lx = 0, ly = 0;
    let lastRender = 0;
    
    $(canvas).on('mousedown touchstart', function(e) {
        if(!canScratch) return;
        down = true;
        isScratching = true; // RAF sabe que está raspando
        const r = canvas.getBoundingClientRect();
        const cx = e.touches ? e.touches[0].clientX : e.clientX;
        const cy = e.touches ? e.touches[0].clientY : e.clientY;
        lx = cx - r.left;
        ly = cy - r.top;
        scratchAt(lx, ly);
        e.preventDefault();
    });
    
    $(canvas).on('mousemove touchmove', function(e) {
        if(!canScratch || !down) return;
        
        // THROTTLE: Máximo 60fps
        const now = Date.now();
        if(now - lastRender < 16) return;
        lastRender = now;
        
        const r = canvas.getBoundingClientRect();
        const cx = e.touches ? e.touches[0].clientX : e.clientX;
        const cy = e.touches ? e.touches[0].clientY : e.clientY;
        const x = cx - r.left;
        const y = cy - r.top;
        
        // Reduzir steps para otimização
        const steps = Math.min(Math.max(Math.abs(x - lx), Math.abs(y - ly)), 10);
        for(let i = 0; i <= steps; i++) {
            scratchAt(
                lx + (x - lx) * (i / steps),
                ly + (y - ly) * (i / steps)
            );
        }
        
        lx = x;
        ly = y;
        e.preventDefault();
    });
    
    $(canvas).on('mouseup touchend mouseleave', () => { 
        down = false;
        isScratching = false; // RAF vai fazer fade-out
    });
    
    function check() {
        $('.prize-slot').addClass('revealed');
        
        const c = {};
        grid.forEach(k => c[k] = (c[k] || 0) + 1);
        
        console.log('📊 Contagem:', c);
        
        let won = false;
        let prize = null;
        
        // SOMENTE TV GANHA - ignora outros prêmios
        if(c['tv'] >= 3) {
            won = true;
            prize = 'tv';
            console.log('✅ GANHOU A TV!');
        } else {
            console.log('❌ Não ganhou (precisa de 3 TVs)');
        }
        
        attempts--;
        $('#attempts').text(attempts);
        $('#current').text(6 - attempts);
        
        if(won) {
            setTimeout(() => showWin(prize), 1000);
        } else if(attempts > 0) {
            setTimeout(showFail, 1000);
        }
    }
    
    function showWin(k) {
        const it = items[k];
        $('#win-name').text(it.n);
        $('#win-img').attr('src', it.i);
        
        $('#overlay, #popup-win').fadeIn(300);
        
        const s = $('#snd-win')[0];
        if(s) {
            s.volume = 0.4;
            s.play().catch(() => {});
        }
        
        for(let i = 0; i < 5; i++) {
            setTimeout(() => {
                confetti({
                    particleCount: 100,
                    spread: 70,
                    origin: { y: 0.6 },
                    colors: ['#0047AB', '#FF6400', '#28a745', '#ffd700']
                });
            }, i * 200);
        }
    }
    
    function showFail() {
        $('#overlay, #popup-fail').fadeIn(300);
        round++;
    }
    
    function reset() {
        $('#overlay, #popup-fail, #popup-win').fadeOut(300);
        initCanvas();
    }
    
    $('#btn-start').on('click', function() {
        $('#welcome-modal').fadeOut(300);
        $('#loading').fadeIn(300);
        
        // Áudio de moedas caindo (começa em 6s)
        const coinsSound = new Audio('sounds/coins.mp3');
        coinsSound.currentTime = 6;
        coinsSound.volume = 0.5;
        coinsSound.play().catch(e => console.log('Áudio bloqueado:', e));
        
        setTimeout(() => {
            coinsSound.pause();
            $('#loading').fadeOut(500, () => $('#main').fadeIn(500));
            $('#attempts').text(attempts);
            $('#current').text(1);
            loadWinners();
            area.style.pointerEvents = 'none';
        }, 8000); // 8 segundos (3s a mais)
    });
    
    $('#btn-scratch').on('click', function() {
        $(this).fadeOut(300);
        area.style.pointerEvents = 'auto';
        initAudio(); // Inicializar Web Audio API
        initCanvas();
    });
    
    $('#btn-retry').on('click', reset);
    $('#btn-continue').on('click', () => {
        $('#popup-win').fadeOut(300);
        $('#popup-claim').fadeIn(300);
    });
    
    // Modal Especificações LG
    $('#btn-specs').on('click', function() {
        $('#modal-specs').fadeIn(300);
    });
    
    $('#close-specs, #close-specs-bottom').on('click', function() {
        $('#modal-specs').fadeOut(300);
    });
    
    $('#modal-specs').on('click', function(e) {
        if($(e.target).is('#modal-specs')) {
            $(this).fadeOut(300);
        }
    });
    
    function loadWinners() {
        const winners = [
            { n: 'João S. (RJ)', p: 'Smart TV 60"', img: 'images/produtos/tv.png', avatar: 'images/avatars/joao.jpg' },
            { n: 'Maria P. (SP)', p: 'iPhone 17', img: 'images/iphone17.png', avatar: 'images/avatars/maria.jpg' },
            { n: 'Carlos R. (MG)', p: 'PS5 Pro', img: 'images/produtos/ps5.png', avatar: 'images/avatars/carlos.jpg' },
            { n: 'Ana L. (BA)', p: 'Notebook Gamer', img: 'images/notebookgamer.png', avatar: 'images/avatars/ana.jpg' }
        ];
        
        winners.forEach(w => {
            const div = $('<div>').addClass('bg-gradient-to-r from-green-50 to-blue-50 rounded-xl p-4 border-l-4 border-green-500 shadow-md').html(
                `<div class="flex justify-between items-center">
                    <div class="flex items-center gap-3">
                        <img src="${w.avatar}" alt="${w.n}" class="w-12 h-12 rounded-full border-2 border-caixa-azul shadow-md">
                        <span class="font-bold text-gray-800">${w.n}</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <img src="${w.img}" alt="${w.p}" class="w-10 h-10 object-contain">
                        <span class="font-bold text-green-600">${w.p}</span>
                        <i class="fas fa-star text-yellow-500"></i>
                    </div>
                </div>`
            );
            $('#winners').append(div);
        });
    }
    
    let t = 300;
    setInterval(() => {
        const m = Math.floor(t / 60);
        const s = t % 60;
        $('#countdown').text(`${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`);
        if(t > 0) t--;
    }, 1000);
    
    $(window).on('resize', () => {
        if(canvas && area && canScratch) {
            canvas.width = area.offsetWidth;
            canvas.height = area.offsetHeight;
        }
    });
});
