// Eden Park By Dror - Custom JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // Initialize all functionality
    initMobileMenu();
    initSmoothScrolling();
    initGallery();
    initPlants();
    initContactForm();
    initFloatingCTA();
    initLeadCapture();
    initAnimations();
    initImageBackground();
    initWhatsAppCtas();
});

// Mobile Menu Functionality
function initMobileMenu() {
    const menuTrigger = document.getElementById('menuTrigger');
    const mobileMenuOverlay = document.getElementById('mobileMenuOverlay');
    const mobileMenuPanel = document.getElementById('mobileMenuPanel');
    const mobileMenuClose = document.getElementById('mobileMenuClose');
    const mobileMenuLinks = document.querySelectorAll('.mobile-menu-link');

    function toggleMobileMenu() {
        mobileMenuOverlay.classList.toggle('active');
        mobileMenuPanel.classList.toggle('active');
        document.body.style.overflow = mobileMenuPanel.classList.contains('active') ? 'hidden' : '';
    }

    function closeMobileMenu() {
        mobileMenuOverlay.classList.remove('active');
        mobileMenuPanel.classList.remove('active');
        document.body.style.overflow = '';
    }

    // Event listeners
    menuTrigger.addEventListener('click', toggleMobileMenu);
    mobileMenuClose.addEventListener('click', closeMobileMenu);
    mobileMenuOverlay.addEventListener('click', closeMobileMenu);

    // Close menu when clicking on links
    mobileMenuLinks.forEach(link => {
        link.addEventListener('click', closeMobileMenu);
    });

    // Hamburger animation
    menuTrigger.addEventListener('click', function() {
        this.classList.toggle('active');
    });
}

