// ============================================
// MENU MOBILE
// ============================================
const menuToggle = document.getElementById('menuToggle');
const navMenu = document.getElementById('navMenu');
const navLinks = document.querySelectorAll('.nav-link');

if (menuToggle && navMenu) {
    menuToggle.addEventListener('click', () => {
        navMenu.classList.toggle('active');
        menuToggle.classList.toggle('active');
        document.body.style.overflow = navMenu.classList.contains('active') ? 'hidden' : '';
    });

    // Fechar menu ao clicar em um link
    navLinks.forEach(link => {
        link.addEventListener('click', () => {
            navMenu.classList.remove('active');
            menuToggle.classList.remove('active');
            document.body.style.overflow = '';
        });
    });

    // Fechar menu ao clicar fora
    document.addEventListener('click', (e) => {
        if (!navMenu.contains(e.target) && !menuToggle.contains(e.target)) {
            navMenu.classList.remove('active');
            menuToggle.classList.remove('active');
            document.body.style.overflow = '';
        }
    });
}

// ============================================
// HEADER SCROLL EFFECT
// ============================================
const header = document.getElementById('header');
let lastScroll = 0;

window.addEventListener('scroll', () => {
    const currentScroll = window.pageYOffset;
    
    if (currentScroll > 50) {
        header?.classList.add('scrolled');
    } else {
        header?.classList.remove('scrolled');
    }
    
    lastScroll = currentScroll;
});

// ============================================
// SCROLL SUAVE PARA LINKS
// ============================================
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        const href = this.getAttribute('href');
        if (href === '#') return;
        
        e.preventDefault();
        const target = document.querySelector(href);
        
        if (target) {
            const headerHeight = header?.offsetHeight || 0;
            const targetPosition = target.offsetTop - headerHeight - 20;
            
            window.scrollTo({
                top: targetPosition,
                behavior: 'smooth'
            });
        }
    });
});

// ============================================
// ANIMAÇÃO DE ENTRADA AO FAZER SCROLL
// ============================================
const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.style.opacity = '1';
            entry.target.style.transform = 'translateY(0)';
            observer.unobserve(entry.target);
        }
    });
}, observerOptions);

// Observar elementos para animação
document.addEventListener('DOMContentLoaded', () => {
    const animateElements = document.querySelectorAll(
        '.problem-item, .solution-list li, .feature-item, .testimonial-item, .logo-item'
    );
    
    animateElements.forEach((el, index) => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(30px)';
        el.style.transition = `opacity 0.6s ease-out ${index * 0.1}s, transform 0.6s ease-out ${index * 0.1}s`;
        observer.observe(el);
    });
});

// ============================================
// CARROSSEL AUTOMÁTICO DE LOGOS
// ============================================
let logoIndex = 0;
const logosCarousel = document.querySelector('.logos-carousel');

if (logosCarousel) {
    const logos = logosCarousel.querySelectorAll('.logo-item');
    let rotationInterval;
    
    function rotateLogos() {
        if (logos.length === 0) return;
        
        logos.forEach((logo, index) => {
            logo.style.opacity = '0.6';
            logo.style.transform = 'scale(0.95)';
        });
        
        logoIndex = (logoIndex + 1) % logos.length;
        logos[logoIndex].style.opacity = '1';
        logos[logoIndex].style.transform = 'scale(1)';
    }
    
    // Pausar rotação ao passar o mouse
    logosCarousel.addEventListener('mouseenter', () => {
        if (rotationInterval) {
            clearInterval(rotationInterval);
        }
    });
    
    logosCarousel.addEventListener('mouseleave', () => {
        rotationInterval = setInterval(rotateLogos, 3000);
    });
    
    // Iniciar rotação
    if (logos.length > 0) {
        logos.forEach((logo, index) => {
            logo.style.transition = 'all 0.5s ease';
            if (index === 0) {
                logo.style.opacity = '1';
                logo.style.transform = 'scale(1)';
            } else {
                logo.style.opacity = '0.6';
                logo.style.transform = 'scale(0.95)';
            }
        });
        
        rotationInterval = setInterval(rotateLogos, 3000);
    }
}

// ============================================
// MÁSCARA PARA TELEFONE
// ============================================
const telefoneInput = document.getElementById('telefone');

if (telefoneInput) {
    telefoneInput.addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        
        if (value.length <= 11) {
            if (value.length <= 10) {
                value = value.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
            } else {
                value = value.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
            }
            e.target.value = value;
        }
    });
    
    telefoneInput.addEventListener('blur', function(e) {
        const value = e.target.value.replace(/\D/g, '');
        if (value.length < 10) {
            e.target.setCustomValidity('Por favor, insira um telefone válido');
        } else {
            e.target.setCustomValidity('');
        }
    });
}

// ============================================
// MÁSCARA PARA CNPJ
// ============================================
const cnpjInput = document.getElementById('cnpj');

if (cnpjInput) {
    cnpjInput.addEventListener('input', function(e) {
        let value = e.target.value.replace(/\D/g, '');
        
        if (value.length <= 14) {
            if (value.length <= 2) {
                value = value;
            } else if (value.length <= 5) {
                value = value.replace(/(\d{2})(\d+)/, '$1.$2');
            } else if (value.length <= 8) {
                value = value.replace(/(\d{2})(\d{3})(\d+)/, '$1.$2.$3');
            } else if (value.length <= 12) {
                value = value.replace(/(\d{2})(\d{3})(\d{3})(\d+)/, '$1.$2.$3/$4');
            } else {
                value = value.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d+)/, '$1.$2.$3/$4-$5');
            }
            e.target.value = value;
        }
    });
    
    cnpjInput.addEventListener('blur', function(e) {
        const value = e.target.value.replace(/\D/g, '');
        if (value.length !== 14) {
            e.target.setCustomValidity('Por favor, insira um CNPJ válido (14 dígitos)');
        } else {
            e.target.setCustomValidity('');
        }
    });
}

// ============================================
// VALIDAÇÃO E ENVIO DO FORMULÁRIO
// ============================================
const contactForm = document.getElementById('contactForm');
let isSubmitting = false;

if (contactForm) {
    // Validação em tempo real
    const formInputs = contactForm.querySelectorAll('input, select');
    formInputs.forEach(input => {
        input.addEventListener('blur', function() {
            validateField(this);
        });
        
        input.addEventListener('input', function() {
            if (this.classList.contains('error')) {
                validateField(this);
            }
        });
    });
    
    function validateField(field) {
        const value = field.value.trim();
        let isValid = true;
        let errorMessage = '';
        
        if (field.hasAttribute('required') && !value) {
            isValid = false;
            errorMessage = 'Este campo é obrigatório';
        } else if (field.type === 'tel' && value) {
            const digits = value.replace(/\D/g, '');
            if (digits.length < 10) {
                isValid = false;
                errorMessage = 'Telefone inválido';
            }
        } else if (field.id === 'cnpj' && value) {
            const digits = value.replace(/\D/g, '');
            if (digits.length !== 14) {
                isValid = false;
                errorMessage = 'CNPJ inválido (deve conter 14 dígitos)';
            }
        } else if (field.type === 'email' && value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(value)) {
                isValid = false;
                errorMessage = 'Email inválido';
            }
        }
        
        if (isValid) {
            field.classList.remove('error');
            removeErrorMessage(field);
        } else {
            field.classList.add('error');
            showErrorMessage(field, errorMessage);
        }
        
        return isValid;
    }
    
    function showErrorMessage(field, message) {
        removeErrorMessage(field);
        const errorDiv = document.createElement('div');
        errorDiv.className = 'error-message';
        errorDiv.textContent = message;
        errorDiv.style.color = 'var(--error-red)';
        errorDiv.style.fontSize = '0.875rem';
        errorDiv.style.marginTop = '4px';
        field.parentNode.appendChild(errorDiv);
    }
    
    function removeErrorMessage(field) {
        const errorDiv = field.parentNode.querySelector('.error-message');
        if (errorDiv) {
            errorDiv.remove();
        }
    }
    
    // Se o formulário já foi enviado com sucesso (PHP), não precisa validar novamente
    const formMessage = contactForm.querySelector('.form-message.success');
    if (!formMessage) {
        // Só adiciona o listener se o formulário ainda não foi enviado
        contactForm.addEventListener('submit', function(e) {
        // Permitir submit normal do PHP se não houver JavaScript
        // O PHP processará o formulário normalmente
        
        if (isSubmitting) {
            e.preventDefault();
            return false;
        }
        
        // Validar todos os campos antes de enviar
        let formIsValid = true;
        formInputs.forEach(input => {
            if (!validateField(input)) {
                formIsValid = false;
            }
        });
        
        if (!formIsValid) {
            e.preventDefault();
            showNotification('Por favor, corrija os erros no formulário', 'error');
            return false;
        }
        
        // Se validação passou, permitir submit normal do PHP
        const submitButton = contactForm.querySelector('button[type="submit"]');
        const originalText = submitButton.textContent;
        
        isSubmitting = true;
        submitButton.textContent = 'Enviando...';
        submitButton.disabled = true;
        submitButton.style.opacity = '0.7';
        submitButton.style.cursor = 'not-allowed';
        
        // Rastrear evento de Lead no Facebook Pixel
        if (typeof fbq !== 'undefined') {
            fbq('track', 'Lead', {
                content_name: 'Solicitação de Orçamento GK2100',
                content_category: 'Formulário de Contato'
            });
            console.log('✅ Evento Lead enviado ao Facebook Pixel');
        }
        
        // O formulário será enviado normalmente para o PHP processar
    });
    }
}

