// MAIN NAVIGATION TOGGLE RESPONSIVE
//==========================================
document.addEventListener('DOMContentLoaded', function () {
    const body = document.body;
    const menuToggle = document.getElementById('menu-toggle');
    const mobileMenu = document.getElementById('mobile-menu');

    // Event listener para o botão de menu
    if (menuToggle) {
        menuToggle.addEventListener('click', () => {
            mobileMenu.classList.toggle('active');
            menuToggle.classList.toggle('active');

            // Adiciona ou remove a classe overflow-hidden ao body
            if (mobileMenu.classList.contains('active')) {
                body.classList.add('overflow-hidden');
            } else {
                body.classList.remove('overflow-hidden');
            }
        });
    }

    // Listener personalizado para navegação no Blazor
    window.addEventListener('blazor:navigation', () => {
        // Qualquer código necessário após a navegação no Blazor
    });
    
    function redirecionar(value) {
        // Redireciona para a página de destino com o parâmetro na QueryString
        window.location.href = "pagina-destino.html?tipo=" + value;
    }

});
//==========================================
// END MAIN NAVIGATION TOGGLE RESPONSIVE



// BLAZOR NAVIGATION (?) APAGAR?????
//==========================================
// Detecta e configura a navegação do Blazor
(function () {
    if (window.Blazor) {
        const handleBlazorNavigation = () => {
            window.history.pushState = (f => function pushState() {
                const ret = f.apply(this, arguments);
                window.dispatchEvent(new CustomEvent('blazor:navigation'));
                return ret;
            })(window.history.pushState);

            window.history.replaceState = (f => function replaceState() {
                const ret = f.apply(this, arguments);
                window.dispatchEvent(new CustomEvent('blazor:navigation'));
                return ret;
            })(window.history.replaceState);
        };

        if (window.Blazor._internal && window.Blazor._internal.navigationManager) {
            handleBlazorNavigation();
        } else {
            window.addEventListener('blazor:loaded', handleBlazorNavigation);
        }
    }
})();
//==========================================
// END BLAZOR NAVIGATION (?)



// CAROUSEL (LEGACY)
//==========================================
window.carousel = function carousel(defaultSlidesVisible, navigateByPage = false, showPreview = true, paddingValue = 0) {
    return {
        currentIndex: 0,
        slidesVisible: defaultSlidesVisible,
        totalSlides: 0,
        maxIndex: 0,
        navigateByPage: navigateByPage,
        showPreview: showPreview,
        paddingValue: paddingValue,

        // Inicializa o carrossel e calcula o número de slides visíveis
        initCarousel(el) {
            this.totalSlides = el.querySelectorAll('.carousel-slide').length;
            this.calculateSlidesVisible();
        },

        // Função para calcular a largura de cada slide
        slideWidth() {
            if (!this.showPreview) {
                return `calc(100% / ${this.slidesVisible})`;
            } else if (this.slidesVisible === 1 && this.showPreview) {
                return '90%';
            } else {
                const previewWidth = 10 / this.slidesVisible;
                return `calc(97% / ${this.slidesVisible} - ${Math.round(previewWidth)}px)`;
            }
        },

        slidePadding(index) {
            const lastVisibleIndex = this.currentIndex + this.slidesVisible - 1;
            if (!this.showPreview && index === lastVisibleIndex) {
                return 0;
            }
            return this.paddingValue;
        },

        isLastVisibleSlide(index) {
            const lastVisibleIndex = this.currentIndex + this.slidesVisible - 1;
            return index === lastVisibleIndex;
        },

        get totalPages() {
            return Math.ceil(this.totalSlides / this.slidesVisible);
        },

        get currentPage() {
            return Math.ceil((this.currentIndex + this.slidesVisible) / this.slidesVisible);
        },

        get translateXValue() {
            if (this.slidesVisible === 1 && this.showPreview) {
                return Math.round(this.currentIndex * 90);
            } else {
                return Math.round(this.currentIndex * (100 / this.slidesVisible));
            }
        },

        updateMaxIndex() {
            this.maxIndex = this.totalSlides - this.slidesVisible;
        },

        calculateSlidesVisible() {
            if (window.innerWidth >= 1024) {
                this.slidesVisible = defaultSlidesVisible;
            } else if (window.innerWidth >= 768) {
                this.slidesVisible = Math.max(2, Math.floor(defaultSlidesVisible / 2));
            } else {
                this.slidesVisible = 1;
            }
            this.updateMaxIndex();
            this.currentIndex = Math.min(this.currentIndex, this.maxIndex);
        },

        next() {
            if (this.navigateByPage) {
                if (this.currentIndex < this.maxIndex) {
                    this.currentIndex += this.slidesVisible;
                    this.currentIndex = Math.min(this.currentIndex, this.maxIndex);
                }
            } else if (this.currentIndex < this.maxIndex) {
                this.currentIndex++;
            }
        },

        prev() {
            if (this.navigateByPage) {
                if (this.currentIndex > 0) {
                    this.currentIndex -= this.slidesVisible;
                    this.currentIndex = Math.max(this.currentIndex, 0);
                }
            } else if (this.currentIndex > 0) {
                this.currentIndex--;
            }
        },

        startTouch(event) {
            this.startX = event.touches[0].clientX;
        },

        moveTouch(event) {
            event.preventDefault();
            this.endX = event.touches[0].clientX;
        },

        endTouch() {
            const diff = this.startX - this.endX;
            if (diff > 50) {
                this.next();
            } else if (diff < -50) {
                this.prev();
            }
        }
    };
}
//==========================================
// END CAROUSEL (LEGACY)