// Smooth Scrolling
function initSmoothScrolling() {
    const links = document.querySelectorAll('a[href^="#"]');
    
    links.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            const targetSection = document.querySelector(targetId);
            
            if (targetSection) {
                const offsetTop = targetSection.offsetTop - 80; // Account for navbar height
                
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// Scroll to Section Function (for buttons)
function scrollToSection(sectionId) {
    const section = document.getElementById(sectionId);
    if (section) {
        const offsetTop = section.offsetTop - 80;
        window.scrollTo({
            top: offsetTop,
            behavior: 'smooth'
        });
    }
}

// Dynamic Gallery Functionality
function initGallery() {
    const galleryMasonry = document.getElementById('galleryMasonry');
    const modal = document.getElementById('galleryModal');
    const modalImage = document.getElementById('modalImage');
    const modalTitle = document.getElementById('modalTitle');
    const modalDescription = document.getElementById('modalDescription');
    const closeBtn = document.querySelector('.close');
    const filterBtns = document.querySelectorAll('.filter-btn');

    // Definir as imagens da pasta galeria (apenas as que existem)
    const imageCategories = {
        galeria: [
            'LVR_01_Fachada_EF3.jpg',
            'LVR_02_Portaria_EF3.jpg',
            'LVR_03_Piscina_descoberta_EF3.jpg',
            'LVR_04_Quadra_Tennis_EF3.jpg'
        ]
    };

    // Função para gerar títulos e descrições baseados no nome da imagem
    function getImageInfo(filename, category) {
        const titles = {
            'LVR_01_Fachada_EF3.jpg': 'Fachada',
            'LVR_02_Portaria_EF3.jpg': 'Portaria',
            'LVR_03_Piscina_descoberta_EF3.jpg': 'Piscina Descoberta',
            'LVR_04_Quadra_Tennis_EF3.jpg': 'Quadra de Tênis'
        };

        const descriptions = {
            'LVR_01_Fachada_EF3.jpg': 'Arquitetura moderna e sofisticada que reflete o padrão de excelência do empreendimento. Design contemporâneo com acabamentos de primeira linha.',
            'LVR_02_Portaria_EF3.jpg': 'Recepção de alto padrão com segurança 24 horas e atendimento diferenciado. Seu primeiro contato com o conforto e a qualidade que você merece.',
            'LVR_03_Piscina_descoberta_EF3.jpg': 'Área de lazer completa com piscina descoberta, perfeita para relaxar e aproveitar momentos de descanso ao ar livre.',
            'LVR_04_Quadra_Tennis_EF3.jpg': 'Quadra de tênis profissional para você praticar seu esporte favorito sem sair de casa. Qualidade e comodidade em um só lugar.'
        };

        return {
            title: titles[filename] || filename.replace('.jpg', ''),
            description: descriptions[filename] || 'Imagens exclusivas do empreendimento ZEN CYRELA E YOO'
        };
    }

    // Função para criar um item da galeria
    function createGalleryItem(filename, category, index) {
        const info = getImageInfo(filename, category);
        const number = String(index + 1).padStart(2, '0');
        
        const item = document.createElement('div');
        item.className = 'gallery-item';
        item.setAttribute('data-category', category);
        
        item.innerHTML = `
            <div class="gallery-image-wrapper">
                <img src="${category}/${filename}" alt="${info.title}" loading="lazy">
            </div>
            <div class="gallery-text" data-number="${number}">
                <div class="gallery-text-content">
                    <h3>${info.title}</h3>
                    <div class="separator"></div>
                    <p>${info.description}</p>
                </div>
            </div>
        `;

        return item;
    }

    // Variáveis do carrossel
    let currentIndex = 0;
    let galleryItems = [];

    // Função para ir para um slide específico
    function goToSlide(index) {
        // Não funciona no mobile - todas as imagens são exibidas
        if (window.innerWidth <= 768) return;
        
        if (galleryItems.length === 0) return;
        if (index < 0) index = galleryItems.length - 1;
        if (index >= galleryItems.length) index = 0;
        
        // Remover active de todos
        galleryItems.forEach(item => {
            item.classList.remove('active');
        });
        
        document.querySelectorAll('.carousel-dot').forEach(dot => {
            dot.classList.remove('active');
        });
        
        // Adicionar active no atual
        if (galleryItems[index]) {
            galleryItems[index].classList.add('active');
        }
        
        const activeDot = document.querySelector(`.carousel-dot[data-index="${index}"]`);
        if (activeDot) {
            activeDot.classList.add('active');
        }
        
        currentIndex = index;
    }

    // Função para próximo slide
    function nextSlide() {
        // Não funciona no mobile
        if (window.innerWidth <= 768) return;
        if (galleryItems.length === 0) return;
        const nextIndex = (currentIndex + 1) % galleryItems.length;
        goToSlide(nextIndex);
    }

    // Função para slide anterior
    function prevSlide() {
        // Não funciona no mobile
        if (window.innerWidth <= 768) return;
        if (galleryItems.length === 0) return;
        const prevIndex = (currentIndex - 1 + galleryItems.length) % galleryItems.length;
        goToSlide(prevIndex);
    }

    // Função para carregar todas as imagens
    function loadGalleryImages() {
        galleryMasonry.innerHTML = '';
        galleryItems = [];
        
        const carouselDots = document.getElementById('carouselDots');
        if (carouselDots) carouselDots.innerHTML = '';
        
        let index = 0;
        const isMobileCheck = window.innerWidth <= 768;
        
        // Carregar imagens de todas as categorias
        Object.keys(imageCategories).forEach(category => {
            imageCategories[category].forEach(filename => {
                const galleryItem = createGalleryItem(filename, category, index);
                galleryMasonry.appendChild(galleryItem);
                galleryItems.push(galleryItem);
                
                // Criar dot apenas no desktop
                if (carouselDots && !isMobileCheck) {
                    const dot = document.createElement('button');
                    dot.className = 'carousel-dot';
                    dot.setAttribute('data-index', index);
                    if (index === 0) dot.classList.add('active');
                    dot.addEventListener('click', () => goToSlide(index));
                    carouselDots.appendChild(dot);
                }
                
                index++;
            });
        });

        // Verificar se é mobile
        const isMobile = window.innerWidth <= 768;
        
        // Obter controles do carrossel
        const carouselPrevBtn = document.getElementById('carouselPrev');
        const carouselNextBtn = document.getElementById('carouselNext');
        const carouselDotsEl = document.getElementById('carouselDots');
        
        // Ajustar masonry no mobile
        if (isMobile && galleryMasonry) {
            galleryMasonry.style.position = 'relative';
            galleryMasonry.style.display = 'flex';
            galleryMasonry.style.flexDirection = 'column';
        }
        
        if (isMobile) {
            // No mobile, mostrar todos os itens sem posicionamento absoluto
            galleryItems.forEach(item => {
                item.classList.add('active');
                item.style.position = 'relative';
                item.style.top = 'auto';
                item.style.left = 'auto';
                item.style.display = 'flex';
                item.style.flexDirection = 'column';
                item.style.opacity = '1';
                item.style.visibility = 'visible';
                item.style.width = '100%';
                item.style.zIndex = 'auto';
            });
            
            // Esconder controles
            if (carouselPrevBtn) carouselPrevBtn.style.display = 'none';
            if (carouselNextBtn) carouselNextBtn.style.display = 'none';
            if (carouselDotsEl) carouselDotsEl.style.display = 'none';
        } else {
            // No desktop, mostrar apenas o primeiro item (carrossel)
            setTimeout(() => {
                if (galleryItems.length > 0) {
                    goToSlide(0);
                }
            }, 100);
        }

        // Adicionar event listeners para os itens da galeria
        addGalleryEventListeners();
        
        // Adicionar event listeners para navegação (apenas no desktop)
        if (!isMobile && carouselPrevBtn && carouselNextBtn) {
            carouselPrevBtn.onclick = prevSlide;
            carouselNextBtn.onclick = nextSlide;
            carouselPrevBtn.style.display = '';
            carouselNextBtn.style.display = '';
        } else {
            // Garantir que estão ocultos no mobile
            if (carouselPrevBtn) {
                carouselPrevBtn.onclick = null;
                carouselPrevBtn.style.display = 'none';
            }
            if (carouselNextBtn) {
                carouselNextBtn.onclick = null;
                carouselNextBtn.style.display = 'none';
            }
        }
    }
    
    // Navegação por teclado
    function handleKeyboardNavigation(e) {
        // Não funciona no mobile
        if (window.innerWidth <= 768) return;
        
        const gallerySection = document.getElementById('gallery');
        if (gallerySection) {
            const rect = gallerySection.getBoundingClientRect();
            const isVisible = rect.top < window.innerHeight && rect.bottom > 0;
            if (isVisible) {
                if (e.key === 'ArrowLeft') {
                    e.preventDefault();
                    prevSlide();
                }
                if (e.key === 'ArrowRight') {
                    e.preventDefault();
                    nextSlide();
                }
            }
        }
    }
    
    // Adicionar listener de teclado apenas uma vez
    if (!window.galleryKeyboardListenerAdded) {
        document.addEventListener('keydown', handleKeyboardNavigation);
        window.galleryKeyboardListenerAdded = true;
    }

    // Função para adicionar event listeners
    function addGalleryEventListeners() {
        const galleryItems = document.querySelectorAll('.gallery-item');
        
        galleryItems.forEach(item => {
            item.addEventListener('click', function() {
                const img = this.querySelector('img');
                const textDiv = this.querySelector('.gallery-text');
                const title = textDiv.querySelector('h3').textContent;
                const description = textDiv.querySelector('p').textContent;

                modalImage.src = img.src;
                modalImage.alt = img.alt;
                modalTitle.textContent = title;
                modalDescription.textContent = description;
                modal.style.display = 'block';
                document.body.style.overflow = 'hidden';
            });
        });
    }

    // Função para filtrar imagens
    function filterGallery(filter) {
        const galleryItems = document.querySelectorAll('.gallery-item');
        
            galleryItems.forEach(item => {
                const category = item.getAttribute('data-category');
                
                if (filter === 'all' || category === filter) {
                    item.style.display = 'block';
                    setTimeout(() => {
                        item.style.opacity = '1';
                        item.style.transform = 'scale(1)';
                    }, 100);
                } else {
                    item.style.opacity = '0';
                    item.style.transform = 'scale(0.8)';
                    setTimeout(() => {
                        item.style.display = 'none';
                    }, 300);
                }
            });
    }

    // Event listeners para filtros
    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const filter = this.getAttribute('data-filter');
            
            // Atualizar botão ativo
            filterBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // Filtrar galeria
            filterGallery(filter);
        });
    });

    // Event listeners para modal
    if (closeBtn) {
        closeBtn.addEventListener('click', closeModal);
    }
    
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeModal();
            }
        });
    }

    function closeModal() {
        modal.style.display = 'none';
        document.body.style.overflow = '';
    }

    // Carregar imagens iniciais
    loadGalleryImages();
    
    // Ajustar comportamento no redimensionamento
    let resizeTimeout;
    window.addEventListener('resize', function() {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(function() {
            const isMobileResize = window.innerWidth <= 768;
            const carouselPrevResize = document.getElementById('carouselPrev');
            const carouselNextResize = document.getElementById('carouselNext');
            const carouselDotsResize = document.getElementById('carouselDots');
            
            if (isMobileResize) {
                // Ajustar masonry no mobile
                if (galleryMasonry) {
                    galleryMasonry.style.position = 'relative';
                    galleryMasonry.style.display = 'flex';
                    galleryMasonry.style.flexDirection = 'column';
                }
                
                // Mostrar todos os itens no mobile sem posicionamento absoluto
                galleryItems.forEach(item => {
                    item.classList.add('active');
                    item.style.position = 'relative';
                    item.style.top = 'auto';
                    item.style.left = 'auto';
                    item.style.display = 'flex';
                    item.style.flexDirection = 'column';
                    item.style.opacity = '1';
                    item.style.visibility = 'visible';
                    item.style.width = '100%';
                    item.style.zIndex = 'auto';
                });
                
                // Esconder controles
                if (carouselPrevResize) carouselPrevResize.style.display = 'none';
                if (carouselNextResize) carouselNextResize.style.display = 'none';
                if (carouselDotsResize) carouselDotsResize.style.display = 'none';
            } else {
                // Mostrar apenas o primeiro no desktop
                if (galleryItems.length > 0) {
                    goToSlide(currentIndex);
                }
                
                // Mostrar controles
                if (carouselPrevResize) carouselPrevResize.style.display = '';
                if (carouselNextResize) carouselNextResize.style.display = '';
                if (carouselDotsResize) carouselDotsResize.style.display = '';
            }
        }, 250);
    });
}

