/**
 * Gallery Page JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    // Check if gallery elements exist
    const galleryGrid = document.getElementById('gallery-grid');
    if (!galleryGrid) return;

    // ===== Configuration from PHP (set via data attributes) =====
    const imagesPerLoad = parseInt(galleryGrid.dataset.perLoad) || 4;

    // ===== Variables =====
    const loadMoreBtn = document.getElementById('load-more-btn');
    const noMoreMsg = document.getElementById('no-more-msg');
    const filterBtns = document.querySelectorAll('.gallery-filter-btn');
    const allItems = galleryGrid.querySelectorAll('.gallery-item');

    let visibleCount = imagesPerLoad;
    let currentCategory = 'all';

    // ===== Category Filter =====
    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const category = this.dataset.category;

            // Update active button style
            filterBtns.forEach(b => {
                b.classList.remove('bg-gradient-to-r', 'from-secondary-600', 'to-secondary-800', 'text-white');
                b.classList.add('bg-white', 'text-gray-700', 'shadow-sm');
            });
            this.classList.remove('bg-white', 'text-gray-700', 'shadow-sm');
            this.classList.add('bg-gradient-to-r', 'from-secondary-600', 'to-secondary-800', 'text-white');

            // Update category and reset visible count
            currentCategory = category;
            visibleCount = imagesPerLoad;

            // Apply filter and show/hide items
            updateGalleryDisplay();
        });
    });

    function updateGalleryDisplay() {
        let shownCount = 0;
        let totalInCategory = 0;

        allItems.forEach(item => {
            const itemCategory = item.dataset.category;
            const matchesCategory = currentCategory === 'all' || itemCategory === currentCategory;

            if (matchesCategory) {
                totalInCategory++;
                if (shownCount < visibleCount) {
                    item.classList.remove('hidden');
                    item.style.animation = 'fadeIn 0.5s ease';
                    shownCount++;
                } else {
                    item.classList.add('hidden');
                }
            } else {
                item.classList.add('hidden');
            }
        });

        // Update load more button visibility
        if (shownCount >= totalInCategory) {
            loadMoreBtn.classList.add('hidden');
            if (totalInCategory > imagesPerLoad) {
                noMoreMsg.classList.remove('hidden');
            } else {
                noMoreMsg.classList.add('hidden');
            }
        } else {
            loadMoreBtn.classList.remove('hidden');
            noMoreMsg.classList.add('hidden');
        }
    }

    // ===== Load More =====
    loadMoreBtn.addEventListener('click', function() {
        visibleCount += imagesPerLoad;
        updateGalleryDisplay();
    });

    // ===== Lightbox =====
    const lightbox = document.getElementById('lightbox');
    const lightboxImage = document.getElementById('lightbox-image');
    const lightboxTitle = document.getElementById('lightbox-title');
    const lightboxCounter = document.getElementById('lightbox-counter');
    const lightboxClose = document.getElementById('lightbox-close');
    const lightboxPrev = document.getElementById('lightbox-prev');
    const lightboxNext = document.getElementById('lightbox-next');

    let currentImageIndex = 0;
    let visibleImages = [];

    galleryGrid.addEventListener('click', function(e) {
        const item = e.target.closest('.gallery-item');
        if (!item || item.classList.contains('hidden')) return;

        // Get all visible images
        visibleImages = Array.from(galleryGrid.querySelectorAll('.gallery-item:not(.hidden)'));

        currentImageIndex = visibleImages.indexOf(item);
        showLightboxImage();
        lightbox.classList.remove('hidden');
        lightbox.classList.add('flex');
        document.body.style.overflow = 'hidden';
    });

    function showLightboxImage() {
        const item = visibleImages[currentImageIndex];
        const img = item.querySelector('img');
        const title = item.querySelector('h3')?.textContent || '';

        lightboxImage.src = img.src;
        lightboxImage.alt = img.alt;
        lightboxTitle.textContent = title;
        lightboxCounter.textContent = `${currentImageIndex + 1} / ${visibleImages.length}`;
    }

    function closeLightbox() {
        lightbox.classList.add('hidden');
        lightbox.classList.remove('flex');
        document.body.style.overflow = '';
    }

    lightboxClose.addEventListener('click', closeLightbox);
    lightbox.addEventListener('click', function(e) {
        if (e.target === lightbox) closeLightbox();
    });

    lightboxPrev.addEventListener('click', function(e) {
        e.stopPropagation();
        currentImageIndex = (currentImageIndex + 1) % visibleImages.length;
        showLightboxImage();
    });

    lightboxNext.addEventListener('click', function(e) {
        e.stopPropagation();
        currentImageIndex = (currentImageIndex - 1 + visibleImages.length) % visibleImages.length;
        showLightboxImage();
    });

    // Keyboard navigation
    document.addEventListener('keydown', function(e) {
        if (!lightbox.classList.contains('hidden')) {
            if (e.key === 'Escape') closeLightbox();
            if (e.key === 'ArrowRight') lightboxNext.click();
            if (e.key === 'ArrowLeft') lightboxPrev.click();
        }
    });
});

// CSS Animation
(function() {
    const style = document.createElement('style');
    style.textContent = `
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    `;
    document.head.appendChild(style);
})();
