// Main JavaScript - Efeitos profissionais
document.addEventListener('DOMContentLoaded', function() {
    // Inicializar contador regressivo
    initCountdown();
    
    // Inicializar estatísticas animadas
    initStats();
    
    // Inicializar feed de fretes em tempo real
    initLiveFreights();
    
    // Efeitos de áudio (opcional)
    initAudioEffects();
});

// Contador Regressivo
function initCountdown() {
    let timeLeft = 5 * 60; // 5 minutos
    const minutesElement = document.getElementById('minutes');
    const secondsElement = document.getElementById('seconds');

    function updateTimer() {
        const minutes = Math.floor(timeLeft / 60);
        const seconds = timeLeft % 60;
        
        minutesElement.textContent = minutes.toString().padStart(2, '0');
        secondsElement.textContent = seconds.toString().padStart(2, '0');
        
        // Efeito de urgência nos últimos 60 segundos
        if (timeLeft <= 60) {
            document.querySelector('.countdown-timer').style.background = 
                'linear-gradient(135deg, #ff1744, #ff6d00)';
            minutesElement.style.color = '#fff';
            secondsElement.style.color = '#fff';
        }
        
        if (timeLeft > 0) {
            timeLeft--;
            setTimeout(updateTimer, 1000);
        } else {
            // Tempo esgotado
            minutesElement.textContent = '00';
            secondsElement.textContent = '00';
            document.querySelector('.cta-button').style.opacity = '0.5';
            document.querySelector('.cta-button').style.pointerEvents = 'none';
            document.querySelector('.cta-button').innerHTML = 
                '<span class="btn-text">TEMPO ESGOTADO!</span>';
        }
    }
    
    updateTimer();
}

// Estatísticas Animadas
function initStats() {
    const stats = {
        onlineDrivers: 247,
        totalDrivers: 12500,
        avgPrice: 2850,
        successRate: 98
    };
    
    // Animar número de motoristas online
    animateValue('onlineDrivers', 0, stats.onlineDrivers, 2000);
    
    // Animar outras estatísticas com delay
    setTimeout(() => {
        animateValue('totalDrivers', 0, stats.totalDrivers, 2000);
        animateValue('avgPrice', 0, stats.avgPrice, 2000, true);
        animateValue('successRate', 0, stats.successRate, 2000, false, '%');
    }, 500);
}

function animateValue(id, start, end, duration, isCurrency = false, suffix = '') {
    const element = document.getElementById(id);
    let startTime = null;
    
    const animate = (timestamp) => {
        if (!startTime) startTime = timestamp;
        const progress = Math.min((timestamp - startTime) / duration, 1);
        
        // Easing function para animação suave
        const easeOutQuart = 1 - Math.pow(1 - progress, 4);
        let value = Math.floor(easeOutQuart * (end - start) + start);
        
        if (isCurrency) {
            element.textContent = `R$ ${value.toLocaleString()}`;
        } else if (suffix) {
            element.textContent = `${value}${suffix}`;
        } else {
            element.textContent = value.toLocaleString();
        }
        
        if (progress < 1) {
            requestAnimationFrame(animate);
        }
    };
    
    requestAnimationFrame(animate);
}

// Feed de Fretes em Tempo Real
function initLiveFreights() {
    const freights = [
        { route: 'Curitiba → Porto Alegre', price: 'R$ 2.150' },
        { route: 'Belo Horizonte → Brasília', price: 'R$ 2.800' },
        { route: 'Goiânia → São Paulo', price: 'R$ 1.950' },
        { route: 'Salvador → Fortaleza', price: 'R$ 3.200' },
        { route: 'Manaus → Belém', price: 'R$ 4.100' },
        { route: 'Florianópolis → Curitiba', price: 'R$ 1.800' },
        { route: 'Recife → Natal', price: 'R$ 2.400' },
        { route: 'Rio → Vitória', price: 'R$ 1.750' }
    ];
    
    const feed = document.getElementById('freightsFeed');
    let currentIndex = 0;
    
    // Adicionar fretes iniciais
    freights.slice(0, 3).forEach(freight => {
        addFreightToFeed(freight);
    });
    
    // Simular novos fretes em tempo real
    setInterval(() => {
        if (currentIndex < freights.length) {
            addFreightToFeed(freights[currentIndex]);
            currentIndex++;
            
            // Manter máximo de 4 fretes no feed
            if (feed.children.length > 4) {
                feed.removeChild(feed.children[0]);
            }
        }
    }, 5000);
}

function addFreightToFeed(freight) {
    const feed = document.getElementById('freightsFeed');
    const freightElement = document.createElement('div');
    freightElement.className = 'freight-item';
    freightElement.style.animation = 'slideInFromRight 0.5s ease-out';
    freightElement.innerHTML = `
        <span class="freight-route">${freight.route}</span>
        <span class="freight-price">${freight.price}</span>
    `;
    
    feed.appendChild(freightElement);
    
    // Remover animação após execução
    setTimeout(() => {
        freightElement.style.animation = '';
    }, 500);
}

// Efeitos de Áudio (Opcional)
function initAudioEffects() {
    // Criar elementos de áudio para efeitos sonoros
    const clickSound = new Audio('data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQ...');
    
    // Efeito de clique no CTA
    document.querySelector('.cta-button').addEventListener('click', function(e) {
        // Tocaria som de clique aqui
        console.log('🔊 Som de clique reproduzido');
    });
}

// Efeito de Digitação (Para futuras implementações)
function typeWriter(element, text, speed = 100) {
    let i = 0;
    element.textContent = '';
    
    function type() {
        if (i < text.length) {
            element.textContent += text.charAt(i);
            i++;
            setTimeout(type, speed);
        }
    }
    
    type();
}

// Detect scroll para efeitos parallax
window.addEventListener('scroll', function() {
    const scrolled = window.pageYOffset;
    const parallaxElements = document.querySelectorAll('.floating-truck, .floating-money, .floating-star');
    
    parallaxElements.forEach(element => {
        const speed = 0.5;
        element.style.transform = `translateY(${scrolled * speed}px)`;
    });
});