// Verificar se o formulário foi enviado com sucesso (via parâmetro na URL)
if (window.location.hash.includes('success=1') || new URLSearchParams(window.location.search).get('success') === '1') {
    // Rastrear evento de conversão no Facebook Pixel
    if (typeof fbq !== 'undefined') {
        fbq('track', 'Lead', {
            content_name: 'Solicitação de Orçamento GK2100',
            content_category: 'Formulário de Contato'
        });
        console.log('✅ Evento Lead enviado ao Facebook Pixel (via URL)');
    }
}

// ============================================
// NOTIFICAÇÕES
// ============================================
function showNotification(message, type = 'success') {
    // Remover notificação existente
    const existingNotification = document.querySelector('.notification');
    if (existingNotification) {
        existingNotification.remove();
    }
    
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        background: ${type === 'success' ? 'var(--success-green)' : 'var(--error-red)'};
        color: white;
        padding: 16px 24px;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        z-index: 10000;
        animation: slideInRight 0.3s ease-out;
        max-width: 400px;
        font-weight: 500;
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease-out';
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 5000);
}

// Adicionar estilos de animação para notificações
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
    
    .form-group input.error,
    .form-group select.error {
        border-color: var(--error-red);
    }
`;
document.head.appendChild(style);

// ============================================
// ACESSIBILIDADE - FOCUS VISIBLE
// ============================================
document.querySelectorAll('a, button, input, select, textarea').forEach(element => {
    element.addEventListener('focus', function() {
        if (this.matches(':focus-visible')) {
            this.style.outline = '3px solid var(--primary)';
            this.style.outlineOffset = '2px';
        }
    });
    
    element.addEventListener('blur', function() {
        this.style.outline = '';
        this.style.outlineOffset = '';
    });
});

// ============================================
// PERFORMANCE - LAZY LOADING
// ============================================
if ('IntersectionObserver' in window) {
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                if (img.dataset.src) {
                    img.src = img.dataset.src;
                    img.removeAttribute('data-src');
                    observer.unobserve(img);
                }
            }
        });
    });
    
    document.querySelectorAll('img[data-src]').forEach(img => {
        imageObserver.observe(img);
    });
}

// ============================================
// PREVENIR COMPORTAMENTO PADRÃO DE FORMULÁRIO
// ============================================
document.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'BUTTON') {
        const form = e.target.closest('form');
        if (form && form.id === 'contactForm') {
            // Permitir submit apenas se o campo atual for válido
            if (e.target.hasAttribute('required') && !e.target.value.trim()) {
                e.preventDefault();
            }
        }
    }
});

// ============================================
// PARTÍCULAS NO HERO (FORA DA CURVA)
// ============================================
function initParticles() {
    const canvas = document.getElementById('particlesCanvas');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    
    const particles = [];
    const particleCount = 50;
    
    class Particle {
        constructor() {
            this.x = Math.random() * canvas.width;
            this.y = Math.random() * canvas.height;
            this.size = Math.random() * 3 + 1;
            this.speedX = Math.random() * 2 - 1;
            this.speedY = Math.random() * 2 - 1;
            this.opacity = Math.random() * 0.5 + 0.2;
        }
        
        update() {
            this.x += this.speedX;
            this.y += this.speedY;
            
            if (this.x > canvas.width || this.x < 0) this.speedX *= -1;
            if (this.y > canvas.height || this.y < 0) this.speedY *= -1;
        }
        
        draw() {
            ctx.fillStyle = `rgba(37, 99, 235, ${this.opacity})`;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
        }
    }
    
    for (let i = 0; i < particleCount; i++) {
        particles.push(new Particle());
    }
    
    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        particles.forEach(particle => {
            particle.update();
            particle.draw();
        });
        
        // Conectar partículas próximas
        particles.forEach((particle, i) => {
            particles.slice(i + 1).forEach(otherParticle => {
                const dx = particle.x - otherParticle.x;
                const dy = particle.y - otherParticle.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance < 150) {
                    ctx.strokeStyle = `rgba(37, 99, 235, ${0.2 * (1 - distance / 150)})`;
                    ctx.lineWidth = 1;
                    ctx.beginPath();
                    ctx.moveTo(particle.x, particle.y);
                    ctx.lineTo(otherParticle.x, otherParticle.y);
                    ctx.stroke();
                }
            });
        });
        
        requestAnimationFrame(animate);
    }
    
    animate();
    
    window.addEventListener('resize', () => {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    });
}

// ============================================
// CONTADORES ANIMADOS
// ============================================
function animateCounter(element, target, duration = 2000) {
    const start = 0;
    const increment = target / (duration / 16);
    let current = start;
    
    const timer = setInterval(() => {
        current += increment;
        if (current >= target) {
            element.textContent = target + (element.dataset.suffix || '');
            clearInterval(timer);
        } else {
            element.textContent = Math.floor(current) + (element.dataset.suffix || '');
        }
    }, 16);
}

function initCounters() {
    const counters = document.querySelectorAll('.stat-number');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting && !entry.target.classList.contains('counted')) {
                entry.target.classList.add('counted');
                const target = parseInt(entry.target.dataset.target);
                animateCounter(entry.target, target);
            }
        });
    }, { threshold: 0.5 });
    
    counters.forEach(counter => observer.observe(counter));
}

// ============================================
// EFEITO 3D TILT NOS CARDS
// ============================================
function init3DTilt() {
    const cards = document.querySelectorAll('[data-tilt]');
    
    cards.forEach(card => {
        card.addEventListener('mousemove', (e) => {
            const rect = card.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const centerX = rect.width / 2;
            const centerY = rect.height / 2;
            
            const rotateX = (y - centerY) / 10;
            const rotateY = (centerX - x) / 10;
            
            card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) translateY(-8px)`;
        });
        
        card.addEventListener('mouseleave', () => {
            card.style.transform = '';
        });
    });
}

// ============================================
// PARALLAX SCROLL AVANÇADO
// ============================================
function initParallax() {
    const hero = document.querySelector('.hero');
    const machine3D = document.querySelector('.machine-3d');
    
    if (!hero || !machine3D) return;
    
    window.addEventListener('scroll', () => {
        const scrolled = window.pageYOffset;
        const heroHeight = hero.offsetHeight;
        
        if (scrolled < heroHeight) {
            const parallaxValue = scrolled * 0.5;
            hero.style.transform = `translateY(${parallaxValue}px)`;
            
            if (machine3D) {
                const rotateY = scrolled * 0.1;
                machine3D.style.transform = `translateY(${parallaxValue * 0.3}px) rotateY(${rotateY}deg)`;
            }
        }
    });
}

