// Mobile Menu Toggle
const navToggle = document.getElementById('nav-toggle');
const navMenu = document.getElementById('nav-menu');
const navLinks = document.querySelectorAll('.nav-link');

navToggle.addEventListener('click', () => {
    navMenu.classList.toggle('active');
});

navLinks.forEach(link => {
    link.addEventListener('click', () => {
        navMenu.classList.remove('active');
    });
});

// Smooth Scroll
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if (target) {
            const headerOffset = 80;
            const elementPosition = target.getBoundingClientRect().top;
            const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

            window.scrollTo({
                top: offsetPosition,
                behavior: 'smooth'
            });
        }
    });
});

// Header Scroll Effect
let lastScroll = 0;
const header = document.getElementById('header');

window.addEventListener('scroll', () => {
    const currentScroll = window.pageYOffset;
    
    if (currentScroll > 100) {
        header.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)';
    } else {
        header.style.boxShadow = 'none';
    }
    
    lastScroll = currentScroll;
});

// Load Gallery Images
function loadGalleryImages() {
    const galleryGrid = document.getElementById('gallery-grid');
    const imageExtensions = ['jpg', 'jpeg', 'png', 'webp'];
    const imageNumbers = [1, 2, 3, 4, 5, 6, 7, 8]; // Basado en las imágenes que viste
    
    // Intentar cargar imágenes numeradas primero
    imageNumbers.forEach(num => {
        imageExtensions.forEach(ext => {
            const imgPath = `gallery_lacabana/${num}.${ext}`;
            const img = new Image();
            img.onload = function() {
                const galleryItem = document.createElement('div');
                galleryItem.className = 'gallery-item';
                galleryItem.innerHTML = `<img src="${imgPath}" alt="La Cabaña - Imagen ${num}">`;
                galleryItem.addEventListener('click', () => openLightbox(imgPath));
                galleryGrid.appendChild(galleryItem);
            };
            img.src = imgPath;
        });
    });
    
    // También intentar cargar cualquier otra imagen en el directorio
    // Esto requeriría una llamada al servidor para listar archivos
    // Por ahora, solo cargamos las numeradas
}

// Lightbox Functionality
let currentImageIndex = 0;
let galleryImages = [];

function openLightbox(imageSrc) {
    const lightbox = document.getElementById('lightbox');
    const lightboxImage = document.getElementById('lightbox-image');
    
    // Obtener todas las imágenes de la galería
    const galleryItems = document.querySelectorAll('.gallery-item img');
    galleryImages = Array.from(galleryItems).map(img => img.src);
    currentImageIndex = galleryImages.indexOf(imageSrc);
    
    if (currentImageIndex === -1) currentImageIndex = 0;
    
    lightboxImage.src = imageSrc;
    lightbox.classList.add('active');
    document.body.style.overflow = 'hidden';
}

function closeLightbox() {
    const lightbox = document.getElementById('lightbox');
    lightbox.classList.remove('active');
    document.body.style.overflow = 'auto';
}

function showNextImage() {
    if (galleryImages.length === 0) return;
    currentImageIndex = (currentImageIndex + 1) % galleryImages.length;
    document.getElementById('lightbox-image').src = galleryImages[currentImageIndex];
}

function showPrevImage() {
    if (galleryImages.length === 0) return;
    currentImageIndex = (currentImageIndex - 1 + galleryImages.length) % galleryImages.length;
    document.getElementById('lightbox-image').src = galleryImages[currentImageIndex];
}

// Lightbox Event Listeners
document.getElementById('lightbox-close').addEventListener('click', closeLightbox);
document.getElementById('lightbox-next').addEventListener('click', showNextImage);
document.getElementById('lightbox-prev').addEventListener('click', showPrevImage);

document.getElementById('lightbox').addEventListener('click', (e) => {
    if (e.target.id === 'lightbox') {
        closeLightbox();
    }
});

// Keyboard Navigation for Lightbox
document.addEventListener('keydown', (e) => {
    const lightbox = document.getElementById('lightbox');
    if (lightbox.classList.contains('active')) {
        if (e.key === 'Escape') {
            closeLightbox();
        } else if (e.key === 'ArrowRight') {
            showNextImage();
        } else if (e.key === 'ArrowLeft') {
            showPrevImage();
        }
    }
});

// Intersection Observer for Animations
const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.style.opacity = '1';
            entry.target.style.transform = 'translateY(0)';
        }
    });
}, observerOptions);

// Load About Section Image
function loadAboutImage() {
    const aboutImg = document.querySelector('.about-img');
    if (!aboutImg) return;
    
    const imageExtensions = ['jpg', 'jpeg', 'png', 'webp'];
    const imageNumbers = [1, 2, 3, 4, 5];
    let imageFound = false;
    
    // Intentar cargar la primera imagen disponible
    function tryLoadImage(index) {
        if (index >= imageNumbers.length || imageFound) return;
        
        const num = imageNumbers[index];
        imageExtensions.forEach(ext => {
            if (imageFound) return;
            
            const imgPath = `gallery_lacabana/${num}.${ext}`;
            const img = new Image();
            
            img.onload = function() {
                if (!imageFound) {
                    aboutImg.src = imgPath;
                    aboutImg.style.display = 'block';
                    const placeholder = aboutImg.nextElementSibling;
                    if (placeholder && placeholder.classList.contains('image-placeholder')) {
                        placeholder.style.display = 'none';
                    }
                    imageFound = true;
                }
            };
            
            img.onerror = function() {
                // Intentar siguiente extensión o número
                if (ext === imageExtensions[imageExtensions.length - 1]) {
                    tryLoadImage(index + 1);
                }
            };
            
            img.src = imgPath;
        });
    }
    
    tryLoadImage(0);
}

// Observe elements for animation
document.addEventListener('DOMContentLoaded', () => {
    const animateElements = document.querySelectorAll('.service-card, .gallery-item, .contact-item');
    animateElements.forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(20px)';
        el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(el);
    });
    
    // Load about section image
    loadAboutImage();
    
    // Load gallery images after DOM is ready
    loadGalleryImages();
});

// Update Google Maps iframe with correct coordinates
// Nota: El iframe actual es un placeholder. Deberías reemplazarlo con el código embed real de Google Maps
// usando el enlace: https://goo.gl/maps/LCYh7rx8zp5LUSq36