// Plants Section Functionality
function initPlants() {
    const plantsGrid = document.getElementById('plantsGrid');
    const plantsModal = document.getElementById('plantsModal');
    const plantsModalImage = document.getElementById('plantsModalImage');
    const plantsModalTitle = document.getElementById('plantsModalTitle');
    const plantsModalDescription = document.getElementById('plantsModalDescription');
    const plantsCloseBtn = document.querySelector('.plants-close');
    const categoryBtns = document.querySelectorAll('.category-btn');

    // Lista de plantas - atualizada com os arquivos da pasta plantas
    const plantsCategories = {
        arquitetonica: [
            '01_CYRIP_PLANTA+TIPO+320m+PADRAO+T01_P5-1920w.png',
            '08_CYRIP_PLANTA+TIPO+270m-+PADRAO+T02_P5+(2)-1920w.png'
        ]
    };

    // Função para extrair informações do nome do arquivo
    function extractPlantInfo(filename) {
        // Extrair informações do nome do arquivo
        // Formato esperado: 01_CYRIP_PLANTA+TIPO+320m+PADRAO+T01_P5-1920w.png
        const match = filename.match(/(\d+)_CYRIP_PLANTA\+TIPO\+(\d+)m\+PADRAO\+T(\d+)/);
        
        if (match) {
            const torreNum = match[3];
            const area = match[2];
            return {
                torre: `Torre ${torreNum}`,
                area: `${area}m²`,
                tipo: 'Padrão'
            };
        }
        
        return null;
    }

    // Função para obter informações das plantas
    function getPlantInfo(filename, category) {
        const info = extractPlantInfo(filename);
        
        if (info) {
            return {
                title: `${info.torre} - ${info.tipo} ${info.area}`,
                description: `Apartamento de ${info.area} na ${info.torre} com layout funcional e espaços bem distribuídos.`
            };
        }
        
        // Fallback para nomes de arquivo não reconhecidos
        const cleanName = filename
            .replace(/^\d+_CYRIP_PLANTA\+TIPO\+/, '')
            .replace(/\+PADRAO\+.*$/, '')
            .replace(/-1920w\.png/, '')
            .replace(/\.(png|jpg|jpeg)$/i, '');
        
        return {
            title: cleanName || 'Planta Arquitetônica',
            description: 'Planta arquitetônica do ZEN CYRELA E YOO'
        };
    }

    // Função para criar um item da planta
    function createPlantItem(filename, category) {
        const info = getPlantInfo(filename, category);
        
        const item = document.createElement('div');
        item.className = 'plant-item';
        item.setAttribute('data-category', category);
        
        item.innerHTML = `
            <div class="plant-image-container">
                <img src="plantas/${filename}" alt="${info.title}" loading="lazy">
                <div class="plant-overlay">
                    <div class="plant-info">
                        <h4>${info.title}</h4>
                        <p>${info.description}</p>
                        <button class="view-plant-btn">
                            <i class="fas fa-eye"></i>
                            <span>Ver Planta</span>
                        </button>
                    </div>
                </div>
            </div>
            <div class="plant-details">
                <h3>${info.title}</h3>
                <p>${info.description}</p>
                <div class="plant-actions">
                    <button class="action-btn download">
                        <i class="fas fa-download"></i>
                    </button>
                    <button class="action-btn share">
                        <i class="fas fa-share"></i>
                    </button>
                    <button class="action-btn zoom">
                        <i class="fas fa-search-plus"></i>
                    </button>
                </div>
            </div>
        `;

        return item;
    }

    // Função para carregar todas as plantas
    function loadPlants() {
        plantsGrid.innerHTML = '';
        
        // Carregar plantas de todas as categorias
        Object.keys(plantsCategories).forEach(category => {
            plantsCategories[category].forEach(filename => {
                const plantItem = createPlantItem(filename, category);
                plantsGrid.appendChild(plantItem);
            });
        });

        // Adicionar event listeners
        addPlantsEventListeners();
    }

    // Função para adicionar event listeners
    function addPlantsEventListeners() {
        const plantItems = document.querySelectorAll('.plant-item');
        
        plantItems.forEach(item => {
            const viewBtn = item.querySelector('.view-plant-btn');
            const downloadBtn = item.querySelector('.download');
            const shareBtn = item.querySelector('.share');
            const zoomBtn = item.querySelector('.zoom');
            const img = item.querySelector('img');
            
            viewBtn.addEventListener('click', function() {
                const overlay = item.querySelector('.plant-overlay');
                const title = overlay.querySelector('h4').textContent;
                const description = overlay.querySelector('p').textContent;

                plantsModalImage.src = img.src;
                plantsModalImage.alt = img.alt;
                plantsModalTitle.textContent = title;
                plantsModalDescription.textContent = description;
                plantsModal.style.display = 'block';
                document.body.style.overflow = 'hidden';
            });

            downloadBtn.addEventListener('click', function() {
                // Simular download
                const link = document.createElement('a');
                link.href = img.src;
                const extension = img.src.split('.').pop();
                link.download = img.alt + '.' + extension;
                link.click();
            });

            shareBtn.addEventListener('click', function() {
                if (navigator.share) {
                    navigator.share({
                        title: item.querySelector('h3').textContent,
                        text: item.querySelector('p').textContent,
                        url: window.location.href
                    });
                } else {
                    // Fallback para copiar URL
                    navigator.clipboard.writeText(window.location.href);
                    alert('Link copiado para a área de transferência!');
                }
            });

            zoomBtn.addEventListener('click', function() {
                viewBtn.click();
            });
        });
    }

    // Função para filtrar plantas
    function filterPlants(category) {
        const plantItems = document.querySelectorAll('.plant-item');
        
        plantItems.forEach(item => {
            const itemCategory = item.getAttribute('data-category');
            
            if (category === 'all' || itemCategory === category) {
                item.style.display = 'block';
                setTimeout(() => {
                    item.style.opacity = '1';
                    item.style.transform = 'scale(1)';
                }, 100);
            } else {
                item.style.opacity = '0';
                item.style.transform = 'scale(0.8)';
                setTimeout(() => {
                    item.style.display = 'none';
                }, 300);
            }
        });
    }

    // Event listeners para categorias
    categoryBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const category = this.getAttribute('data-category');
            
            // Atualizar botão ativo
            categoryBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // Filtrar plantas
            filterPlants(category);
        });
    });

    // Event listeners para modal
    if (plantsCloseBtn) {
        plantsCloseBtn.addEventListener('click', closePlantsModal);
    }
    
    if (plantsModal) {
        plantsModal.addEventListener('click', function(e) {
            if (e.target === plantsModal) {
                closePlantsModal();
            }
        });
    }

    function closePlantsModal() {
        plantsModal.style.display = 'none';
        document.body.style.overflow = '';
    }

    // Carregar plantas iniciais
    loadPlants();
}