// ============================================
// ANIMAÇÃO DE TEXTO REVELADO
// ============================================
function initTextReveal() {
    const reveals = document.querySelectorAll('.headline-line, .headline-highlight');
    
    reveals.forEach((element, index) => {
        element.style.animationDelay = `${index * 0.1}s`;
    });
}

// ============================================
// EFEITO DE GLOW NO HOVER DA MÁQUINA
// ============================================
function initMachineGlow() {
    const machineContainer = document.querySelector('.machine-3d-container');
    const machine = document.querySelector('.machine-3d');
    
    if (!machineContainer || !machine) return;
    
    machineContainer.addEventListener('mousemove', (e) => {
        const rect = machineContainer.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        const centerX = rect.width / 2;
        const centerY = rect.height / 2;
        
        const rotateX = (y - centerY) / 20;
        const rotateY = (centerX - x) / 20;
        
        machine.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) translateY(-20px)`;
    });
    
    machineContainer.addEventListener('mouseleave', () => {
        machine.style.transform = '';
    });
}

// ============================================
// ANIMAÇÕES DE ENTRADA AVANÇADAS
// ============================================
function initAdvancedAnimations() {
    const solutionCards = document.querySelectorAll('.solution-card');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                setTimeout(() => {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0) rotateX(0)';
                }, index * 100);
            }
        });
    }, { threshold: 0.1 });
    
    solutionCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(50px) rotateX(10deg)';
        card.style.transition = 'all 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
        observer.observe(card);
    });
}

// ============================================
// PARTÍCULAS PARA FEATURES SECTION
// ============================================
function initFeaturesParticles() {
    const canvas = document.getElementById('featuresCanvas');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    const section = document.querySelector('.features');
    if (!section) return;
    
    canvas.width = section.offsetWidth;
    canvas.height = section.offsetHeight;
    
    const particles = [];
    const particleCount = 30;
    
    class FeatureParticle {
        constructor() {
            this.x = Math.random() * canvas.width;
            this.y = Math.random() * canvas.height;
            this.size = Math.random() * 2 + 1;
            this.speedX = (Math.random() - 0.5) * 0.5;
            this.speedY = (Math.random() - 0.5) * 0.5;
            this.opacity = Math.random() * 0.3 + 0.1;
        }
        
        update() {
            this.x += this.speedX;
            this.y += this.speedY;
            
            if (this.x > canvas.width || this.x < 0) this.speedX *= -1;
            if (this.y > canvas.height || this.y < 0) this.speedY *= -1;
        }
        
        draw() {
            ctx.fillStyle = `rgba(37, 99, 235, ${this.opacity})`;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
        }
    }
    
    for (let i = 0; i < particleCount; i++) {
        particles.push(new FeatureParticle());
    }
    
    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        particles.forEach(particle => {
            particle.update();
            particle.draw();
        });
        
        requestAnimationFrame(animate);
    }
    
    animate();
    
    window.addEventListener('resize', () => {
        canvas.width = section.offsetWidth;
        canvas.height = section.offsetHeight;
    });
}

// ============================================
// EFEITO 3D TILT PARA FEATURE CARDS
// ============================================
function initFeatureTilt() {
    const featureCards = document.querySelectorAll('[data-tilt-feature]');
    
    featureCards.forEach(card => {
        card.addEventListener('mousemove', (e) => {
            const rect = card.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const centerX = rect.width / 2;
            const centerY = rect.height / 2;
            
            const rotateX = (y - centerY) / 15;
            const rotateY = (centerX - x) / 15;
            
            const inner = card.querySelector('.feature-card-inner');
            if (inner) {
                inner.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) translateY(-12px)`;
            }
        });
        
        card.addEventListener('mouseleave', () => {
            const inner = card.querySelector('.feature-card-inner');
            if (inner) {
                inner.style.transform = '';
            }
        });
    });
}

// ============================================
// ANIMAÇÃO DE ENTRADA DOS FEATURE CARDS
// ============================================
function initFeatureCardsAnimation() {
    const featureCards = document.querySelectorAll('.feature-card');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                setTimeout(() => {
                    entry.target.classList.add('visible');
                }, index * 100);
            }
        });
    }, { 
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });
    
    featureCards.forEach(card => {
        observer.observe(card);
    });
}

// ============================================
// EFEITO DE PARTÍCULAS NOS NÚMEROS
// ============================================
function initFeatureNumberParticles() {
    const featureCards = document.querySelectorAll('.feature-card');
    
    featureCards.forEach(card => {
        card.addEventListener('mouseenter', () => {
            const particles = card.querySelector('.feature-number-particles');
            if (!particles) return;
            
            // Criar partículas dinâmicas
            for (let i = 0; i < 5; i++) {
                setTimeout(() => {
                    const particle = document.createElement('div');
                    particle.style.cssText = `
                        position: absolute;
                        width: 4px;
                        height: 4px;
                        background: var(--primary);
                        border-radius: 50%;
                        top: 50%;
                        left: 50%;
                        pointer-events: none;
                        animation: particleExplode 1s ease-out forwards;
                    `;
                    particles.appendChild(particle);
                    
                    setTimeout(() => particle.remove(), 1000);
                }, i * 100);
            }
        });
    });
}

// Adicionar animação de partículas explodindo
const particleStyle = document.createElement('style');
particleStyle.textContent += `
    @keyframes particleExplode {
        0% {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1) translate(0, 0);
        }
        100% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0) translate(${Math.random() * 100 - 50}px, ${Math.random() * 100 - 50}px);
        }
    }
`;
document.head.appendChild(particleStyle);

// ============================================
// EFEITO DE RIPPLE NOS CARDS
// ============================================
function initRippleEffect() {
    const featureCards = document.querySelectorAll('.feature-card');
    
    featureCards.forEach(card => {
        card.addEventListener('click', function(e) {
            const ripple = document.createElement('div');
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            ripple.style.cssText = `
                position: absolute;
                width: 0;
                height: 0;
                border-radius: 50%;
                background: rgba(37, 99, 235, 0.3);
                top: ${y}px;
                left: ${x}px;
                transform: translate(-50%, -50%);
                pointer-events: none;
                animation: rippleExpand 0.6s ease-out;
            `;
            
            const inner = this.querySelector('.feature-card-inner');
            if (inner) {
                inner.appendChild(ripple);
                setTimeout(() => ripple.remove(), 600);
            }
        });
    });
}

// Adicionar animação de ripple
const rippleStyle = document.createElement('style');
rippleStyle.textContent += `
    @keyframes rippleExpand {
        0% {
            width: 0;
            height: 0;
            opacity: 0.6;
        }
        100% {
            width: 300px;
            height: 300px;
            opacity: 0;
        }
    }
`;
document.head.appendChild(rippleStyle);

