// Intersection Observer for lazy loading components
let observers = new Map();

window.setupIntersectionObserver = (element, dotNetRef, threshold = 0.1) => {
    if (!element || observers.has(element)) {
        return; // Already observing this element
    }
    
    let lastIntersectionState = null; // Track previous state to prevent unnecessary calls
    let debounceTimer = null; // Debounce rapid visibility changes

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (dotNetRef) {
                const isIntersecting = entry.isIntersecting && entry.intersectionRatio >= threshold;
                
                // Only call if intersection state actually changed
                if (lastIntersectionState === null || lastIntersectionState !== isIntersecting) {
                    lastIntersectionState = isIntersecting;
                    
                    // Clear any existing debounce timer
                    if (debounceTimer) {
                        clearTimeout(debounceTimer);
                    }
                    
                    // Debounce the callback to prevent rapid fire during scrolling
                    debounceTimer = setTimeout(() => {
                        try {
                            dotNetRef.invokeMethodAsync('OnIntersectionChanged', isIntersecting);
                        } catch (error) {
                            console.warn('Error invoking OnIntersectionChanged:', error);
                        }
                        debounceTimer = null;
                    }, 50); // 50ms debounce
                }
            }
        });
    }, {
        threshold: [0, threshold, 1.0], // Multiple thresholds for better accuracy
        rootMargin: '100px 0px 100px 0px' // Larger margin for smoother loading
    });

    observer.observe(element);
    observers.set(element, { observer, dotNetRef, lastState: lastIntersectionState, debounceTimer });
};

window.cleanupIntersectionObserver = (element) => {
    const observerData = observers.get(element);
    if (observerData) {
        // Clear any pending debounce timer
        if (observerData.debounceTimer) {
            clearTimeout(observerData.debounceTimer);
        }
        observerData.observer.disconnect();
        observers.delete(element);
    }
};

// Clean up all observers when page unloads
window.addEventListener('beforeunload', () => {
    observers.forEach(({ observer }) => observer.disconnect());
    observers.clear();
});

// Scroll to element utility function
window.scrollToElement = (elementId) => {
    const element = document.getElementById(elementId);
    if (element) {
        element.scrollIntoView({ 
            behavior: 'smooth', 
            block: 'start',
            inline: 'nearest'
        });
    }
};
