/**
 * Project Gallery JavaScript
 * Provides lightbox functionality for all project galleries
 */

(function() {
    'use strict';
    
    // Create modal only once
    if (document.querySelector('.skill-gallery-modal')) {
        return;
    }
    
    // Create modal elements
    var modal = document.createElement('div');
    modal.className = 'skill-gallery-modal';
    modal.innerHTML = `
        <div class="skill-gallery-content">
            <span class="skill-gallery-close">&times;</span>
            <img src="" alt="">
            <button class="skill-gallery-nav skill-gallery-prev">›</button>
            <button class="skill-gallery-nav skill-gallery-next">‹</button>
            <div class="skill-gallery-counter"></div>
        </div>
    `;
    document.body.appendChild(modal);
    
    var currentIndex = 0;
    var galleryImages = [];
    
    // Initialize gallery
    function initGallery() {
        // Select all gallery items from both Elementor widget and regular project galleries
        var galleryItems = document.querySelectorAll('.skill-project-gallery-widget .gallery-item, .project-gallery .gallery-item');
        galleryImages = [];
        
        galleryItems.forEach(function(item, index) {
            var img = item.querySelector('img');
            if (img) {
                // Get full size image URL from data attribute or link href
                var fullSizeUrl = item.getAttribute('data-full-image');
                
                // If no data attribute, try to get from link href
                if (!fullSizeUrl) {
                    var link = item.querySelector('a');
                    if (link) {
                        fullSizeUrl = link.getAttribute('href');
                    }
                }
                
                // Fallback to image src if no full size URL found
                if (!fullSizeUrl) {
                    fullSizeUrl = img.src;
                }
                
                galleryImages.push({
                    src: fullSizeUrl,
                    alt: img.alt
                });
                
                // Add click event
                item.addEventListener('click', function(e) {
                    e.preventDefault();
                    openGallery(index);
                });
            }
        });
    }
    
    // Open gallery
    function openGallery(index) {
        currentIndex = index;
        updateGalleryImage();
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
    
    // Update gallery image
    function updateGalleryImage() {
        if (galleryImages[currentIndex]) {
            var img = modal.querySelector('img');
            var counter = modal.querySelector('.skill-gallery-counter');
            
            img.src = galleryImages[currentIndex].src;
            img.alt = galleryImages[currentIndex].alt;
            counter.textContent = (currentIndex + 1) + ' / ' + galleryImages.length;
        }
    }
    
    // Navigation
    function nextImage() {
        currentIndex = (currentIndex + 1) % galleryImages.length;
        updateGalleryImage();
    }
    
    function prevImage() {
        currentIndex = (currentIndex - 1 + galleryImages.length) % galleryImages.length;
        updateGalleryImage();
    }
    
    // Close gallery
    function closeGallery() {
        modal.classList.remove('active');
        document.body.style.overflow = 'auto';
    }
    
    // Event listeners
    modal.querySelector('.skill-gallery-close').addEventListener('click', closeGallery);
    modal.querySelector('.skill-gallery-next').addEventListener('click', nextImage);
    modal.querySelector('.skill-gallery-prev').addEventListener('click', prevImage);
    
    // Close on background click
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeGallery();
        }
    });
    
    // Keyboard navigation
    document.addEventListener('keydown', function(e) {
        if (modal.classList.contains('active')) {
            if (e.key === 'Escape') {
                closeGallery();
            } else if (e.key === 'ArrowRight') {
                nextImage();
            } else if (e.key === 'ArrowLeft') {
                prevImage();
            }
        }
    });
    
    // Initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initGallery);
    } else {
        initGallery();
    }
    
    // Initialize for Elementor frontend
    if (window.elementorFrontend) {
        window.elementorFrontend.hooks.addAction('frontend/element_ready/widget', function($scope) {
            if ($scope.find('.skill-project-gallery-widget').length) {
                setTimeout(initGallery, 100);
            }
        });
    }
    
    // Re-initialize when new content is loaded (for AJAX)
    document.addEventListener('DOMContentLoaded', function() {
        // Watch for new gallery items being added
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'childList') {
                    var hasGalleryItems = false;
                    mutation.addedNodes.forEach(function(node) {
                        if (node.nodeType === 1) { // Element node
                            if (node.querySelector && (node.querySelector('.gallery-item') || node.classList.contains('gallery-item'))) {
                                hasGalleryItems = true;
                            }
                        }
                    });
                    if (hasGalleryItems) {
                        setTimeout(initGallery, 100);
                    }
                }
            });
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
    
})();