// SCROLL TO SECTION
//==========================================
function ScrollToSection(id) {
    const element = document.getElementById(id);
    if (element) {
        const headerOffset = 90; // Defina o valor do offset, equivalente à altura do seu menu sticky.
        const elementPosition = element.getBoundingClientRect().top;
        const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

        window.scrollTo({
            top: offsetPosition,
            behavior: "smooth"
        });
    }
}
//==========================================
// END SCROLL TO SECTION



// SCROLL TO TOP
//==========================================
function scrollToTop() {
    window.scrollTo(0, 0);
}
//==========================================
// END SCROLL TO TOP



// ANCHOR LINKS
//==========================================
// Adicionar evento a todos os links que fazem a navegação
document.addEventListener('DOMContentLoaded', function () {
    const navLinks = document.querySelectorAll('nav a');
    navLinks.forEach(link => {
        link.addEventListener('click', function () {
            setTimeout(scrollToTop, 0);
        });
    });
});
document.addEventListener('DOMContentLoaded', function () {
    const sections = document.querySelectorAll('.anchor-section');
    const navLinks = document.querySelectorAll('.anchor-nav a');

    window.addEventListener('scroll', () => {
        let current = '';

        // Verifica qual seção está majoritariamente visível na tela
        sections.forEach(section => {
            const sectionTop = section.getBoundingClientRect().top;
            const sectionBottom = sectionTop + section.clientHeight;

            // Verifica se a seção está ocupando mais de 50% da janela de visualização
            if (sectionTop < window.innerHeight / 2 && sectionBottom > window.innerHeight / 2) {
                current = section.getAttribute('id');
            }
        });

        // Remove a classe "active" de todos os botões e adiciona ao atual
        navLinks.forEach(link => {
            link.classList.remove('border-primary', 'active', 'text-primary');
            if (link.getAttribute('data-anchor') === current) {
                link.classList.add('border-primary', 'active', 'text-primary');
            }
        });
    });
});
//==========================================
// END ANCHOR LINKS



// ANIMATION SCROLLING ELEMENTS
//==========================================
window.scroller = {
    addAnimation: function () {
        const scrollers = document.querySelectorAll(".scroller");
        scrollers.forEach((scroller) => {
            scroller.setAttribute("data-animated", true);
            const scrollerInner = scroller.querySelector(".scroller__inner");
            const scrollerContent = Array.from(scrollerInner.children);
            scrollerContent.forEach((item) => {
                const duplicatedItem = item.cloneNode(true);
                duplicatedItem.setAttribute("aria-hidden", true);
                scrollerInner.appendChild(duplicatedItem);
            });
        });
    },
    highlightCenter: function () {
        const scrollers = document.querySelectorAll(".scroller");
        scrollers.forEach((scroller) => {
            const scrollerInner = scroller.querySelector(".scroller__inner");
            const items = Array.from(scrollerInner.children);

            function updateHighlight() {
                let closestItem = null;
                let closestDistance = Infinity;
                const screenCenter = window.innerWidth / 2;

                items.forEach((item) => {
                    const itemRect = item.getBoundingClientRect();
                    const itemCenter = itemRect.left + itemRect.width / 2;
                    const distance = Math.abs(screenCenter - itemCenter);

                    if (distance < closestDistance) {
                        closestDistance = distance;
                        closestItem = item;
                    }
                });

                items.forEach(item => item.classList.remove('highlighted-word'));
                if (closestItem) {
                    closestItem.classList.add('highlighted-word');
                }
            }

            function animate() {
                updateHighlight();
                requestAnimationFrame(animate);
            }

            animate();
        });
    }
};
//==========================================
// END ANIMATION SCROLLING ELEMENTS




