// ===========================
// PORTFOLIO LIGHTBOX SYSTEM
// Builder Bee Projects - Professional Image Gallery
// ===========================

class PortfolioLightbox {
    constructor() {
        this.currentIndex = 0;
        this.portfolioItems = [];
        this.lightboxOverlay = null;
        this.isOpen = false;
        
        this.init();
    }
    
    init() {
        // Get all portfolio items
        this.portfolioItems = Array.from(document.querySelectorAll('.portfolio-item[data-lightbox="portfolio"]'));
        
        if (this.portfolioItems.length === 0) {
            console.log('No portfolio items found');
            return;
        }
        
        // Create lightbox HTML
        this.createLightboxHTML();
        
        // Add event listeners
        this.addEventListeners();
        
        console.log(`Portfolio Lightbox initialized with ${this.portfolioItems.length} images`);
    }
    
    createLightboxHTML() {
        // Create lightbox overlay
        this.lightboxOverlay = document.createElement('div');
        this.lightboxOverlay.className = 'lightbox-overlay';
        this.lightboxOverlay.setAttribute('role', 'dialog');
        this.lightboxOverlay.setAttribute('aria-modal', 'true');
        this.lightboxOverlay.setAttribute('aria-label', 'Image gallery');
        
        this.lightboxOverlay.innerHTML = `
            <div class="lightbox-container">
                <button class="lightbox-close" aria-label="Close gallery">
                    <span aria-hidden="true">&times;</span>
                </button>
                <button class="lightbox-nav lightbox-prev" aria-label="Previous image">
                    <span aria-hidden="true">&#8249;</span>
                </button>
                <button class="lightbox-nav lightbox-next" aria-label="Next image">
                    <span aria-hidden="true">&#8250;</span>
                </button>
                <img class="lightbox-image" src="" alt="" />
                <div class="lightbox-info">
                    <h4 class="lightbox-title"></h4>
                    <p class="lightbox-description"></p>
                </div>
            </div>
        `;
        
        document.body.appendChild(this.lightboxOverlay);
    }
    
    addEventListeners() {
        // Portfolio item clicks
        this.portfolioItems.forEach((item, index) => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                this.openLightbox(index);
            });
            
