function initGalleryPreviews() {
    const previews = document.querySelectorAll('.preview-gallery');

    previews.forEach((img) => {
        // Prevent double initialization
        if (img.dataset.previewInitialized) return;

        img.dataset.previewInitialized = 'true';

        let images = [];

        try {
            images = JSON.parse(img.dataset.gallery);
        } catch (e) {
            console.error('Invalid gallery JSON', e);
            return;
        }

        if (images.length <= 1) return;

        const original = img.src;

        let index = 0;
        let interval = null;

        const startPreview = () => {
            console.log("startPreview");
            interval = setInterval(() => {
                index = (index + 1) % images.length;
                img.src = images[index];
            }, 700);
        };

        const stopPreview = () => {
            console.log("stopPreview");
            clearInterval(interval);
            interval = null;

            index = 0;
            img.src = original;
        };

        img.addEventListener('mouseenter', startPreview);
        img.addEventListener('mouseleave', stopPreview);
    });
}

// Initial page load
document.addEventListener('DOMContentLoaded', initGalleryPreviews);

// Livewire v3 navigation/update
document.addEventListener('contentChanged', initGalleryPreviews);