function manipulateLoader(image, show = false)
{
    const imageLoader =  image.parentElement.querySelector('.athena-spinner-loader');

    if(show) {
        imageLoader &&
        imageLoader?.classList.contains('athena-helper-hide') &&
        imageLoader?.classList.remove('athena-helper-hide');
    }
    imageLoader && imageLoader?.classList.add('athena-helper-hide');
}


function observeImagesToLoad(imageSelector)
{
    const images = document.querySelectorAll(imageSelector);

    const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                const image = entry.target;
                manipulateLoader(image, true);

                image.src = image.dataset.src;

                image.onload = () => {
                    if(image) image.style.visibility = 'visible';
                    manipulateLoader(image);
                };

                observer.unobserve(image);
            }
        });
    });

    images.forEach((image) => {
        observer.observe(image);
    });
}

export default function lazyLoading(
    imageSelector,
    initialLoadLandingPage = false
)
{
    initialLoadLandingPage ?
        window.addEventListener('searchDataFetched', () => observeImagesToLoad(imageSelector)) :
        observeImagesToLoad(imageSelector);
}