// wwwroot/js/fixedElement.js

export function initializeFixedElement() {
    const fixedElement = document.getElementById('fixedElement');
    const footer = document.getElementById('footer');

    if (!fixedElement || !footer) {
        console.warn('Fixed element or footer not found.');
        return;
    }

    // Definir a media query para telas com largura >= 1024px
    const mediaQuery = window.matchMedia('(min-width: 1024px)');

    // Variável para armazenar a instância do IntersectionObserver
    let observer = null;

    // Função para aplicar estilos de posição fixa
    const applyFixedStyles = () => {
        fixedElement.style.position = 'fixed';
        fixedElement.style.bottom = '0'; // Espaçamento inicial do fundo
        fixedElement.style.transition = 'bottom 0.3s ease';

        // Configuração do Intersection Observer com múltiplos thresholds
        const observerOptions = {
            root: null, // Observa em relação à viewport
            threshold: Array.from({ length: 101 }, (_, i) => i / 100), // Thresholds de 0 a 1 em incrementos de 0.01
        };

        const observerCallback = (entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    // Calcula a quantidade visível do footer
                    const viewportHeight = window.innerHeight;
                    const footerRect = footer.getBoundingClientRect();
                    const visibleFooterHeight = Math.max(viewportHeight - footerRect.top, 0);

                    // Define o espaçamento adicional (em pixels)
                    const margin = 20;

                    // Ajusta a posição bottom do elemento fixo para ficar acima do footer
                    fixedElement.style.bottom = `${visibleFooterHeight + margin}px`;
                } else {
                    // Footer não está visível - mantém o elemento fixo na posição original
                    fixedElement.style.bottom = '0';
                }
            });
        };

        // Inicializar o Intersection Observer
        observer = new IntersectionObserver(observerCallback, observerOptions);
        observer.observe(footer);
    };

    // Função para remover estilos de posição fixa e desconectar o observer
    const removeFixedStyles = () => {
        fixedElement.style.position = '';
        fixedElement.style.bottom = '';
        fixedElement.style.transition = '';

        if (observer) {
            observer.disconnect();
            observer = null;
        }
    };

    // Função para verificar a media query e aplicar/remover estilos
    const checkMediaQuery = (e) => {
        if (e.matches) {
            applyFixedStyles();
        } else {
            removeFixedStyles();
        }
    };

    // Verificar a condição inicial
    if (mediaQuery.matches) {
        applyFixedStyles();
    }

    // Adicionar listener para mudanças na media query
    mediaQuery.addEventListener('change', checkMediaQuery);

    // Retornar uma função de limpeza para desconectar o observer e remover o listener
    return () => {
        removeFixedStyles();
        mediaQuery.removeEventListener('change', checkMediaQuery);
    };
}