// ============================================
// EFEITO 3D TILT PARA PROBLEM CARDS
// ============================================
function initProblemTilt() {
    const problemCards = document.querySelectorAll('.problem-card');
    
    problemCards.forEach(card => {
        card.addEventListener('mousemove', (e) => {
            const rect = card.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const centerX = rect.width / 2;
            const centerY = rect.height / 2;
            
            const rotateX = (y - centerY) / 20;
            const rotateY = (centerX - x) / 20;
            
            const inner = card.querySelector('.problem-card-inner');
            if (inner) {
                inner.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) translateY(-12px)`;
            }
        });
        
        card.addEventListener('mouseleave', () => {
            const inner = card.querySelector('.problem-card-inner');
            if (inner) {
                inner.style.transform = '';
            }
        });
    });
}

// ============================================
// ANIMAÇÃO DE ENTRADA DOS PROBLEM CARDS
// ============================================
function initProblemCardsAnimation() {
    const problemCards = document.querySelectorAll('.problem-card');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0) scale(1)';
            }
        });
    }, { 
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });
    
    problemCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(30px) scale(0.95)';
        card.style.transition = `opacity 0.6s ease-out ${index * 0.1}s, transform 0.6s ease-out ${index * 0.1}s`;
        observer.observe(card);
    });
}

// ============================================
// CALCULADORA ECONOMIA DE FILME (PRÉ-ESTIRO 450%)
// ============================================
function initFilmEconomyCalculator() {
    const root = document.getElementById('filmEconomyCalculator');
    if (!root) return;

    const inputEl = document.getElementById('filmKgMonthInput');
    const btnEl = document.getElementById('filmEconomyCalcBtn');
    const resultsEl = document.getElementById('filmEconomyResults');
    const errorEl = document.getElementById('filmEconomyError');

    const newConsEl = document.getElementById('filmNewConsumptionKg');
    const currentConsEl = document.getElementById('filmCurrentConsumptionKg');
    const economyKgEl = document.getElementById('filmEconomyKg');
    const reductionPctEl = document.getElementById('filmReductionPct'); // opcional (card pode ser removido)

    if (!inputEl || !btnEl || !resultsEl || !errorEl || !newConsEl || !currentConsEl || !economyKgEl) {
        return;
    }

    // Raciocínio do usuário:
    // Manual: 800g (0,8kg) por pallet stretchado
    // Máquina: 280g (0,28kg) por pallet
    const avgManualKgPerPallet = 0.8;
    const avgMachineKgPerPallet = 0.28;
    const parseNumberPt = (value) => {
        const raw = String(value ?? '').trim();
        // Remove separador de milhar e converte vírgula decimal para ponto
        const normalized = raw.replace(/\./g, '').replace(',', '.');
        const n = parseFloat(normalized);
        return n;
    };

    const formatKg1 = (n) => {
        // Usar ponto decimal para ficar igual ao layout do print
        return `${Number(n).toLocaleString('en-US', {
            minimumFractionDigits: 1,
            maximumFractionDigits: 1
        })}kg`;
    };

    const formatPct1 = (n) => {
        return `${Number(n).toLocaleString('en-US', {
            minimumFractionDigits: 1,
            maximumFractionDigits: 1
        })}%`;
    };

    function compute() {
        const currentKg = parseNumberPt(inputEl.value);

        if (!Number.isFinite(currentKg) || currentKg <= 0) {
            errorEl.textContent = 'Informe um valor de kg/mês maior do que 0.';
            errorEl.style.display = 'block';
            resultsEl.style.display = 'none';
            return;
        }

        // Converte consumo atual (kg) para equivalência em pallets (pela regra manual 0,8kg/pallet)
        const palletsEquiv = currentKg / avgManualKgPerPallet;
        // Consumo da máquina no mesmo volume de pallets (0,28kg/pallet)
        const newConsumptionKg = palletsEquiv * avgMachineKgPerPallet;
        // Economia = consumo atual - consumo na máquina
        const economyKg = currentKg - newConsumptionKg;
        const reductionPct = (economyKg / currentKg) * 100;

        currentConsEl.textContent = formatKg1(currentKg);
        newConsEl.textContent = formatKg1(newConsumptionKg);
        economyKgEl.textContent = formatKg1(economyKg);
        // Se o card de porcentagem existir, atualiza.
        if (reductionPctEl) {
            reductionPctEl.textContent = formatPct1(reductionPct);
        }

        errorEl.style.display = 'none';
        resultsEl.style.display = 'block';
    }

    btnEl.addEventListener('click', compute);
    inputEl.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            compute();
        }
    });
}

// ============================================
// VÍDEO CURTO DOS DEPOIMENTOS (YOUTUBE SHORTS)
// ============================================
function initTestimonialsShortsVideo() {
    const iframe = document.getElementById('testimonialsShortsIframe');
    const muteBtn = document.getElementById('testimonialsMuteBtn');
    const pauseBtn = document.getElementById('testimonialsPauseBtn');
    if (!iframe || !muteBtn) return;

    const videoId = '94YNZI8dyc8';
    let isMuted = true; // Por padrão, o autoplay funciona melhor com mute ativo

    const baseUrl = `https://www.youtube.com/embed/${videoId}?autoplay=1&mute=1&modestbranding=1&rel=0&controls=0&showinfo=0&fs=0&cc_load_policy=0&iv_load_policy=3&playsinline=1&disablekb=1&loop=1&playlist=${videoId}&autohide=1&disable_polymer=1&enablejsapi=1&vq=hd1080`;

    let testimonialsPlayer = null;
    let playerReady = false;

    function setMuteUI(nextMuted) {
        isMuted = !!nextMuted;
        muteBtn.textContent = isMuted ? 'Som: mutado' : 'Som: ativado';
        muteBtn.setAttribute('aria-pressed', isMuted ? 'true' : 'false');

        if (isMuted) {
            muteBtn.classList.remove('is-unmuted');
        } else {
            muteBtn.classList.add('is-unmuted');
        }
    }

    function applyMute(nextMuted) {
        setMuteUI(nextMuted);

        // Se o Player API estiver pronto, use mute/unmute sem recarregar o iframe
        if (testimonialsPlayer && playerReady) {
            if (isMuted) testimonialsPlayer.mute();
            else testimonialsPlayer.unMute();
            return;
        }

        // Fallback: troca do parâmetro no src (mantém o comportamento antigo)
        const muteParam = isMuted ? 1 : 0;
        iframe.src = baseUrl.replace(/mute=\d+/, `mute=${muteParam}`);
    }

    function setPauseUI(isPlaying) {
        if (!pauseBtn) return;
        const playing = !!isPlaying;
        pauseBtn.textContent = playing ? 'Pausar' : 'Reproduzir';
        pauseBtn.setAttribute('aria-pressed', playing ? 'true' : 'false');
    }

    // Mantém a máscara ativa para esconder os overlays do YouTube no início (e durante todo o tempo).
    const topMask = document.getElementById('testimonialsTopMask');
    if (topMask) topMask.classList.remove('is-hidden');

    if (pauseBtn) pauseBtn.disabled = true;

    function loadYouTubeIframeAPI() {
        if (window.YT && window.YT.Player) return Promise.resolve();
        if (window.__gimakTestimonialsApiPromise) return window.__gimakTestimonialsApiPromise;

        window.__gimakTestimonialsApiPromise = new Promise((resolve) => {
            const prev = window.onYouTubeIframeAPIReady;
            window.onYouTubeIframeAPIReady = function () {
                try {
                    if (typeof prev === 'function') prev();
                } catch (e) {
                    // ignora
                }
                resolve();
            };

            const tag = document.createElement('script');
            tag.src = 'https://www.youtube.com/iframe_api';
            document.head.appendChild(tag);
        });

        return window.__gimakTestimonialsApiPromise;
    }

    function createPlayerWhenReady() {
        if (!window.YT || !window.YT.Player) return;

        testimonialsPlayer = new window.YT.Player('testimonialsShortsIframe', {
            events: {
                onReady: () => {
                    playerReady = true;
                    if (pauseBtn) pauseBtn.disabled = false;

                    // Estado inicial consistente
                    applyMute(true);

                    // Tenta iniciar em 1080p quando disponível
                    try {
                        if (typeof testimonialsPlayer.setPlaybackQuality === 'function') {
                            testimonialsPlayer.setPlaybackQuality('hd1080');
                        }
                    } catch (e) {
                        // ignora (quando a qualidade não estiver disponível)
                    }

                    // UI inicial do botão Pausar
                    const st = testimonialsPlayer.getPlayerState?.();
                    const isPlaying = st === window.YT.PlayerState.PLAYING;
                    setPauseUI(isPlaying);
                },
                onStateChange: (event) => {
                    if (!pauseBtn || !window.YT) return;
                    const st = event.data;
                    const isPlaying = st === window.YT.PlayerState.PLAYING;
                    const isPaused = st === window.YT.PlayerState.PAUSED || st === window.YT.PlayerState.ENDED;
                    if (isPlaying) setPauseUI(true);
                    if (isPaused) setPauseUI(false);
                }
            }
        });
    }

    loadYouTubeIframeAPI()
        .then(() => createPlayerWhenReady())
        .catch(() => {
            // Sem API, fica apenas com mute via src. Pausar fica inativo.
            if (pauseBtn) pauseBtn.disabled = true;
            applyMute(true);
        });

    muteBtn.addEventListener('click', (e) => {
        e.preventDefault();
        applyMute(!isMuted);
    });

    if (pauseBtn) {
        pauseBtn.addEventListener('click', (e) => {
            e.preventDefault();
            if (!testimonialsPlayer || !playerReady) return;
            const st = testimonialsPlayer.getPlayerState?.();
            const isPlaying = window.YT && st === window.YT.PlayerState.PLAYING;
            if (isPlaying) testimonialsPlayer.pauseVideo();
            else testimonialsPlayer.playVideo();
        });
    }
}

// ============================================
// WIDGET DE WHATSAPP (SEM FORMULÁRIO)
// ============================================
function initWhatsAppContactWidget() {
    const link = document.getElementById('whatsappContactLink');
    if (!link) return;

    const previewEl = document.getElementById('whatsPreview');

    const chips = document.querySelectorAll('[data-whats-topic]');
    if (!chips || chips.length === 0) return;

    const number = link.dataset.whatsNumber || '';
    if (!number) return;

    const activeChip = document.querySelector('.whats-chip.is-active') || chips[0];

    function buildMessage(topic) {
        const safeTopic = topic ? topic.trim() : 'Orçamento';
        return `Olá! Tenho interesse na GK2100. Assunto: ${safeTopic}. Pode me passar informações e valores?`;
    }

    function setActiveTopic(topic) {
        chips.forEach(chip => {
            const isActive = chip.dataset.whatsTopic === topic;
            chip.classList.toggle('is-active', isActive);
        });

        const message = buildMessage(topic);
        link.href = `https://wa.me/${number}?text=${encodeURIComponent(message)}`;

        if (previewEl) {
            const safeTopic = topic ? topic.trim() : 'Orçamento';
            previewEl.textContent = `Mensagem pronta: ${safeTopic}`;
        }
    }

    chips.forEach(chip => {
        chip.addEventListener('click', () => {
            const topic = chip.dataset.whatsTopic;
            if (topic) setActiveTopic(topic);
        });
    });

    if (activeChip && activeChip.dataset && activeChip.dataset.whatsTopic) {
        setActiveTopic(activeChip.dataset.whatsTopic);
    }
}

// ============================================
// INICIALIZAÇÃO COMPLETA
// ============================================
document.addEventListener('DOMContentLoaded', () => {
    console.log('🚀 Landing Page GK2100 GIMAK - Versão Premium carregada!');
    
    // Inicializar todos os efeitos
    initParticles();
    initCounters();
    init3DTilt();
    initParallax();
    initTextReveal();
    initMachineGlow();
    initAdvancedAnimations();
    
    // Inicializar efeitos das features
    initFeaturesParticles();
    initFeatureTilt();
    initFeatureCardsAnimation();
    initFeatureNumberParticles();
    initRippleEffect();
    
    // Inicializar efeitos dos problemas
    initProblemTilt();
    initProblemCardsAnimation();
    
    // Adicionar classe loaded ao body
    document.body.classList.add('loaded');
    
    // Adicionar efeito de cursor personalizado (opcional)
    const cursor = document.createElement('div');
    cursor.className = 'custom-cursor';
    document.body.appendChild(cursor);
    
    document.addEventListener('mousemove', (e) => {
        cursor.style.left = e.clientX + 'px';
        cursor.style.top = e.clientY + 'px';
    });
    
    // Inicializar calculadora de economia (pré-estiro 450%)
    initFilmEconomyCalculator();

    // Inicializar vídeo dos depoimentos (YouTube Shorts)
    initTestimonialsShortsVideo();
    
    // Inicializar animações ao scroll
    initScrollAnimations();
    
    // Inicializar interatividade dos cards
    initCardInteractions();
    
    // Inicializar FAQ Accordion
    initFAQAccordion();

    // Inicializar widget de contato no WhatsApp
    initWhatsAppContactWidget();
    
    // Inicializar Carrossel de Logos
    initLogosCarousel();
    
    // Inicializar Carrossel de Países
    initCountriesCarousel();
    
    // Inicializar contadores dos cards flutuantes do hero
    initFloatingCardCounters();
    
    // Inicializar vídeo customizado
    initCustomVideo();
});

// ============================================
// FAQ ACCORDION INTERATIVO
// ============================================
function initFAQAccordion() {
    const faqItems = document.querySelectorAll('.faq-item');
    
    if (faqItems.length === 0) {
        console.warn('Nenhum item FAQ encontrado');
        return;
    }
    
    faqItems.forEach((item, index) => {
        const button = item.querySelector('.faq-question-btn');
        const answerWrapper = item.querySelector('.faq-answer-wrapper');
        
        if (!button || !answerWrapper) {
            console.warn(`Item FAQ ${index} não possui botão ou resposta`);
            return;
        }
        
        // Prevenir comportamento padrão
        button.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            
            const isActive = item.classList.contains('active');
            
            // Toggle do item atual
            if (isActive) {
                item.classList.remove('active');
                button.setAttribute('aria-expanded', 'false');
            } else {
                item.classList.add('active');
                button.setAttribute('aria-expanded', 'true');
            }
        });
        
        // Adicionar suporte para teclado
        button.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                button.click();
            }
        });
    });
    
    console.log(`✅ FAQ Accordion inicializado com ${faqItems.length} itens`);
}