// SLIDESHOW CAROUSEL CARDS
//==========================================

// Função global para os cartões de flip
window.flipCardData = function () {
    return {
        isActive: false,
        touchStartX: 0,
        touchStartY: 0,
        handleTouchEnd(event) {
            const touchEndX = event.changedTouches[0].clientX;
            const touchEndY = event.changedTouches[0].clientY;

            const deltaX = Math.abs(touchEndX - this.touchStartX);
            const deltaY = Math.abs(touchEndY - this.touchStartY);

            const threshold = 10; // px

            if (deltaX < threshold && deltaY < threshold) {
                // É um tap
                this.isActive = !this.isActive;
                event.preventDefault(); // Previne que o carousel interprete como swipe
            }
        }
    };
}

// Função de Inicialização do Carousel (já implementada)
window.initializeCarouselById = function (id, openModalCallback = null) {
    const carouselElement = document.getElementById(id);
    if (!carouselElement) {
        console.error(`Elemento com ID '${id}' não foi encontrado.`);
        return;
    }

    // Se o callback não for passado, tente usar window.openModal
    if (!openModalCallback && window.openModal) {
        openModalCallback = window.openModal;
    }

    window.initializeCarousel(carouselElement, openModalCallback);
}

window.initializeCarousel = function (carouselElement, openModalCallback = null) {
    console.log("Inicializando carousel...");
    console.log("carouselElement:", carouselElement);
    console.log("openModalCallback:", openModalCallback);

    if (!carouselElement) {
        console.error("carouselElement não foi encontrado.");
        return;
    }

    let currentIndex = 0; // Índice do slide atual
    let slideWidth = getSlideWidth(); // Largura inicial do slide
    const slides = carouselElement.querySelector('.slides'); // Container dos slides
    const slideItems = carouselElement.querySelectorAll('.slide-flip'); // Cada slide individual
    const totalSlides = slideItems.length; // Número total de slides
    let startX = 0, endX = 0; // Variáveis para o swipe

    // Função para obter a largura do slide
    function getSlideWidth() {
        return window.innerWidth <= 768
            ? parseInt(carouselElement.getAttribute('data-slide-widths-mobile')) // Mobile
            : parseInt(carouselElement.getAttribute('data-slide-width')); // Desktop
    }

    // Atualiza a largura dos slides quando o tamanho da janela muda
    function updateSlideWidths() {
        slideWidth = getSlideWidth(); // Recalcula a largura
        slideItems.forEach(slide => slide.style.width = `${slideWidth}px`);
        moveSlideCarousel(currentIndex); // Atualiza a posição do carrossel
    }

    // Função que move o carrossel
    function moveSlideCarousel(newIndex) {
        currentIndex = Math.max(0, Math.min(newIndex, totalSlides - 1));
        slides.style.transform = `translateX(-${currentIndex * slideWidth}px)`;
        updateCarouselButtons();
    }

    // Função que atualiza a opacidade dos botões "prev" e "next"
    function updateCarouselButtons() {
        const prevButton = carouselElement.querySelector('.prev');
        const nextButton = carouselElement.querySelector('.next');
        if (prevButton && nextButton) {
            prevButton.classList.toggle('opacity-50', currentIndex === 0);
            nextButton.classList.toggle('opacity-50', currentIndex === totalSlides - 1);
        }
    }

    // Referências aos botões de navegação
    const nextButton = carouselElement.querySelector('.next');
    const prevButton = carouselElement.querySelector('.prev');

    if (!nextButton || !prevButton) {
        console.error("Botões de navegação não encontrados no carouselElement.");
        return;
    }

    // Adiciona eventos de clique para os botões de navegação
    nextButton.addEventListener('click', () => moveSlideCarousel(currentIndex + 1));
    prevButton.addEventListener('click', () => moveSlideCarousel(currentIndex - 1));

    // Eventos para o swipe (toque) nos slides
    slides.addEventListener('touchstart', (e) => {
        const touch = e.touches[0];
        startX = touch.clientX;
    });

    slides.addEventListener('touchmove', (e) => {
        endX = e.touches[0].clientX;
    });

    slides.addEventListener('touchend', (e) => {
        const swipeDistance = endX - startX;
        const swipeThreshold = 50;
        console.log('Swipe distance:', swipeDistance);

        // Verifica se o evento já foi prevenido por um cartão de flip
        if (e.defaultPrevented) {
            // O evento foi prevenido, não faça nada
            return;
        }

        if (swipeDistance > swipeThreshold) moveSlideCarousel(currentIndex - 1);
        else if (swipeDistance < -swipeThreshold) moveSlideCarousel(currentIndex + 1);
        startX = 0;
        endX = 0;
    });

    // Adiciona evento de clique a cada slide para abrir a modal
    slideItems.forEach((slide, index) => {
        slide.style.width = `${slideWidth}px`;
        if (openModalCallback) {
            slide.addEventListener('click', () => openModalCallback(index, slideItems));
        }
    });

    // Atualiza a largura dos slides quando a janela é redimensionada
    window.addEventListener('resize', updateSlideWidths);

    // Define a largura inicial dos slides
    updateSlideWidths();
}