// Contact Form Functionality
function initContactForm() {
    const contactForm = document.getElementById('contactForm');
    const leadForm = document.getElementById('leadForm');

    function handleFormSubmit(form, formName) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = Object.fromEntries(formData);
            
            // Redireciona para WhatsApp com os dados do formulário
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Enviando...';
            submitBtn.disabled = true;
            
            const name = data.name || '';
            const phone = data.phone || '';
            const propertyType = data.propertyType || '';
            const budget = data.budget || '';
            const message = (data.message || '').trim();

            const email = data.email || '';
            const lines = [
                `Olá, Mari!` ,
                `Meu nome: ${name}`,
                email ? `E-mail: ${email}` : '',
                phone ? `Telefone/WhatsApp: ${phone}` : '',
                message ? `Mensagem: ${message}` : ''
            ].filter(Boolean);

            const waText = encodeURIComponent(lines.join('\n'));
            const waNumber = '5511939148558';
            const waUrl = `https://wa.me/${waNumber}?text=${waText}`;

            if (typeof gtag !== 'undefined') {
                gtag('event', 'conversion', { 'send_to': 'AW-11232983179/whatsapp_click' });
            }

            window.open(waUrl, '_blank', 'noopener');
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        });
    }

    if (contactForm) {
        handleFormSubmit(contactForm, 'contact_form');
    }
    
    if (leadForm) {
        handleFormSubmit(leadForm, 'lead_form');
    }
}