// ============================================
// CARROSSEL DE LOGOS AUTOMÁTICO
// ============================================
function initLogosCarousel() {
    const carousel = document.getElementById('logosCarousel');
    const track = carousel?.querySelector('.carousel-track');
    const indicators = document.querySelectorAll('.indicator');
    const logoItems = document.querySelectorAll('.logo-item');
    
    if (!carousel || !track || logoItems.length === 0) return;
    
    let currentSlide = 0;
    const totalSlides = 3; // 3 grupos de 2 logos
    const slideInterval = 2000; // 2 segundos
    const logosPerSlide = 2;
    
    // Calcular largura do slide baseado no elemento real
    const firstLogo = logoItems[0];
    if (!firstLogo) return;
    
    const logoWidth = firstLogo.offsetWidth || 180;
    const gap = parseInt(getComputedStyle(track).gap) || 32;
    const slideWidth = (logoWidth + gap) * logosPerSlide;
    
    let autoSlideInterval;
    let isPaused = false;
    
    function updateCarousel() {
        // Atualizar posição do track
        const translateX = -(currentSlide * slideWidth);
        track.style.transform = `translateX(${translateX}px)`;
        
        // Atualizar indicadores
        indicators.forEach((indicator, index) => {
            if (index === currentSlide) {
                indicator.classList.add('active');
            } else {
                indicator.classList.remove('active');
            }
        });
        
        // Atualizar logos ativos (mostrar 2 por vez)
        logoItems.forEach((item, index) => {
            const startIndex = currentSlide * logosPerSlide;
            const endIndex = startIndex + logosPerSlide;
            
            if (index >= startIndex && index < endIndex) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });
    }
    
    function nextSlide() {
        if (isPaused) return;
        
        currentSlide = (currentSlide + 1) % totalSlides;
        updateCarousel();
    }
    
    function goToSlide(slideIndex) {
        currentSlide = slideIndex;
        updateCarousel();
        resetAutoSlide();
    }
    
    function resetAutoSlide() {
        clearInterval(autoSlideInterval);
        if (!isPaused) {
            autoSlideInterval = setInterval(nextSlide, slideInterval);
        }
    }
    
    // Adicionar eventos aos indicadores
    indicators.forEach((indicator, index) => {
        indicator.addEventListener('click', () => goToSlide(index));
    });
    
    // Pausar carrossel ao passar o mouse
    carousel.addEventListener('mouseenter', () => {
        isPaused = true;
        clearInterval(autoSlideInterval);
    });
    
    carousel.addEventListener('mouseleave', () => {
        isPaused = false;
        resetAutoSlide();
    });
    
    // Aguardar carregamento completo antes de inicializar
    window.addEventListener('load', () => {
        updateCarousel();
        resetAutoSlide();
    });
    
    // Inicializar imediatamente também
    setTimeout(() => {
        updateCarousel();
        resetAutoSlide();
    }, 100);
}

