function loadImage(img) {
    if (img.dataset.src) {
        img.src = img.dataset.src;
        img.removeAttribute("data-src");
    }
    if (img.dataset.srcset) {
        img.srcset = img.dataset.srcset;
        img.removeAttribute("data-srcset");
    }
    img.classList.add("lazy-loading");
    img.addEventListener("load", function() {
        img.classList.remove("lazy-loading");
        img.classList.add("lazy-loaded");
    });
    img.addEventListener("error", function() {
        img.classList.remove("lazy-loading");
        img.classList.add("lazy-error");
        console.error("Image load failed:", img.dataset.src || img.src);
    });
}

function observeImages(rootNode, observer) {
    const images = rootNode.querySelectorAll("img[data-src]:not([src]), img[data-srcset]:not([srcset])");
    images.forEach(function(img) {
        if (!img.classList.contains("lazy-init")) {
            img.classList.add("lazy-init");
        }
        observer.observe(img);
    });
}

function loadAllImages(rootNode) {
    const images = rootNode.querySelectorAll("img[data-src]");
    images.forEach(function(img) {
        loadImage(img);
    });
}

function initLazyLoad(rootNode) {
    const config = {
        root: null,
        rootMargin: "50px",
        threshold: .01
    };
    let observer = null;
    function onIntersection(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                const img = entry.target;
                loadImage(img);
                observer.unobserve(img);
            }
        });
    }
    if ("IntersectionObserver" in window) {
        observer = new IntersectionObserver(onIntersection, config);
        observeImages(rootNode, observer);
        if ("MutationObserver" in window) {
            const observeTarget = rootNode instanceof ShadowRoot ? rootNode : rootNode.body || rootNode;
            const mutationObserver = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.addedNodes && mutation.addedNodes.length > 0) {
                        mutation.addedNodes.forEach(function(node) {
                            if (node.tagName === "IMG" && (node.dataset.src || node.dataset.srcset)) {
                                if (!node.classList.contains("lazy-init")) {
                                    node.classList.add("lazy-init");
                                }
                                observer.observe(node);
                            } else if (node.querySelectorAll) {
                                const images = node.querySelectorAll("img[data-src]:not([src]), img[data-srcset]:not([srcset])");
                                images.forEach(function(img) {
                                    if (!img.classList.contains("lazy-init")) {
                                        img.classList.add("lazy-init");
                                    }
                                    observer.observe(img);
                                });
                            }
                        });
                    }
                });
            });
            mutationObserver.observe(observeTarget, {
                childList: true,
                subtree: true
            });
        }
    } else {
        loadAllImages(rootNode);
    }
    return function refresh() {
        if (observer) {
            observeImages(rootNode, observer);
        }
    };
}

(function() {
    "use strict";
    function init() {
        const refresh = initLazyLoad(document);
        window.LazyLoadRefresh = refresh;
    }
    if (!document.querySelector('script[src*="vunelix-"]')) {
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", init);
        } else {
            init();
        }
    }
})();

export const LazyLoadRefresh = () => {
    if (typeof window !== "undefined" && window.LazyLoadRefresh) {
        window.LazyLoadRefresh();
    }
};

export { initLazyLoad };