/**
 * Mousinho Consultoria - Landing Page Scripts
 * Desenvolvido por Dante Testa (https://dantetesta.com.br)
 * Data: 05/12/2024 10:17
 */

'use strict';

// ============================================
// DOM Elements
// ============================================
const header = document.getElementById('header');
const navMenu = document.getElementById('nav-menu');
const navToggle = document.getElementById('nav-toggle');
const navClose = document.getElementById('nav-close');
const navLinks = document.querySelectorAll('.nav__link');
const whatsappFloat = document.getElementById('whatsapp-float');

// ============================================
// Mobile Navigation
// ============================================
function openMenu() {
    navMenu.classList.add('show-menu');
    document.body.style.overflow = 'hidden';
}

function closeMenu() {
    navMenu.classList.remove('show-menu');
    document.body.style.overflow = '';
}

if (navToggle) {
    navToggle.addEventListener('click', openMenu);
}

if (navClose) {
    navClose.addEventListener('click', closeMenu);
}

// Close menu when clicking on nav links
navLinks.forEach(link => {
    link.addEventListener('click', () => {
        closeMenu();
    });
});

// Close menu when clicking outside
document.addEventListener('click', (e) => {
    if (navMenu.classList.contains('show-menu') &&
        !navMenu.contains(e.target) &&
        !navToggle.contains(e.target)) {
        closeMenu();
    }
});

// Close menu on escape key
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && navMenu.classList.contains('show-menu')) {
        closeMenu();
    }
});

// ============================================
// Header Scroll Effect
// ============================================
let lastScroll = 0;
const scrollThreshold = 100;

function handleScroll() {
    const currentScroll = window.scrollY;

    // Add/remove background based on scroll position
    if (currentScroll > 50) {
        header.style.background = 'rgba(10, 10, 15, 0.95)';
        header.style.boxShadow = '0 4px 30px rgba(0, 0, 0, 0.3)';
    } else {
        header.style.background = 'rgba(10, 10, 15, 0.8)';
        header.style.boxShadow = 'none';
    }

    // Hide/show header based on scroll direction
    if (currentScroll > scrollThreshold) {
        if (currentScroll > lastScroll) {
            header.style.transform = 'translateY(-100%)';
        } else {
            header.style.transform = 'translateY(0)';
        }
    }

    lastScroll = currentScroll;
}

window.addEventListener('scroll', handleScroll, { passive: true });

// ============================================
// Smooth Scroll
// ============================================
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        const href = this.getAttribute('href');

        if (href !== '#') {
            e.preventDefault();
            const target = document.querySelector(href);

            if (target) {
                const headerHeight = header.offsetHeight;
                const targetPosition = target.offsetTop - headerHeight;

                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });
            }
        }
    });
});

// ============================================
// Intersection Observer for Animations
// ============================================
const observerOptions = {
    root: null,
    rootMargin: '0px',
    threshold: 0.1
};

const animatedElements = document.querySelectorAll(
    '.benefit-card, .feature-block, .service-card, .about__grid, .cta__card'
);

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);

animatedElements.forEach(el => {
    el.style.opacity = '0';
    el.style.transform = 'translateY(30px)';
    el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    observer.observe(el);
});

// Stagger animation for grid items
const cardGrids = document.querySelectorAll('.benefits__grid, .services__grid');

cardGrids.forEach(grid => {
    const cards = grid.querySelectorAll('.benefit-card, .service-card');
    cards.forEach((card, index) => {
        card.style.transitionDelay = `${index * 100}ms`;
    });
});

// ============================================
// WhatsApp Float Button
// ============================================
let isScrolling = false;
let scrollTimeout;

function hideWhatsAppButton() {
    if (!isScrolling) {
        isScrolling = true;
        whatsappFloat.style.opacity = '0.5';
        whatsappFloat.style.transform = 'scale(0.9)';
    }

    clearTimeout(scrollTimeout);
    scrollTimeout = setTimeout(() => {
        isScrolling = false;
        whatsappFloat.style.opacity = '1';
        whatsappFloat.style.transform = 'scale(1)';
    }, 300);
}

window.addEventListener('scroll', hideWhatsAppButton, { passive: true });

// Show WhatsApp button after delay
setTimeout(() => {
    whatsappFloat.style.animation = 'bounceIn 0.6s ease forwards';
}, 2000);

// ============================================
// Typing Effect for Hero Title (Optional)
// ============================================
function typeEffect(element, text, speed = 50) {
    let i = 0;
    element.textContent = '';

    function type() {
        if (i < text.length) {
            element.textContent += text.charAt(i);
            i++;
            setTimeout(type, speed);
        }
    }

    type();
}

// ============================================
// Counter Animation
// ============================================
function animateCounter(element, target, duration = 2000) {
    let start = 0;
    const increment = target / (duration / 16);

    function updateCounter() {
        start += increment;
        if (start < target) {
            element.textContent = Math.floor(start);
            requestAnimationFrame(updateCounter);
        } else {
            element.textContent = target;
        }
    }

    updateCounter();
}

