document.addEventListener('DOMContentLoaded', () => {
    // Check if LightGallery is loaded
    if (typeof lightGallery === 'function') {
        // Select all elements with the class '.lcp-gallery'
        const galleryContainers = document.querySelectorAll('.lcp-gallery');

        galleryContainers.forEach(galleryContainer => {
            // Retrieve the JSON string from the data-lgsettings attribute
            const lgSettingsAttr = galleryContainer.getAttribute('data-lgsettings');
            const initOnLoad = galleryContainer.getAttribute('data-gallery-settings') === 'init-on-load'; // Check for the 'init-on-load' setting
            const isInlineGallery = galleryContainer.classList.contains('lcp-inline-gallery'); // Check if it's an inline gallery

            if (lgSettingsAttr) {
                try {
                    // Parse the JSON string to a JavaScript object
                    const lgSettings = JSON.parse(lgSettingsAttr);

                    // Log the settings to debug
                    console.log("LightGallery Settings:", lgSettings);

                    // Ensure that plugins are mapped to actual functions if available
                    const availablePlugins = {
                        lgZoom: lgZoom,
                        lgThumbnail: lgThumbnail,
                        lgFullScreen: lgFullscreen,
                        lgRotate: lgRotate,
                        lgAutoplay: lgAutoplay,
                        lgShare: lgShare,
                        lgComment: lgComment,
                        lgHash: lgHash,
                        lgPager: lgPager,
                        lgVideo: lgVideo,
                        lgMediumZoom: lgMediumZoom
                    };

                    // Map the plugin names to actual plugin functions
                    if (Array.isArray(lgSettings.plugins)) {
                        lgSettings.plugins = lgSettings.plugins.map(pluginName => availablePlugins[pluginName] || pluginName);
                    }

                    // Initialize LightGallery for the gallery container (only once)
                    let galleryInstance = null;

                    // Initialize the gallery immediately if 'init-on-load' is set or it's an inline gallery
                    if (!galleryContainer.classList.contains('lcp-inline-gallery') || initOnLoad || isInlineGallery) {
                        galleryInstance = lightGallery(galleryContainer, lgSettings);
                        
                        // If it's an inline gallery, immediately open the first item (index 0)
                        if (isInlineGallery) {
                            galleryInstance.openGallery(0);
                            galleryContainer.classList.add('initialized');  // Mark the gallery as initialized
                            
                        }
                    }

                    // Add click event listener to the gallery items
                    const galleryItems = galleryContainer.querySelectorAll('.lcp-gallery-item');
                    galleryItems.forEach((item, index) => {
                        item.addEventListener('click', () => {
                            // Check if galleryInstance is valid and open the gallery at the correct index
                            if (galleryInstance && typeof galleryInstance.openGallery === 'function') {
                                galleryInstance.openGallery(index);  // Pass the index to open the correct image
                            } else {
                                console.error('LightGallery instance is not initialized correctly or missing openGallery method.');
                            }
                        });
                    });

                } catch (error) {
                    console.error('Error parsing data-lgsettings JSON:', error);
                }
            } else {
                console.error('data-lgsettings attribute is missing for a gallery.');
            }
        });
    } else {
        console.error('LightGallery is not defined');
    }
});