// Floating CTA Functionality
function initFloatingCTA() {
    const floatingCTA = document.getElementById('floatingCta');
    
    if (floatingCTA) {
        floatingCTA.addEventListener('click', function() {
            // Abrir WhatsApp diretamente
            openWhatsApp();
        });
        
        // Hide floating CTA after scroll
        let hideTimeout;
        window.addEventListener('scroll', function() {
            clearTimeout(hideTimeout);
            floatingCTA.style.opacity = '1';
            floatingCTA.style.transform = 'translateY(0)';
            
            hideTimeout = setTimeout(() => {
                if (window.scrollY > 500) {
                    floatingCTA.style.opacity = '0.7';
                    floatingCTA.style.transform = 'translateY(10px)';
                }
            }, 2000);
        });
    }
}

// Lead Capture Modal
function initLeadCapture() {
    const leadModalOverlay = document.getElementById('leadModalOverlay');
    const leadModalClose = document.getElementById('leadModalClose');
    
    if (leadModalOverlay && leadModalClose) {
        leadModalClose.addEventListener('click', function() {
            leadModalOverlay.style.display = 'none';
            document.body.style.overflow = '';
        });
        
        leadModalOverlay.addEventListener('click', function(e) {
            if (e.target === leadModalOverlay) {
                leadModalOverlay.style.display = 'none';
                document.body.style.overflow = '';
            }
        });
    }
}