// Animate stats when in view
const stats = document.querySelectorAll('.stat__number');
const statsObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const text = entry.target.textContent;
            const number = parseInt(text.replace(/\D/g, ''));
            const prefix = text.match(/[^\d]/)?.[0] || '';
            const suffix = text.includes('%') ? '%' : '';

            entry.target.textContent = prefix + '0' + suffix;

            let current = 0;
            const increment = number / 50;

            const timer = setInterval(() => {
                current += increment;
                if (current >= number) {
                    entry.target.textContent = prefix + number + suffix;
                    clearInterval(timer);
                } else {
                    entry.target.textContent = prefix + Math.floor(current) + suffix;
                }
            }, 40);

            statsObserver.unobserve(entry.target);
        }
    });
}, { threshold: 0.5 });

stats.forEach(stat => statsObserver.observe(stat));

// ============================================
// Particle Effect (Subtle)
// ============================================
function createParticle() {
    const particles = document.getElementById('particles');
    if (!particles) return;

    const particle = document.createElement('div');
    particle.style.cssText = `
        position: absolute;
        width: 4px;
        height: 4px;
        background: rgba(96, 165, 250, 0.3);
        border-radius: 50%;
        pointer-events: none;
        left: ${Math.random() * 100}%;
        top: ${Math.random() * 100}%;
        animation: particleFloat ${5 + Math.random() * 5}s linear infinite;
    `;

    particles.appendChild(particle);

    setTimeout(() => {
        particle.remove();
    }, 10000);
}

// Create particles periodically
setInterval(createParticle, 500);

// Add particle animation style
const style = document.createElement('style');
style.textContent = `
    @keyframes particleFloat {
        0% {
            opacity: 0;
            transform: translateY(0) scale(0);
        }
        10% {
            opacity: 1;
            transform: translateY(-10px) scale(1);
        }
        90% {
            opacity: 1;
            transform: translateY(-100px) scale(1);
        }
        100% {
            opacity: 0;
            transform: translateY(-120px) scale(0);
        }
    }
    
    @keyframes bounceIn {
        0% {
            opacity: 0;
            transform: scale(0.3);
        }
        50% {
            transform: scale(1.1);
        }
        70% {
            transform: scale(0.9);
        }
        100% {
            opacity: 1;
            transform: scale(1);
        }
    }
`;
document.head.appendChild(style);

// ============================================
// UTM Tracking for WhatsApp
// ============================================
function addUTMToWhatsApp() {
    const urlParams = new URLSearchParams(window.location.search);
    const utm_source = urlParams.get('utm_source') || 'direct';
    const utm_medium = urlParams.get('utm_medium') || 'organic';
    const utm_campaign = urlParams.get('utm_campaign') || 'landing';

    const whatsappLinks = document.querySelectorAll('a[href*="wa.me"]');

    whatsappLinks.forEach(link => {
        const currentHref = link.getAttribute('href');
        const [baseUrl, text] = currentHref.split('?text=');

        if (text) {
            const decodedText = decodeURIComponent(text);
            const trackedText = `${decodedText} [Origem: ${utm_source}/${utm_medium}/${utm_campaign}]`;
            link.setAttribute('href', `${baseUrl}?text=${encodeURIComponent(trackedText)}`);
        }
    });
}

// Initialize UTM tracking
addUTMToWhatsApp();

// ============================================
// Performance Optimization
// ============================================

// Lazy load images
if ('loading' in HTMLImageElement.prototype) {
    const images = document.querySelectorAll('img[loading="lazy"]');
    images.forEach(img => {
        img.src = img.src;
    });
} else {
    // Fallback for browsers that don't support lazy loading
    const lazyLoadScript = document.createElement('script');
    lazyLoadScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.2/lazysizes.min.js';
    document.body.appendChild(lazyLoadScript);
}

// ============================================
// Console Easter Egg
// ============================================
console.log(`
%c Mousinho Consultoria 
%c Desenvolvido por Dante Testa
%c https://dantetesta.com.br

🚀 Organização. Comunicação. Lucratividade.
`,
    'color: #3b82f6; font-size: 24px; font-weight: bold;',
    'color: #94a3b8; font-size: 14px;',
    'color: #60a5fa; font-size: 12px;'
);

// ============================================
// Service Worker Registration (PWA Ready)
// ============================================
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        // Uncomment when service worker is ready
        // navigator.serviceWorker.register('/sw.js')
        //     .then(reg => console.log('Service Worker registered'))
        //     .catch(err => console.log('Service Worker registration failed:', err));
    });
}

// ============================================
// Analytics Events (Google Analytics Ready)
// ============================================
function trackEvent(category, action, label = null) {
    if (typeof gtag !== 'undefined') {
        gtag('event', action, {
            'event_category': category,
            'event_label': label
        });
    }
}

// Track CTA clicks
document.querySelectorAll('.btn--primary, .btn--white').forEach(btn => {
    btn.addEventListener('click', (e) => {
        const label = btn.id || btn.textContent.trim();
        trackEvent('CTA', 'click', label);
    });
});

// Track scroll depth
let scrollDepths = [25, 50, 75, 100];
let trackedDepths = [];

window.addEventListener('scroll', () => {
    const scrollPercent = Math.round(
        (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100
    );

    scrollDepths.forEach(depth => {
        if (scrollPercent >= depth && !trackedDepths.includes(depth)) {
            trackedDepths.push(depth);
            trackEvent('Scroll', 'depth', `${depth}%`);
        }
    });
}, { passive: true });