// ============================================
// CARROSSEL DE PAÍSES
// ============================================
function initCountriesCarousel() {
    const carousel = document.getElementById('countriesCarousel');
    if (!carousel) return;
    
    const countryItems = carousel.querySelectorAll('.country-item');
    if (countryItems.length === 0) return;
    
    // Duplicar países para loop infinito
    countryItems.forEach(item => {
        const clone = item.cloneNode(true);
        carousel.appendChild(clone);
    });
    
    let position = 0;
    let isPaused = false;
    let animationId = null;
    
    // Calcular largura real do item
    const firstItem = countryItems[0];
    const itemWidth = firstItem.offsetWidth + parseInt(getComputedStyle(carousel).gap) || 140 + 24;
    const totalWidth = itemWidth * countryItems.length;
    
    function animate() {
        if (isPaused) return;
        
        position -= 0.5; // velocidade do scroll
        
        // Reset quando chegar ao final (metade porque duplicamos)
        if (Math.abs(position) >= totalWidth) {
            position = 0;
        }
        
        carousel.style.transform = `translateX(${position}px)`;
        animationId = requestAnimationFrame(animate);
    }
    
    // Pausar ao passar o mouse
    const wrapper = carousel.closest('.countries-carousel-wrapper');
    if (wrapper) {
        wrapper.addEventListener('mouseenter', () => {
            isPaused = true;
        });
        
        wrapper.addEventListener('mouseleave', () => {
            isPaused = false;
            if (!animationId) {
                animate();
            }
        });
    }
    
    // Iniciar animação
    animate();
}

// ============================================
// CALCULADORA DE ECONOMIA
// ============================================

// ============================================
// ANIMAÇÕES AO SCROLL
// ============================================
function initScrollAnimations() {
    // Observar seções principais
    const sections = document.querySelectorAll('section');
    sections.forEach(section => {
        section.classList.add('animate-in');
    });
    
    const sectionObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });

    sections.forEach(section => {
        sectionObserver.observe(section);
    });
    
    // Mostrar primeira seção imediatamente
    if (sections.length > 0) {
        sections[0].classList.add('visible');
    }

    // Observar cards de problemas
    const problemCards = document.querySelectorAll('.problem-card');
    problemCards.forEach(card => {
        card.classList.add('animate-in');
    });
    
    const problemObserver = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                setTimeout(() => {
                    entry.target.classList.add('visible');
                }, index * 100);
            }
        });
    }, {
        threshold: 0.2,
        rootMargin: '0px 0px -50px 0px'
    });

    problemCards.forEach(card => {
        problemObserver.observe(card);
    });

    // Observar cards de solução
    const solutionCards = document.querySelectorAll('.solution-card');
    solutionCards.forEach(card => {
        card.classList.add('animate-in');
    });
    
    const solutionObserver = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                setTimeout(() => {
                    entry.target.classList.add('visible');
                }, index * 150);
            }
        });
    }, {
        threshold: 0.2,
        rootMargin: '0px 0px -50px 0px'
    });

    solutionCards.forEach(card => {
        solutionObserver.observe(card);
    });

    // Observar feature cards
    const featureCards = document.querySelectorAll('.feature-card');
    featureCards.forEach(card => {
        card.classList.add('animate-in');
    });
    
    const featureObserver = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                setTimeout(() => {
                    entry.target.classList.add('visible');
                }, index * 100);
            }
        });
    }, {
        threshold: 0.2,
        rootMargin: '0px 0px -50px 0px'
    });

    featureCards.forEach(card => {
        featureObserver.observe(card);
    });

    // Observar depoimentos
    const testimonialItems = document.querySelectorAll('.testimonial-item');
    testimonialItems.forEach(item => {
        item.classList.add('animate-in');
    });
    
    const testimonialObserver = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                setTimeout(() => {
                    entry.target.classList.add('visible');
                }, index * 150);
            }
        });
    }, {
        threshold: 0.2,
        rootMargin: '0px 0px -50px 0px'
    });

    testimonialItems.forEach(item => {
        testimonialObserver.observe(item);
    });
}

// ============================================
// INTERATIVIDADE DOS CARDS
// ============================================
function initCardInteractions() {
    // Efeito de ripple nos cards
    const cards = document.querySelectorAll('.problem-card, .solution-card, .feature-card, .testimonial-item');
    
    cards.forEach(card => {
        card.addEventListener('click', function(e) {
            const ripple = document.createElement('span');
            const rect = this.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = e.clientX - rect.left - size / 2;
            const y = e.clientY - rect.top - size / 2;
            
            ripple.style.cssText = `
                position: absolute;
                width: ${size}px;
                height: ${size}px;
                border-radius: 50%;
                background: rgba(0, 0, 0, 0.1);
                left: ${x}px;
                top: ${y}px;
                pointer-events: none;
                transform: scale(0);
                animation: ripple 0.6s ease-out;
            `;
            
            const inner = this.querySelector('.problem-card-inner, .solution-card-inner, .feature-card-inner');
            if (inner) {
                inner.style.position = 'relative';
                inner.appendChild(ripple);
                
                setTimeout(() => {
                    ripple.remove();
                }, 600);
            }

            // Interacao "fora da curva" - revelar insight no card de problemas
            if (this.classList && this.classList.contains('problem-card')) {
                const innerProblem = this.querySelector('.problem-card-inner');
                if (innerProblem) {
                    const details = {
                        1: {
                            tag: 'Impacto no dia a dia',
                            text: 'O filme “compensa” pequenas imperfeicoes do processo e vira desperdicio invisivel.',
                            action: 'Proxima acao: automatize a pre-ajuste do envolvimento para reduzir variabilidade.'
                        },
                        2: {
                            tag: 'Efeito na produtividade',
                            text: 'Quando o envolvimento depende de operacao manual, o tempo de ajuste e setup se acumula no turno.',
                            action: 'Proxima acao: padronize e semiautomatize o ciclo para cortar atrasos.'
                        },
                        3: {
                            tag: 'Risco de seguranca',
                            text: 'Sem padrao consistente, a amarração muda de pallet para pallet e aumenta a chance de falha durante transporte.',
                            action: 'Proxima acao: envolvimento uniforme com processo controlado.'
                        },
                        4: {
                            tag: 'Perdas que somam',
                            text: 'Custos ocultos aparecem no final: retrabalho, reposicao e refugos que nao aparecem na linha principal.',
                            action: 'Proxima acao: reduza perdas com processo mais estavel e economia de filme.'
                        },
                        5: {
                            tag: 'Efeito humano',
                            text: 'Fadiga reduz atencao e aumenta retrabalho: mais tempo gasto para “corrigir” o que ja saiu errado.',
                            action: 'Proxima acao: diminua esforço e varie menos com automacao do envolvimento.'
                        },
                        6: {
                            tag: 'Exposicao a avarias',
                            text: 'Tensao inadequada e falhas de amarração elevam avarias e devolucoes no transporte.',
                            action: 'Proxima acao: envolvimento firme e repetivel (GK2100) para proteger carga.'
                        }
                    };

                    const problemId = this.getAttribute('data-problem');
                    const current = details[problemId] || details[1];

                    const isExpanded = innerProblem.classList.contains('is-expanded');
                    // Fecha outros cards abertos para manter o layout limpo
                    document.querySelectorAll('.problem-card-inner.is-expanded').forEach(other => {
                        if (other !== innerProblem) other.classList.remove('is-expanded');
                    });

                    innerProblem.classList.toggle('is-expanded', !isExpanded);

                    // Gera o bloco de insight apenas quando precisa
                    let extra = innerProblem.querySelector('.problem-extra');
                    if (!extra) {
                        extra = document.createElement('div');
                        extra.className = 'problem-extra';
                        extra.innerHTML = `
                            <div class="problem-extra-title">👀 ${current.tag}</div>
                            <div class="problem-extra-text">${current.text}</div>
                            <div class="problem-extra-action"><strong>Próxima ação:</strong> ${current.action.replace('Proxima acao: ', '')}</div>
                        `;
                        // Garantir que fica apos o texto principal
                        innerProblem.appendChild(extra);
                    } else {
                        // Atualizar conteudo (caso o usuario clique em outro problema)
                        extra.querySelector('.problem-extra-title') && (extra.querySelector('.problem-extra-title').textContent = `👀 ${current.tag}`);
                        extra.querySelector('.problem-extra-text') && (extra.querySelector('.problem-extra-text').textContent = current.text);
                        const actionEl = extra.querySelector('.problem-extra-action');
                        if (actionEl) {
                            actionEl.innerHTML = `<strong>Próxima ação:</strong> ${current.action.replace('Proxima acao: ', '')}`;
                        }
                    }
                }
            }
        });
    });

    // Adicionar animação de ripple ao CSS
    if (!document.getElementById('ripple-animation')) {
        const style = document.createElement('style');
        style.id = 'ripple-animation';
        style.textContent = `
            @keyframes ripple {
                to {
                    transform: scale(2);
                    opacity: 0;
                }
            }
        `;
        document.head.appendChild(style);
    }

    // Efeito parallax suave no hero
    const hero = document.querySelector('.hero');
    if (hero) {
        window.addEventListener('scroll', () => {
            const scrolled = window.pageYOffset;
            const heroHeight = hero.offsetHeight;
            
            if (scrolled < heroHeight) {
                const parallaxValue = scrolled * 0.3;
                hero.style.transform = `translateY(${parallaxValue}px)`;
            }
        });
    }
}