window.initializeModal = function(modalId) {
    const modalElement = document.getElementById(modalId);
    if (!modalElement) {
        console.error(`Elemento com ID '${modalId}' não foi encontrado.`);
        return;
    }

    const modalImage = modalElement.querySelector('#modalImage'); // Imagem no modal
    const modalPrev = modalElement.querySelector('#modalPrev'); // Botão prev no modal
    const modalNext = modalElement.querySelector('#modalNext'); // Botão next no modal
    const thumbnailsContainer = modalElement.querySelector('#thumbnails'); // Container de thumbnails
    let modalIndex = 0; // Índice da imagem atual no modal
    let slideItems = []; // Referência aos slides do carrossel ou galeria

    // Abre o modal fullscreen com a imagem correspondente ao índice
    function openModal(index, items) {
        modalIndex = index;
        slideItems = items;
        updateModalImage();
        updateModalButtons();
        createThumbnails();
        modalElement.classList.remove('hidden'); // Mostra o modal
        document.body.classList.add('overflow-hidden'); // Desativa o scroll da página
    }

    // Fecha o modal
    modalElement.querySelector('#closeFullscreenModal').addEventListener('click', () => {
        modalElement.classList.add('hidden');
        document.body.classList.remove('overflow-hidden'); // Restaura o scroll da página
    });

    // Atualiza a imagem no modal
    function updateModalImage() {
        const currentSlide = slideItems[modalIndex].querySelector('img');
        modalImage.src = currentSlide.src;
        modalImage.alt = currentSlide.alt;
    }

    // Atualiza os botões "prev" e "next"
    function updateModalButtons() {
        modalPrev.classList.toggle('opacity-50', modalIndex === 0);
        modalNext.classList.toggle('opacity-50', modalIndex === slideItems.length - 1);
    }

    // Cria thumbnails e adiciona eventos de navegação
    function createThumbnails() {
        thumbnailsContainer.innerHTML = ''; // Limpa thumbnails anteriores
        slideItems.forEach((slide, index) => {
            const imgSrc = slide.querySelector('img').src;
            const thumbnail = document.createElement('img');
            thumbnail.src = imgSrc;
            thumbnail.classList.add('w-16', 'h-16', 'object-cover', 'cursor-pointer', 'border-2', 'border-transparent', 'rounded');
            thumbnail.addEventListener('click', () => {
                modalIndex = index;
                updateModalImage();
                updateModalButtons();
                updateThumbnails();
            });
            thumbnailsContainer.appendChild(thumbnail);
        });
        updateThumbnails();
    }

    // Atualiza a borda dos thumbnails
    function updateThumbnails() {
        const thumbnails = thumbnailsContainer.querySelectorAll('img');
        thumbnails.forEach((thumbnail, index) => {
            thumbnail.classList.remove('border-white');
            if (index === modalIndex) thumbnail.classList.add('border-white');
        });
    }

    // Adiciona eventos de navegação (prev/next)
    modalNext.addEventListener('click', () => {
        if (modalIndex < slideItems.length - 1) {
            modalIndex++;
            updateModalImage();
            updateModalButtons();
            updateThumbnails();
        }
    });

    modalPrev.addEventListener('click', () => {
        if (modalIndex > 0) {
            modalIndex--;
            updateModalImage();
            updateModalButtons();
            updateThumbnails();
        }
    });

    // Expor a função openModal globalmente
    window.openModal = openModal;
}

