/* =========================================
   1. CONFIGURAÇÃO GLOBAL E INICIALIZAÇÃO
   ========================================= */
document.addEventListener('DOMContentLoaded', () => {
    // Inicializa ícones e funções básicas
    if (typeof lucide !== 'undefined') lucide.createIcons();
    
    initNavbar();
    initScrollReveal();
    initEventTracking();

});

/* =========================================
   2. LÓGICA DA NAVBAR (SCROLL & MOBILE)
   ========================================= */
function initNavbar() {
    const navbar = document.querySelector('nav');
    const mobileBtn = document.getElementById('mobile-menu-btn');
    const mobileMenu = document.getElementById('mobile-menu');

    if (!navbar) return;

    // Efeito de Vidro/Opacidade no Scroll
    const updateNavbarStyle = () => {
        if (window.scrollY > 20) {
            navbar.classList.add('nav-scrolled', 'nav-blur');
        } else {
            navbar.classList.remove('nav-scrolled', 'nav-blur');
        }
    };
    window.addEventListener('scroll', updateNavbarStyle);
    updateNavbarStyle();

    // Lógica de Link Ativo (Fidelidade ao NavLink)
    const setActiveLink = () => {
        const currentPath = window.location.pathname;
        const navLinks = document.querySelectorAll('nav a');

        navLinks.forEach(link => {
            const href = link.getAttribute('href');
            if (!href || link.classList.contains('glow-button')) return;

            link.classList.remove('text-primary', 'bg-primary/10');
            if (!link.classList.contains('glow-button')) {
                link.classList.add('text-muted-foreground');
            }

            // Melhoria na detecção da página atual
            const isHome = (href === '/' || href === '/index') && (currentPath === '/' || currentPath === '/index' || currentPath === '');
            const isCurrentPage = href !== '/' && href !== '/index' && currentPath.startsWith(href);

            if (isHome || isCurrentPage) {
                link.classList.add('text-primary');
                link.classList.remove('text-muted-foreground');
                if (link.closest('#mobile-menu')) link.classList.add('bg-primary/10');
            }
        });
    };
    setActiveLink();

    // Menu Mobile Toggle
    if (mobileBtn && mobileMenu) {
        mobileBtn.addEventListener('click', () => {
            const isOpen = !mobileMenu.classList.contains('hidden');
            mobileMenu.classList.toggle('hidden');
            mobileBtn.innerHTML = isOpen ? '<i data-lucide="menu" class="w-6 h-6"></i>' : '<i data-lucide="x" class="w-6 h-6"></i>';
            lucide.createIcons();
        });
    }

    const updateLangUI = () => {
        const getCookie = (name) => {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
            return 'ptBR';
        };

        const currentLang = getCookie('site_lang') || 'ptBR';
        const flagMappings = {
            ptBR: '/assets/flag-ptBR.svg',
            enUS: '/assets/flag-enUS.svg',
            esES: '/assets/flag-esES.svg'
        };

        const mainFlag = document.getElementById('main-flag');
        if (mainFlag) {
            const targetSrc = flagMappings[currentLang];

            // Verifica se precisa trocar (compara o final da string pra evitar erro de URL absoluta)
            if (!mainFlag.src.endsWith(targetSrc)) {
                
                // 1. Oculta a bandeira errada INSTANTANEAMENTE (sem animação)
                mainFlag.style.transition = 'none';
                mainFlag.style.opacity = '0';

                // 2. Troca a fonte da imagem
                mainFlag.src = targetSrc;

                // 3. Quando a nova carregar...
                mainFlag.onload = () => {
                    // Usa requestAnimationFrame para garantir que o browser renderizou o opacity 0
                    requestAnimationFrame(() => {
                        // Ativa a transição suave
                        mainFlag.style.transition = 'opacity 0.5s ease-in-out';
                        // Torna visível (o CSS fará o fade-in)
                        mainFlag.style.opacity = '1';
                    });
                };
            } else {
                // Se já veio certa do servidor, garante que está visível
                mainFlag.style.opacity = '1';
                mainFlag.style.transition = 'none';
            }
        }

        // Atualiza estilos dos links (mantido igual)
        const langs = ['ptBR', 'enUS', 'esES'];
        langs.forEach(lang => {
            const link = document.getElementById(`lang-${lang}`);
            const mobileLink = document.getElementById(`mobile-lang-${lang}`);
            const isActive = lang === currentLang;

            const activeClasses = 'bg-primary/10 text-primary shadow-sm';
            const inactiveClasses = 'text-muted-foreground hover:text-primary hover:bg-primary/5 opacity-70 hover:opacity-100'; 

            if (link) {
                link.className = `flex items-center gap-3 px-3 py-2 rounded-lg text-xs transition-colors ${isActive ? activeClasses : inactiveClasses}`;
            }
            if (mobileLink) {
                mobileLink.className = `flex flex-col items-center gap-1 text-[10px] p-2 rounded-lg ${isActive ? activeClasses : inactiveClasses}`;
            }
        });
    };

    updateLangUI();
}