// ============================================
// CONTADORES DOS CARDS FLUTUANTES DO HERO
// ============================================
function initFloatingCardCounters() {
    console.log('🔢 Inicializando contadores dos cards flutuantes...');
    
    function animateCounter(element, target) {
        if (!element || !target) return;
        
        const duration = 2000;
        const steps = 60;
        const increment = target / steps;
        let current = 0;
        let step = 0;
        
        element.textContent = '0';
        
        const timer = setInterval(() => {
            step++;
            current = increment * step;
            
            if (current >= target || step >= steps) {
                element.textContent = formatStatNumber(target);
                clearInterval(timer);
            } else {
                element.textContent = formatStatNumber(Math.floor(current));
            }
        }, duration / steps);
    }
    
    function setupCounters() {
        // Tentar encontrar os elementos
        let stats = document.querySelectorAll('.floating-card .stat-number[data-target]');
        
        if (stats.length === 0) {
            stats = document.querySelectorAll('.stat-number[data-target]');
        }
        
        console.log('📊 Elementos encontrados:', stats.length);
        
        if (stats.length > 0) {
            stats.forEach((stat, index) => {
                const targetStr = stat.getAttribute('data-target');
                const target = parseInt(targetStr);
                
                console.log(`📊 Card ${index + 1}: target = ${target}`, stat);
                
                if (target && !isNaN(target)) {
                    // Definir valor imediatamente como fallback
                    stat.textContent = formatStatNumber(target);
                    
                    // Animar após um pequeno delay
                    setTimeout(() => {
                        stat.textContent = '0';
                        animateCounter(stat, target);
                    }, 500 + (index * 200));
                } else {
                    console.error('❌ Target inválido:', targetStr);
                }
            });
            return true;
        }
        
        return false;
    }
    
    // Tentar imediatamente
    if (!setupCounters()) {
        // Tentar novamente após delay
        setTimeout(() => {
            if (!setupCounters()) {
                // Última tentativa: definir valores diretamente
                setTimeout(() => {
                    const allStats = document.querySelectorAll('.stat-number[data-target]');
                    allStats.forEach(stat => {
                        const target = parseInt(stat.getAttribute('data-target'));
                        if (target) {
                            stat.textContent = formatStatNumber(target);
                            console.log('📊 Valor definido diretamente:', stat.textContent);
                        }
                    });
                }, 2000);
            }
        }, 1000);
    }
    
    // Garantir que apareçam após 5 segundos
    setTimeout(() => {
        const allStats = document.querySelectorAll('.stat-number[data-target]');
        allStats.forEach(stat => {
            const target = parseInt(stat.getAttribute('data-target'));
            if (target && (stat.textContent === '0' || !stat.textContent)) {
                stat.textContent = formatStatNumber(target);
                console.log('📊 Valor final garantido:', stat.textContent);
            }
        });
    }, 5000);
}

// Função específica para animar contadores dos cards flutuantes
function animateFloatingCardCounter(element) {
    if (!element) {
        console.error('❌ Elemento não encontrado para animação');
        return;
    }
    
    const targetAttr = element.getAttribute('data-target');
    const target = parseInt(targetAttr);
    
    if (!targetAttr || isNaN(target)) {
        console.error('❌ Target inválido para contador:', element, 'target:', targetAttr);
        return;
    }
    
    console.log('🎬 Animando contador:', element, 'target:', target);
    
    // Garantir que começa do zero
    element.textContent = '0';
    
    const duration = 2000; // 2 segundos
    const steps = 60; // 60 steps
    const increment = target / steps;
    let current = 0;
    let step = 0;

    const timer = setInterval(() => {
        step++;
        current = (target / steps) * step;
        
        if (current >= target || step >= steps) {
            // Formatar número final
            const finalValue = formatStatNumber(target);
            element.textContent = finalValue;
            console.log('✅ Contador finalizado:', finalValue);
            clearInterval(timer);
        } else {
            // Formatar número durante animação
            element.textContent = formatStatNumber(Math.floor(current));
        }
    }, duration / steps);
}

// Função para formatar números (adicionar separadores de milhar)
function formatStatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