//==========================================
// END SLIDESHOW CAROUSEL


// AGENTS SLIDESHOW
//==========================================

window.sliderFunctions = {
    currentIndex: null,
    touchStartX: 0,
    touchEndX: 0,

    setCurrentIndex: function(index) {
        this.currentIndex = index;
    },

    // handleGesture: function() {
    //     const threshold = 50;
    //     if (this.touchEndX < this.touchStartX - threshold) {
    //         document.getElementById('nextSlide').click();
    //     } else if (this.touchEndX > this.touchStartX + threshold) {
    //         document.getElementById('prevSlide').click();
    //     }
    // },

    initializeSlider: function() {
        const slides = document.querySelectorAll('.slide');
        const slider = document.getElementById('slider');
        const prevButton = document.getElementById('prevSlide');
        const nextButton = document.getElementById('nextSlide');

        if (slides.length === 0) {
            requestAnimationFrame(this.initializeSlider.bind(this));
            return;
        }

        this.currentIndex = Math.floor(Math.random() * slides.length);

        const clearClasses = () => {
            slides.forEach(slide => {
                slide.classList.remove(
                    'center-slide', 'left-slide', 'right-slide',
                    'far-left-slide', 'far-right-slide', 'hidden-slide', 'h-80'
                );
            });
        };

        const updateSlides = () => {
            clearClasses();

            const numSlides = slides.length;

            // Garantir que currentIndex está dentro dos limites
            if (this.currentIndex >= numSlides) {
                this.currentIndex = 0;
            } else if (this.currentIndex < 0) {
                this.currentIndex = numSlides - 1;
            }

            // Ocultar botões de navegação se houver apenas um slide
            if (numSlides === 1) {
                prevButton.style.display = 'none';
                nextButton.style.display = 'none';

                // Centralizar o único slide
                slides[0].classList.add('center-slide');
            } else {
                // Mostrar botões de navegação
                prevButton.style.display = 'flex';
                nextButton.style.display = 'flex';

                if (numSlides === 2) {
                    // Dois slides: centralizar um e mostrar o outro à direita
                    slides[this.currentIndex].classList.add('center-slide');
                    slides[(this.currentIndex + 1) % numSlides].classList.add('right-slide');
                } else if (numSlides === 3) {
                    // Três slides: centralizar um, um à esquerda e um à direita
                    slides[this.currentIndex].classList.add('center-slide');
                    slides[(this.currentIndex + 1) % numSlides].classList.add('right-slide');
                    slides[(this.currentIndex - 1 + numSlides) % numSlides].classList.add('left-slide');
                } else {
                    // Quatro ou mais slides: lógica padrão
                    slides.forEach((slide, index) => {
                        const relativeIndex = (index - this.currentIndex + numSlides) % numSlides;
                        if (relativeIndex === 0) {
                            slide.classList.add('center-slide');
                        } else if (relativeIndex === 1) {
                            slide.classList.add('right-slide');
                        } else if (relativeIndex === 2) {
                            slide.classList.add('far-right-slide');
                        } else if (relativeIndex === numSlides - 1) {
                            slide.classList.add('left-slide');
                        } else if (relativeIndex === numSlides - 2) {
                            slide.classList.add('far-left-slide');
                        } else {
                            slide.classList.add('hidden-slide');
                        }
                    });
                }
            }
        };

        // Remover event listeners existentes para evitar múltiplas vinculações
        prevButton.replaceWith(prevButton.cloneNode(true));
        nextButton.replaceWith(nextButton.cloneNode(true));

        // Reatribuir os botões após clonagem
        const newPrevButton = document.getElementById('prevSlide');
        const newNextButton = document.getElementById('nextSlide');

        // slider.addEventListener('touchstart', (e) => {
        //     this.touchStartX = e.changedTouches[0].screenX;
        // });
        //
        // slider.addEventListener('touchmove', (e) => {
        //     this.touchEndX = e.changedTouches[0].screenX;
        // });
        //
        // slider.addEventListener('touchend', () => {
        //     this.handleGesture();
        // });

        newNextButton.addEventListener('click', () => {
            this.currentIndex = (this.currentIndex + 1) % slides.length;
            updateSlides();
        });

        newPrevButton.addEventListener('click', () => {
            this.currentIndex = (this.currentIndex - 1 + slides.length) % slides.length;
            updateSlides();
        });

        updateSlides();
    },

    getSearchInputValue: function() {
        return document.getElementById("agentSearchInput").value;
    }
};