// Animations and Intersection Observer
function initAnimations() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-in');
            }
        });
    }, observerOptions);

    // Observe elements for animation
    const animateElements = document.querySelectorAll('.feature, .service-card, .location-feature, .gallery-item, .plant-item');
    animateElements.forEach(el => {
        observer.observe(el);
    });

    // Add CSS for animations
    const style = document.createElement('style');
    style.textContent = `
        .feature, .service-card, .location-feature, .gallery-item, .plant-item {
            opacity: 0;
            transform: translateY(30px);
            transition: all 0.6s cubic-bezier(0.25, 0.46, 0.45, 0.94);
        }
        
        .feature.animate-in, .service-card.animate-in, .location-feature.animate-in, .gallery-item.animate-in, .plant-item.animate-in {
            opacity: 1;
            transform: translateY(0);
        }
        
        .feature:nth-child(1) { transition-delay: 0.1s; }
        .feature:nth-child(2) { transition-delay: 0.2s; }
        .feature:nth-child(3) { transition-delay: 0.3s; }
        
        .service-card:nth-child(1) { transition-delay: 0.1s; }
        .service-card:nth-child(2) { transition-delay: 0.2s; }
        .service-card:nth-child(3) { transition-delay: 0.3s; }
        .service-card:nth-child(4) { transition-delay: 0.4s; }
        .service-card:nth-child(5) { transition-delay: 0.5s; }
        .service-card:nth-child(6) { transition-delay: 0.6s; }
    `;
    document.head.appendChild(style);
}

