// Consultoria - Minimalist JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // Initialize essential functionality
    initWhatsAppCtas();
    initImageBackground();
    initContactForm();
    initGallery();
    initModal();
    initPlants();
    initNavbar();
    initSmoothScroll();
    initProjectsMenu();
});

// Image Background Functionality
function initImageBackground() {
    const heroImage = document.getElementById('hero-image');
    
    // Ensure image loads properly
    if (heroImage) {
        heroImage.addEventListener('load', function() {
            console.log('Hero image loaded successfully');
        });
        
        heroImage.addEventListener('error', function() {
            console.log('Hero image failed to load');
        });
    }
}

// Navbar Functionality
function initNavbar() {
    const navbar = document.querySelector('.navbar-modern');
    
    if (navbar) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        });
    }
}

// Smooth Scroll for Navigation Links
function initSmoothScroll() {
    const links = document.querySelectorAll('.navbar-link[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 - 100;
                
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// 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(`
🌿 Consultoria Mari Mantovani 🌿
Corretora de Imóveis | Cyrela

Página minimalista desenvolvida com foco na essência.
`);

// 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 aboutBtn = document.getElementById('ctaWhatsAppAbout');
    
    if (aboutBtn) {
        aboutBtn.href = '#';
        aboutBtn.addEventListener('click', function(e) {
            e.preventDefault();
            openWhatsApp('Olá, Mari! Vim pela página e gostaria de mais informações sobre imóveis próximos a parques.');
        });
    }
}

// Contact Form Functionality
function initContactForm() {
    const contactForm = document.getElementById('contactForm');
    
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = Object.fromEntries(formData);
            
            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 email = data.email || '';
            const phone = data.phone || '';
            const message = data.message || '';
            
            const lines = [
                `Olá, Mari!`,
                `Meu nome: ${name}`,
                email ? `E-mail: ${email}` : '',
                phone ? `Telefone: ${phone}` : '',
                message ? `Mensagem: ${message}` : '',
                `Vim pela página e gostaria de mais informações sobre imóveis próximos a parques.`
            ].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');
            
            // Reset form after a delay
            setTimeout(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
                contactForm.reset();
            }, 1000);
        });
    }
}

// Gallery Functionality
function initGallery() {
    const galleryGrid = document.getElementById('galleryGrid');
    
    if (!galleryGrid) return;
    
    // Usar apenas algumas imagens necessárias da galeria
    const leisureAreas = [
        { 
            src: 'galeria/img333.jpg', 
            title: 'Vista Panorâmica', 
            description: 'Vista privilegiada do empreendimento com áreas verdes ao redor.'
        },
        { 
            src: 'galeria/img344.jpg', 
            title: 'Entrada Principal', 
            description: 'Entrada elegante e acolhedora do empreendimento.'
        },
        { 
            src: 'galeria/img356.jpg', 
            title: 'Jardim Central', 
            description: 'Jardim central com paisagismo cuidadosamente planejado.'
        },
        { 
            src: 'galeria/img449.jpg', 
            title: 'Área de Lazer', 
            description: 'Espaços de lazer completos para toda a família.'
        },
        { 
            src: 'galeria/img457.jpg', 
            title: 'Piscina', 
            description: 'Piscina para relaxamento e diversão.'
        }
    ];
    
    leisureAreas.forEach((area, index) => {
        const card = document.createElement('div');
        card.className = 'leisure-card';
        
        const imageContainer = document.createElement('div');
        imageContainer.className = 'leisure-card-image';
        
        const img = document.createElement('img');
        img.src = area.src;
        img.alt = area.title;
        img.loading = 'lazy';
        
        imageContainer.appendChild(img);
        
        const content = document.createElement('div');
        content.className = 'leisure-card-content';
        
        const number = document.createElement('div');
        number.className = 'leisure-card-number';
        number.textContent = String(index + 1).padStart(2, '0');
        
        const title = document.createElement('h3');
        title.className = 'leisure-card-title';
        title.textContent = area.title;
        
        const divider = document.createElement('div');
        divider.className = 'leisure-card-divider';
        
        const description = document.createElement('p');
        description.className = 'leisure-card-description';
        description.textContent = area.description;
        
        content.appendChild(number);
        content.appendChild(title);
        content.appendChild(divider);
        content.appendChild(description);
        
        card.appendChild(imageContainer);
        card.appendChild(content);
        
        imageContainer.addEventListener('click', function() {
            openModal(area.src, area.title);
        });
        
        galleryGrid.appendChild(card);
    });
}

// Modal Functionality
function initModal() {
    const modal = document.getElementById('galleryModal');
    const modalImage = document.getElementById('modalImage');
    const closeBtn = document.querySelector('.modal-close-modern');
    
    if (!modal || !modalImage) return;
    
    window.openModal = function(src, title) {
        modalImage.src = src;
        modalImage.alt = title || '';
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
    };
    
    function closeModal() {
        modal.style.display = 'none';
        document.body.style.overflow = '';
    }
    
    if (closeBtn) {
        closeBtn.addEventListener('click', closeModal);
    }
    
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeModal();
        }
    });
    
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && modal.style.display === 'block') {
            closeModal();
        }
    });
}

// Plants Functionality
function initPlants() {
    const plantsGrid = document.getElementById('plantsGrid');
    
    if (!plantsGrid) return;
    
    // Usar apenas plantas arquitetônicas necessárias
    const plants = [
        {
            src: 'plantas/img765.jpg',
            title: 'Planta Térreo',
            description: 'Planta arquitetônica do térreo com layout funcional e espaçoso.'
        },
        {
            src: 'plantas/img773.jpg',
            title: 'Planta Superior',
            description: 'Planta arquitetônica dos andares superiores com otimização de espaço.'
        }
    ];
    
    plants.forEach((plant, index) => {
        const card = document.createElement('div');
        card.className = 'plant-card-modern';
        
        const imageContainer = document.createElement('div');
        imageContainer.className = 'plant-card-image';
        
        const img = document.createElement('img');
        img.src = plant.src;
        img.alt = plant.title;
        img.loading = 'lazy';
        
        imageContainer.appendChild(img);
        
        const content = document.createElement('div');
        content.className = 'plant-card-content';
        
        const number = document.createElement('div');
        number.className = 'plant-card-number';
        number.textContent = String(index + 1).padStart(2, '0');
        
        const title = document.createElement('h3');
        title.className = 'plant-card-title';
        title.textContent = plant.title;
        
        const divider = document.createElement('div');
        divider.className = 'plant-card-divider';
        
        const description = document.createElement('p');
        description.className = 'plant-card-description';
        description.textContent = plant.description;
        
        const viewButton = document.createElement('button');
        viewButton.className = 'plant-view-button';
        viewButton.innerHTML = '<span>Ver Planta</span> <i class="fas fa-arrow-right"></i>';
        
        content.appendChild(number);
        content.appendChild(title);
        content.appendChild(divider);
        content.appendChild(description);
        content.appendChild(viewButton);
        
        card.appendChild(imageContainer);
        card.appendChild(content);
        
        const openPlantModal = function() {
            const plantsModal = document.getElementById('plantsModal');
            const plantsModalImage = document.getElementById('plantsModalImage');
            if (plantsModal && plantsModalImage) {
                plantsModalImage.src = plant.src;
                plantsModalImage.alt = plant.title;
                plantsModal.style.display = 'block';
                document.body.style.overflow = 'hidden';
            }
        };
        
        imageContainer.addEventListener('click', openPlantModal);
        viewButton.addEventListener('click', openPlantModal);
        
        plantsGrid.appendChild(card);
    });
    
    // Plants Modal
    const plantsModal = document.getElementById('plantsModal');
    const plantsCloseBtn = document.querySelector('.plants-modal-close');
    
    if (plantsModal && plantsCloseBtn) {
        function closePlantsModal() {
            plantsModal.style.display = 'none';
            document.body.style.overflow = '';
        }
        
        plantsCloseBtn.addEventListener('click', closePlantsModal);
        
        plantsModal.addEventListener('click', function(e) {
            if (e.target === plantsModal) {
                closePlantsModal();
            }
        });
        
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && plantsModal.style.display === 'block') {
                closePlantsModal();
            }
        });
    }
}

// Floating Projects Menu Functionality
function initProjectsMenu() {
    const projectsMenu = document.getElementById('floatingProjectsMenu');
    const menuToggle = document.getElementById('projectsMenuToggle');
    const menuDropdown = document.getElementById('projectsMenuDropdown');
    
    if (!projectsMenu || !menuToggle || !menuDropdown) return;
    
    // Toggle menu on button click
    menuToggle.addEventListener('click', function(e) {
        e.stopPropagation();
        projectsMenu.classList.toggle('active');
    });
    
    // Close menu when clicking outside
    document.addEventListener('click', function(e) {
        if (!projectsMenu.contains(e.target)) {
            projectsMenu.classList.remove('active');
        }
    });
    
    // Close menu when clicking on a menu item
    const menuItems = menuDropdown.querySelectorAll('.projects-menu-item');
    menuItems.forEach(item => {
        item.addEventListener('click', function() {
            // Allow navigation but close menu after a short delay
            setTimeout(() => {
                projectsMenu.classList.remove('active');
            }, 100);
        });
    });
    
    // Prevent menu from closing when clicking inside dropdown
    menuDropdown.addEventListener('click', function(e) {
        e.stopPropagation();
    });
}