            // Add keyboard support
            item.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    this.openLightbox(index);
                }
            });
            
            // Make items focusable
            item.setAttribute('tabindex', '0');
            item.setAttribute('role', 'button');
            item.setAttribute('aria-label', `View ${item.querySelector('h4')?.textContent || 'project'} in full size`);
        });
        
        // Lightbox controls
        const closeBtn = this.lightboxOverlay.querySelector('.lightbox-close');
        const prevBtn = this.lightboxOverlay.querySelector('.lightbox-prev');
        const nextBtn = this.lightboxOverlay.querySelector('.lightbox-next');
        
        closeBtn.addEventListener('click', () => this.closeLightbox());
        prevBtn.addEventListener('click', () => this.previousImage());
        nextBtn.addEventListener('click', () => this.nextImage());
        
        // Overlay click to close
        this.lightboxOverlay.addEventListener('click', (e) => {
            if (e.target === this.lightboxOverlay) {
                this.closeLightbox();
            }
        });
        
        // Keyboard navigation
        document.addEventListener('keydown', (e) => {
            if (!this.isOpen) return;
            
            switch (e.key) {
                case 'Escape':
                    this.closeLightbox();
                    break;
                case 'ArrowLeft':
                    this.previousImage();
                    break;
                case 'ArrowRight':
                    this.nextImage();
                    break;
            }
        });
        
        // Touch/swipe support for mobile
        let startX = 0;
        let endX = 0;
        
        this.lightboxOverlay.addEventListener('touchstart', (e) => {
            startX = e.touches[0].clientX;
        });
        
        this.lightboxOverlay.addEventListener('touchend', (e) => {
            endX = e.changedTouches[0].clientX;
            const diff = startX - endX;
            
            if (Math.abs(diff) > 50) { // Minimum swipe distance
                if (diff > 0) {
                    this.nextImage(); // Swipe left = next
                } else {
                    this.previousImage(); // Swipe right = previous
                }
            }
        });
    }
    
    openLightbox(index) {
        this.currentIndex = index;
        this.isOpen = true;
        
        // Update image and info
        this.updateLightboxContent();
        
        // Show lightbox
        this.lightboxOverlay.classList.add('active');
        document.body.style.overflow = 'hidden'; // Prevent background scrolling
        
        // Focus management for accessibility
        const closeBtn = this.lightboxOverlay.querySelector('.lightbox-close');
        closeBtn.focus();
        
        // Announce to screen readers
        this.announceToScreenReader(`Viewing image ${index + 1} of ${this.portfolioItems.length}`);
    }
    
    closeLightbox() {
        this.isOpen = false;
        this.lightboxOverlay.classList.remove('active');
        document.body.style.overflow = ''; // Restore scrolling
        
        // Return focus to the portfolio item that was clicked
        if (this.portfolioItems[this.currentIndex]) {
            this.portfolioItems[this.currentIndex].focus();
        }
    }
    
    nextImage() {
        this.currentIndex = (this.currentIndex + 1) % this.portfolioItems.length;
        this.updateLightboxContent();
        this.announceToScreenReader(`Image ${this.currentIndex + 1} of ${this.portfolioItems.length}`);
    }
    
    previousImage() {
        this.currentIndex = (this.currentIndex - 1 + this.portfolioItems.length) % this.portfolioItems.length;
        this.updateLightboxContent();
        this.announceToScreenReader(`Image ${this.currentIndex + 1} of ${this.portfolioItems.length}`);
    }
    
    updateLightboxContent() {
        const currentItem = this.portfolioItems[this.currentIndex];
        const img = currentItem.querySelector('img');
        const title = currentItem.querySelector('h4')?.textContent || '';
        const description = currentItem.querySelector('p')?.textContent || '';
        
        // Update lightbox elements
        const lightboxImg = this.lightboxOverlay.querySelector('.lightbox-image');
        const lightboxTitle = this.lightboxOverlay.querySelector('.lightbox-title');
        const lightboxDescription = this.lightboxOverlay.querySelector('.lightbox-description');
        
        // Set image with loading state
        lightboxImg.style.opacity = '0.5';
        lightboxImg.src = img.src;
        lightboxImg.alt = img.alt;
        
        lightboxImg.onload = () => {
            lightboxImg.style.opacity = '1';
        };
        
        lightboxTitle.textContent = title;
        lightboxDescription.textContent = description;
        
        // Update navigation button states
        const prevBtn = this.lightboxOverlay.querySelector('.lightbox-prev');
        const nextBtn = this.lightboxOverlay.querySelector('.lightbox-next');
        
        if (this.portfolioItems.length <= 1) {
            prevBtn.style.display = 'none';
            nextBtn.style.display = 'none';
        } else {
            prevBtn.style.display = 'flex';
            nextBtn.style.display = 'flex';
        }
    }
    
    announceToScreenReader(message) {
        // Create or update live region for screen reader announcements
        let liveRegion = document.getElementById('lightbox-live-region');
        if (!liveRegion) {
            liveRegion = document.createElement('div');
            liveRegion.id = 'lightbox-live-region';
            liveRegion.setAttribute('aria-live', 'polite');
            liveRegion.setAttribute('aria-atomic', 'true');
            liveRegion.className = 'sr-only';
            document.body.appendChild(liveRegion);
        }
        
        liveRegion.textContent = message;
    }
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    // Wait a bit for other scripts to load
    setTimeout(() => {
        new PortfolioLightbox();
    }, 100);
});

// Also initialize if DOM is already loaded
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        setTimeout(() => {
            new PortfolioLightbox();
        }, 100);
    });
} else {
    setTimeout(() => {
        new PortfolioLightbox();
    }, 100);
}

console.log('Portfolio Lightbox script loaded successfully! 🐝');