// Video Background Functionality
function initImageBackground() {
    const heroVideo = document.getElementById('hero-video');
    
    // Ensure video iframe loads properly
    if (heroVideo) {
        heroVideo.addEventListener('load', function() {
            console.log('Hero video loaded successfully');
        });
    }
}

// Navbar Scroll Effect
window.addEventListener('scroll', function() {
    const navbar = document.querySelector('.navbar');
    const scrollY = window.scrollY;
    
    if (scrollY > 50) {
        navbar.style.background = 'rgba(240, 247, 243, 0.99)';
        navbar.style.boxShadow = '0 4px 20px rgba(26, 61, 46, 0.1)';
        navbar.style.borderBottom = '1px solid rgba(45, 134, 89, 0.3)';
    } else {
        navbar.style.background = 'rgba(240, 247, 243, 0.98)';
        navbar.style.boxShadow = '0 2px 10px rgba(26, 61, 46, 0.08)';
        navbar.style.borderBottom = '1px solid rgba(45, 134, 89, 0.2)';
    }
});

// Parallax Effect for Sections
function initParallaxEffect() {
    const parallaxElements = document.querySelectorAll('.about-bg-image, .services-bg-image, .gallery-bg-image, .plants-bg-image');
    
    window.addEventListener('scroll', function() {
        const scrolled = window.pageYOffset;
        
        parallaxElements.forEach(element => {
            const rate = scrolled * -0.5;
            element.style.transform = `translateY(${rate}px)`;
        });
    });
}

// Initialize parallax effect
initParallaxEffect();

// Counter Animation for Features - Disabled to prevent interference with feature descriptions
// function initCounterAnimation() {
//     const counters = document.querySelectorAll('.feature-content p');
//     
//     const counterObserver = new IntersectionObserver((entries) => {
//         entries.forEach(entry => {
//             if (entry.isIntersecting) {
//                 const counter = entry.target;
//                 const text = counter.textContent;
//                 
//                 // Extract numbers from text
//                 const numbers = text.match(/\d+/g);
//                 if (numbers) {
//                     animateCounter(counter, numbers);
//                 }
//             }
//         });
//     }, {
//         threshold: 0.5
//     });
//     
//     counters.forEach(counter => {
//         counterObserver.observe(counter);
//     });
// }

// function animateCounter(element, numbers) {
//     numbers.forEach(number => {
//         const targetNumber = parseInt(number);
//         let currentNumber = 0;
//         const increment = targetNumber / 50;
//         
//         const timer = setInterval(() => {
//             currentNumber += increment;
//             if (currentNumber >= targetNumber) {
//                 currentNumber = targetNumber;
//                 clearInterval(timer);
//             }
//             
//             element.textContent = element.textContent.replace(number, Math.floor(currentNumber));
//         }, 30);
//     });
// }

// Initialize counter animation
// initCounterAnimation();