//==========================================
// END AGENTS SLIDESHOW


// --- Meta Pixel helpers ---
window.metaTrackLead = function(details) {
    const fire = () => {
        try {
            if (typeof fbq === 'function') {
                fbq('track', 'Lead', details || {});
            } else {
                console.warn('🟦 Meta Lead: fbq not available');
            }
        } catch (e) { console.warn('🟦 Meta Lead error', e); }
    };
    if (typeof fbq === 'function') return fire();
    document.addEventListener('fbqLoaded', fire, { once: true });
};

// Optional: target a specific pixel id if multiple are initialized
window.metaTrackLeadSingle = function(pixelId, details){
    if (!pixelId) return console.warn('🟦 trackSingle: missing pixelId');
    const fire = () => {
        try {
            if (typeof fbq === 'function') {
                fbq('trackSingle', pixelId, 'Lead', details || {});
            }
        } catch(e){ console.warn('🟦 Meta Lead(trackSingle) error', e); }
    };
    if (typeof fbq === 'function') return fire();
    document.addEventListener('fbqLoaded', fire, { once:true });
};


// --- Meta Pixel: StartTrial ---
window.metaTrackStartTrial = function(details) {
    const fire = () => {
        try {
            if (typeof fbq === 'function') {
                fbq('track', 'StartTrial', details || {});
            } else {
                console.warn('🟦 Meta StartTrial: fbq not available');
            }
        } catch (e) { console.warn('🟦 Meta StartTrial error', e); }
    };
    if (typeof fbq === 'function') return fire();
    document.addEventListener('fbqLoaded', fire, { once: true });
};

// Delegated listener: triggers on any element with data-cta-starttrial="true"
(function attachStartTrialDelegation(){
    if (window.__metaStartTrialDelegated) return;
    window.__metaStartTrialDelegated = true;
    document.addEventListener('click', (ev) => {
        const el = ev.target && ev.target.closest?.('[data-cta-starttrial="true"]');
        if (!el) return;
        if (el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true') {
            return;
        }
        const details = {
            content_name: el.dataset.ctaName || 'CTA StartTrial',
            cta_variant: el.dataset.ctaVariant || null,
            cta_location: el.dataset.ctaLocation || null,
            value: el.dataset.value ? Number(el.dataset.value) : 0,
            currency: el.dataset.currency || 'EUR',
            event_id: el.dataset.eventId || undefined
        };
        window.metaTrackStartTrial(details);
    }, true);
})();


// --- Meta Pixel: ViewContent ---
window.metaTrackViewContent = function(details) {
    const fire = () => {
        try {
            if (typeof fbq === 'function') {
                fbq('track', 'ViewContent', details || {});
            } else {
                console.warn('🟦 Meta ViewContent: fbq not available');
            }
        } catch (e) { console.warn('🟦 Meta ViewContent error', e); }
    };
    if (typeof fbq === 'function') return fire();
    document.addEventListener('fbqLoaded', fire, { once: true });
};