// ============================================
// VÍDEO MODAL POP-UP
// ============================================
function initCustomVideo() {
    console.log('🔍 Inicializando vídeo modal...');
    
    function setupVideo() {
        const videoTriggerCard = document.getElementById('videoTriggerCard');
        const cardContent = document.getElementById('cardContent');
        const videoModal = document.getElementById('videoModal');
        const videoModalClose = document.getElementById('videoModalClose');
        const videoModalOverlay = document.getElementById('videoModalOverlay');
        const videoModalIframe = document.getElementById('videoModalIframe');
        
        if (!videoTriggerCard || !cardContent || !videoModal || !videoModalClose || !videoModalOverlay || !videoModalIframe) {
            console.warn('⚠️ Aguardando elementos do vídeo...', {
                videoTriggerCard: !!videoTriggerCard,
                cardContent: !!cardContent,
                videoModal: !!videoModal,
                videoModalClose: !!videoModalClose,
                videoModalOverlay: !!videoModalOverlay,
                videoModalIframe: !!videoModalIframe
            });
            return false;
        }
        
        console.log('✅ Todos os elementos encontrados!');
        
        const videoId = 'uofjOCeM9AU';
        let videoLoaded = false;
        
        // Função para abrir o modal
        function openVideoModal() {
            console.log('🎬 Abrindo modal de vídeo...');
            
            if (!videoLoaded) {
                // URL com parâmetros para esconder controles do YouTube
                const autoplayUrl = `https://www.youtube.com/embed/${videoId}?autoplay=1&modestbranding=1&rel=0&controls=0&showinfo=0&fs=0&cc_load_policy=0&iv_load_policy=3&playsinline=1&mute=0&disablekb=1&loop=0&origin=${encodeURIComponent(window.location.origin)}&enablejsapi=1`;
                videoModalIframe.src = autoplayUrl;
                videoLoaded = true;
            }
            
            videoModal.classList.add('active');
            document.body.style.overflow = 'hidden';
        }
        
        // Função para fechar o modal
        function closeVideoModal() {
            console.log('❌ Fechando modal de vídeo...');
            videoModal.classList.remove('active');
            document.body.style.overflow = '';
            
            // Parar o vídeo removendo o src
            videoModalIframe.src = '';
            videoLoaded = false;
        }
        
        // Função handler para cliques
        function handleClick(e) {
            e.preventDefault();
            e.stopPropagation();
            openVideoModal();
        }
        
        // Adicionar listeners para abrir o modal
        videoTriggerCard.addEventListener('click', handleClick, true);
        console.log('✅ Listener adicionado ao card principal');
        
        cardContent.addEventListener('click', handleClick, true);
        console.log('✅ Listener adicionado ao conteúdo do card');
        
        // Listener específico no botão "Clique e assista o vídeo"
        const videoHint = cardContent.querySelector('.video-hint');
        if (videoHint) {
            videoHint.addEventListener('click', handleClick, true);
            videoHint.style.cursor = 'pointer';
            videoHint.style.pointerEvents = 'auto';
            console.log('✅ Listener adicionado ao botão "Clique e assista o vídeo"');
        }
        
        // Listener no botão de play do overlay (se existir)
        const playBtn = document.getElementById('playVideoBtn');
        if (playBtn) {
            playBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                openVideoModal();
            }, true);
            console.log('✅ Listener adicionado ao botão play');
        }
        
        // Listener para fechar o modal
        videoModalClose.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeVideoModal();
        });
        
        // Fechar ao clicar no overlay
        videoModalOverlay.addEventListener('click', function(e) {
            if (e.target === videoModalOverlay) {
                closeVideoModal();
            }
        });
        
        // Fechar com a tecla ESC
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && videoModal.classList.contains('active')) {
                closeVideoModal();
            }
        });
        
        console.log('✅ Todos os event listeners adicionados!');
        return true;
    }
    
    // Tentar imediatamente
    if (setupVideo()) {
        console.log('✅ Vídeo modal inicializado!');
        return;
    }
    
    // Se não funcionou, tentar após delays progressivos
    const delays = [500, 1000, 2000];
    delays.forEach((delay, index) => {
        setTimeout(() => {
            if (setupVideo()) {
                console.log(`✅ Vídeo modal inicializado (tentativa ${index + 2})!`);
            } else if (index === delays.length - 1) {
                console.error('❌ Não foi possível inicializar o vídeo modal após todas as tentativas!');
            }
        }, delay);
    });
}

// ============================================
// EFEITO 3D TILT NOS CARDS DE CREDIBILIDADE
// ============================================
function initCredibilityStats3D() {
    // Desabilitar em dispositivos touch (mobile/tablet)
    const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
    if (isTouchDevice) return;
    
    const stats = document.querySelectorAll('.credibility-stat');
    
    stats.forEach(stat => {
        stat.addEventListener('mousemove', (e) => {
            const rect = stat.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const centerX = rect.width / 2;
            const centerY = rect.height / 2;
            
            const rotateX = (y - centerY) / 15;
            const rotateY = (centerX - x) / 15;
            
            stat.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) translateY(-4px) scale(1.01)`;
        });
        
        stat.addEventListener('mouseleave', () => {
            stat.style.transform = 'perspective(1000px) rotateX(0) rotateY(0) translateY(0) scale(1)';
        });
    });
}

// Inicializar efeito 3D quando o DOM estiver pronto
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initCredibilityStats3D);
} else {
    initCredibilityStats3D();
}

// ============================================
// OTIMIZAÇÕES PARA MOBILE E TABLETS
// ============================================

// Detectar dispositivo móvel
const isMobile = () => {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ||
           (window.innerWidth <= 768);
};

// Melhorar scroll suave em mobile
if (isMobile()) {
    // Usar scroll nativo mais suave
    document.documentElement.style.scrollBehavior = 'smooth';
    
    // Prevenir zoom duplo toque
    let lastTouchEnd = 0;
    document.addEventListener('touchend', (e) => {
        const now = Date.now();
        if (now - lastTouchEnd <= 300) {
            e.preventDefault();
        }
        lastTouchEnd = now;
    }, false);
}

// Otimizar carrosséis para touch
function optimizeCarouselsForTouch() {
    const carousels = document.querySelectorAll('.logos-carousel, .countries-carousel');
    
    carousels.forEach(carousel => {
        let isDown = false;
        let startX;
        let scrollLeft;
        
        carousel.addEventListener('touchstart', (e) => {
            isDown = true;
            startX = e.touches[0].pageX - carousel.offsetLeft;
            scrollLeft = carousel.scrollLeft;
        });
        
        carousel.addEventListener('touchmove', (e) => {
            if (!isDown) return;
            e.preventDefault();
            const x = e.touches[0].pageX - carousel.offsetLeft;
            const walk = (x - startX) * 2;
            carousel.scrollLeft = scrollLeft - walk;
        });
        
        carousel.addEventListener('touchend', () => {
            isDown = false;
        });
    });
}

// Melhorar menu mobile com touch
function optimizeMobileMenu() {
    const menuToggle = document.getElementById('menuToggle');
    const navMenu = document.getElementById('navMenu');
    
    if (!menuToggle || !navMenu) return;
    
    // Adicionar suporte para touch
    menuToggle.addEventListener('touchstart', (e) => {
        e.preventDefault();
        navMenu.classList.toggle('active');
        menuToggle.classList.toggle('active');
        document.body.style.overflow = navMenu.classList.contains('active') ? 'hidden' : '';
    });
    
    // Fechar menu ao tocar fora (melhorado para touch)
    document.addEventListener('touchstart', (e) => {
        if (navMenu.classList.contains('active') && 
            !navMenu.contains(e.target) && 
            !menuToggle.contains(e.target)) {
            navMenu.classList.remove('active');
            menuToggle.classList.remove('active');
            document.body.style.overflow = '';
        }
    });
}

// Otimizar performance em mobile
function optimizePerformanceForMobile() {
    if (!isMobile()) return;
    
    // Reduzir animações complexas
    const style = document.createElement('style');
    style.textContent = `
        @media (max-width: 768px) {
            .floating-card,
            .stat-card-1,
            .stat-card-2,
            .stat-card-3 {
                animation-duration: 0.8s !important;
            }
            
            * {
                will-change: auto !important;
            }
        }
    `;
    document.head.appendChild(style);
    
    // Lazy load de imagens
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    if (img.dataset.src) {
                        img.src = img.dataset.src;
                        img.removeAttribute('data-src');
                        observer.unobserve(img);
                    }
                }
            });
        });
        
        document.querySelectorAll('img[data-src]').forEach(img => {
            imageObserver.observe(img);
        });
    }
}

// Melhorar formulários para mobile
function optimizeFormsForMobile() {
    const inputs = document.querySelectorAll('input, textarea, select');
    
    inputs.forEach(input => {
        // Prevenir zoom no iOS ao focar
        if (input.type !== 'file') {
            input.style.fontSize = '16px';
        }
        
        // Melhorar feedback visual em touch
        input.addEventListener('touchstart', function() {
            this.style.backgroundColor = 'rgba(255, 107, 53, 0.05)';
        });
        
        input.addEventListener('blur', function() {
            this.style.backgroundColor = '';
        });
    });
}

// Inicializar otimizações mobile
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        optimizeCarouselsForTouch();
        optimizeMobileMenu();
        optimizePerformanceForMobile();
        optimizeFormsForMobile();
    });
} else {
    optimizeCarouselsForTouch();
    optimizeMobileMenu();
    optimizePerformanceForMobile();
    optimizeFormsForMobile();
}

// (Promoção Fim de Ano removida: pop-up e botão associados)