/* =========================================
   3. SISTEMA DE REVELAÇÃO (INTERSECTION OBSERVER)
   ========================================= */
function initScrollReveal() {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('active');
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.1 });

    document.querySelectorAll('.reveal').forEach(el => observer.observe(el));
}

/* =========================================
   4. SISTEMA DE TOAST (SUBSTITUTO useToast)
   ========================================= */
function showToast({ title, description }) {
    let container = document.getElementById('toast-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'toast-container';
        document.body.appendChild(container);
    }

    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.innerHTML = `
        <div class="flex-1">
            ${title ? `<p class="font-bold text-foreground text-sm">${title}</p>` : ''}
            ${description ? `<p class="text-muted-foreground text-xs">${description}</p>` : ''}
        </div>
        <button class="text-muted-foreground hover:text-foreground transition-colors" onclick="this.parentElement.remove()">
            <i data-lucide="x" class="w-4 h-4"></i>
        </button>
    `;

    container.appendChild(toast);
    lucide.createIcons();

    setTimeout(() => {
        toast.classList.add('removing');
        toast.addEventListener('animationend', () => toast.remove());
    }, 5000);
}
window.toast = showToast;


/* =========================================
   5. SISTEMA DE TRACKING DE EVENTOS
   ========================================= */

// Função para enviar eventos para a API (versão de produção)
function trackEvent(eventType, details) {
    var payload = JSON.stringify({ url: window.location.pathname, eventType: eventType, details: details });

    fetch('/api/track-event', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: payload
    }).catch(error => {
        // Em produção, os erros são ignorados silenciosamente para não impactar a experiência do usuário.
    });
}

// Função para inicializar o tracking de eventos (versão de produção)
function initEventTracking() {
    // TRACKING DE CONVERSÃO (EVENTO: contact)
    document.querySelectorAll('a[href^="mailto:"], a[href*="wa.me"], a[href^="tel:"]').forEach(link => {
        link.addEventListener('click', function() {
            let type = 'Desconhecido';
            if (this.href.startsWith('mailto:')) type = 'Email';
            if (this.href.includes('wa.me')) type = 'WhatsApp';
            if (this.href.startsWith('tel:')) type = 'Telefone';
            trackEvent('contact', `Clique-${type}`);
        });
    });

    document.querySelectorAll('form.contact-form').forEach(form => {
        form.addEventListener('submit', function() {
            trackEvent('fcontact', 'Form-Submit-Contato');
        });
    });

    // TRACKING DE NAVEGAÇÃO E ENGAJAMENTO (EVENTO: click)
    document.querySelectorAll('a.glow-button').forEach(cta => {
        cta.addEventListener('click', function() {
            let detail = this.innerText.trim().replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
            detail = detail.replace(/\s+/g, '-');
            trackEvent('click', `CTA-${detail}`);
        });
    });

    document.querySelectorAll('#navbar a').forEach(link => {
        if (!link.id.startsWith('lang-') && !link.id.startsWith('mobile-lang-') && !link.classList.contains('glow-button')) {
            link.addEventListener('click', function() {
                let detail = 'Desconhecido';
                let location = this.closest('#mobile-menu') ? 'NavMobile' : 'NavDesktop';

                if (this.querySelector('img[src*="logo.svg"]')) {
                    detail = 'Logo';
                } else if (this.innerText.trim() !== '') {
                    let linkText = this.innerText.trim().replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
                    detail = linkText.replace(/\s+/g, '-');
                }
                trackEvent('click', `${location}-${detail}`);
            });
        }
    });

    document.querySelectorAll('#footer a').forEach(link => {
        if (!link.href.startsWith('mailto:') && !link.href.includes('wa.me') && !link.href.startsWith('tel:')) {
            link.addEventListener('click', function() {
                let detail = 'Desconhecido';
                const trackingId = this.dataset.trackingId;

                if (trackingId) {
                    detail = trackingId;
                } else if (this.querySelector('svg title')) {
                    detail = `Social-${this.querySelector('svg title').textContent}`;
                } else if (this.querySelector('img[src*="logo.svg"]')) {
                    detail = 'Logo';
                } else if (this.innerText.trim() !== '') {
                    let linkText = this.innerText.trim().replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
                    detail = linkText.replace(/\s+/g, '-');
                }
                trackEvent('click', `Footer-${detail}`);
            });
        }
    });
}