// Delegated listener: triggers on any element with data-cta-viewcontent="true"
(function attachViewContentDelegation(){
    if (window.__metaViewContentDelegated) return;
    window.__metaViewContentDelegated = true;
    document.addEventListener('click', (ev) => {
        const el = ev.target && ev.target.closest?.('[data-cta-viewcontent="true"]');
        if (!el) return;
        if (el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true') {
            return;
        }
        const details = {
            content_name: el.dataset.ctaName || 'CTA ViewContent',
            content_category: el.dataset.ctaCategory || null,
            cta_location: el.dataset.ctaLocation || null,
            event_id: el.dataset.eventId || undefined
        };
        window.metaTrackViewContent(details);
    }, true);
})();


// META PIXEL (FacebookPixel) CONDITIONAL
//==========================================
window.setMetaPixelId = function (id) {
    if (!id || id === "0") {
        console.warn("🟩 MetaPixel – ID vazio ou 0. Ignorado.");
        return;
    }

    window.__metaPixelInitialized = window.__metaPixelInitialized || [];

    const alreadyInitialized = window.__metaPixelInitialized.includes(id);

    if (!alreadyInitialized) {
        window.__metaPixelInitialized.push(id);
        console.log("🟩 MetaPixel – inicializando novo ID:", id);
    } else {
        console.log("🟩 MetaPixel – já inicializado:", id);
    }

    console.log("🟩 MetaPixel – enviando PageView:", id);

    if (typeof fbq === 'function') {
        if (!alreadyInitialized) {
            fbq('init', id);
        }
        fbq('track', 'PageView');
    } else {
        console.warn("🟩 MetaPixel - fbq ainda não carregado, aguardando evento fbqLoaded.");
        document.addEventListener('fbqLoaded', () => {
            if (!alreadyInitialized) {
                fbq('init', id);
            }
            fbq('track', 'PageView');
        }, { once: true });
    }
};
//==========================================

// GOOGLE TAG (gtag.js) CONDITIONAL
//==========================================
window.setGoogleTagId = function (id) {
    if (!id || id === "0") {
        console.warn("🟦 GoogleTag – ID vazio ou 0. Ignorado.");
        return;
    }

    window.__googleTagInitialized = window.__googleTagInitialized || [];

    if (window.__googleTagInitialized.includes(id)) {
        console.log("🟦 GoogleTag – já inicializado:", id);
        return;
    }

    window.__googleTagInitialized.push(id);
    console.log("🟦 GoogleTag – inicializando:", id);

    // Load gtag.js script if not already present
    var scriptId = 'gtag-script-' + id;
    if (!document.getElementById(scriptId)) {
        var s = document.createElement('script');
        s.id = scriptId;
        s.async = true;
        s.src = 'https://www.googletagmanager.com/gtag/js?id=' + id;
        document.head.appendChild(s);
    }

    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    if (!window.gtag) window.gtag = gtag;
    window.gtag('js', new Date());
    window.gtag('config', id);
};
//==========================================

// GOOGLE ANALYTICS 4 (gtag.js) CONDITIONAL
//==========================================
window.setGoogleAnalyticsId = function (id) {
    if (!id || id === "0") {
        console.warn("🟪 GA4 – ID vazio ou 0. Ignorado.");
        return;
    }

    window.__googleAnalyticsInitialized = window.__googleAnalyticsInitialized || [];

    if (window.__googleAnalyticsInitialized.includes(id)) {
        console.log("🟪 GA4 – já inicializado:", id);
        return;
    }

    window.__googleAnalyticsInitialized.push(id);
    console.log("🟪 GA4 – inicializando:", id);

    var scriptId = 'gtag-script-' + id;
    if (!document.getElementById(scriptId)) {
        var s = document.createElement('script');
        s.id = scriptId;
        s.async = true;
        s.src = 'https://www.googletagmanager.com/gtag/js?id=' + id;
        document.head.appendChild(s);
    }

    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    if (!window.gtag) window.gtag = gtag;
    window.gtag('js', new Date());
    window.gtag('config', id);
};
//==========================================

// GA4 LEAD EVENT
//==========================================
window.fireGa4Lead = function (params) {
    if (typeof window.gtag !== 'function') {
        console.warn("🟪 GA4 – gtag não inicializado; evento Lead ignorado.");
        return;
    }
    var payload = Object.assign({ value: 1, currency: 'EUR' }, params || {});
    window.gtag('event', 'generate_lead', payload);
    console.log("🟪 GA4 – evento generate_lead enviado", payload);
};
//==========================================