// Form Validation Enhancement
function initFormValidation() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        const inputs = form.querySelectorAll('input, select');
        
        inputs.forEach(input => {
            input.addEventListener('blur', function() {
                validateField(this);
            });
            
            input.addEventListener('input', function() {
                if (this.classList.contains('error')) {
                    validateField(this);
                }
            });
        });
    });
}

function validateField(field) {
    const value = field.value.trim();
    let isValid = true;
    let errorMessage = '';
    
    // Required field validation
    if (field.hasAttribute('required') && !value) {
        isValid = false;
        errorMessage = 'Este campo é obrigatório';
    }
    
    // Email validation
    if (field.type === 'email' && value) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(value)) {
            isValid = false;
            errorMessage = 'Digite um email válido';
        }
    }
    
    // Phone validation
    if (field.type === 'tel' && value) {
        const phoneRegex = /^[\d\s\(\)\-\+]+$/;
        if (!phoneRegex.test(value) || value.length < 10) {
            isValid = false;
            errorMessage = 'Digite um telefone válido';
        }
    }
    
    // Update field appearance
    if (isValid) {
        field.classList.remove('error');
        field.style.borderColor = 'var(--accent-color)';
        removeErrorMessage(field);
    } else {
        field.classList.add('error');
        field.style.borderColor = '#e74c3c';
        showErrorMessage(field, errorMessage);
    }
    
    return isValid;
}

function showErrorMessage(field, message) {
    removeErrorMessage(field);
    
    const errorDiv = document.createElement('div');
    errorDiv.className = 'field-error';
    errorDiv.textContent = message;
    errorDiv.style.color = '#e74c3c';
    errorDiv.style.fontSize = '0.8rem';
    errorDiv.style.marginTop = '5px';
    
    field.parentNode.appendChild(errorDiv);
}

function removeErrorMessage(field) {
    const existingError = field.parentNode.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
}

// Initialize form validation
initFormValidation();

// Performance Optimization
function initPerformanceOptimizations() {
    // Lazy loading for images
    const images = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
    
    // Preload critical resources
    const criticalImages = [
        'img344.jpg',
        'images/about-bg.jpg',
        'images/amenities-bg.jpg'
    ];
    
    criticalImages.forEach(src => {
        const link = document.createElement('link');
        link.rel = 'preload';
        link.as = 'image';
        link.href = src;
        document.head.appendChild(link);
    });
}

// Initialize performance optimizations
initPerformanceOptimizations();

// Error Handling
window.addEventListener('error', function(e) {
    console.error('JavaScript Error:', e.error);
    
    // Track errors (if analytics is available)
    if (typeof gtag !== 'undefined') {
        gtag('event', 'javascript_error', {
            'error_message': e.error.message,
            'error_filename': e.filename,
            'error_lineno': e.lineno
        });
    }
});

// Console welcome message
console.log(`
🏢 ZEN CYRELA E YOO - Minimalista. Pura Essência. 🏢

Desenvolvido com ❤️ para quem busca elegância e sofisticação.
`);

// WhatsApp Helpers
function openWhatsApp(defaultMessage) {
    const waNumber = '5511939148558';
    const text = encodeURIComponent(defaultMessage || 'Olá, Mari! Gostaria de mais informações.');
    const url = `https://wa.me/${waNumber}?text=${text}`;
    if (typeof gtag !== 'undefined') {
        gtag('event', 'conversion', { 'send_to': 'AW-11232983179/whatsapp_click' });
    }
    window.open(url, '_blank', 'noopener');
}

function initWhatsAppCtas() {
    const heroBtn = document.getElementById('ctaWhatsAppHero');
    const aboutBtn = document.getElementById('ctaWhatsAppAbout');
    
    if (heroBtn) {
        heroBtn.href = '#';
        heroBtn.addEventListener('click', function(e) {
            e.preventDefault();
            openWhatsApp('Olá, Mari! Vim pela página e quero mais informações sobre o ZEN CYRELA E YOO.');
        });
    }
    
    if (aboutBtn) {
        aboutBtn.href = '#';
        aboutBtn.addEventListener('click', function(e) {
            e.preventDefault();
            openWhatsApp('Olá, Mari! Vim pela página e quero mais informações sobre o ZEN CYRELA E YOO.');
        });
    }
}
