// EDEN PARK - by Dror
// Adaptado mantendo todas as funcionalidades originais

document.addEventListener('DOMContentLoaded', function() {
    initMobileMenu();
    initSmoothScrolling();
    initGallery();
    initPlants();
    initContactForm();
    initFloatingCTA();
    initAnimations();
    initVideoBackground();
});

// 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 = '';
    }

    if (menuTrigger) {
        menuTrigger.addEventListener('click', toggleMobileMenu);
    }
    if (mobileMenuClose) {
        mobileMenuClose.addEventListener('click', closeMobileMenu);
    }
    if (mobileMenuOverlay) {
        mobileMenuOverlay.addEventListener('click', closeMobileMenu);
    }

    mobileMenuLinks.forEach(link => {
        link.addEventListener('click', closeMobileMenu);
    });
}

// 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;
                
                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');

    if (!galleryMasonry) return;

    // Definir apenas as imagens disponíveis (pasta galeria/ e raiz)
    const imageCategories = {
        galeria: [
            'img333.jpg', 'img344.jpg', 'img356.jpg', 'img482.jpg', 'img489.jpg',
            'img497.jpg', 'img502.jpg', 'img507.jpg', 'img512.jpg', 'img517.jpg', 'img522.jpg'
        ]
    };

    // Função para gerar títulos e descrições baseados no nome da imagem
    function getImageInfo(filename, category) {
        const titles = {
            'img333.jpg': 'Vista Panorâmica',
            'img344.jpg': 'Entrada Principal',
            'img356.jpg': 'Jardim Central',
            'img482.jpg': 'Hall de Entrada',
            'img489.jpg': 'Corredores',
            'img497.jpg': 'Vista Externa',
            'img502.jpg': 'Área Verde',
            'img507.jpg': 'Fachada',
            'img512.jpg': 'Ambiente Interno',
            'img517.jpg': 'Espaço Gourmet',
            'img522.jpg': 'Terraço'
        };

        return {
            title: titles[filename] || filename.replace('.jpg', ''),
            description: 'Imagens exclusivas do empreendimento EDEN PARK'
        };
    }

    // Função para criar um item da galeria
    function createGalleryItem(filename, category) {
        const info = getImageInfo(filename, category);
        const isLarge = Math.random() > 0.7;
        
        const item = document.createElement('div');
        item.className = `gallery-item ${isLarge ? 'large' : 'medium'}`;
        item.setAttribute('data-category', category);
        
        // Verificar se a imagem está na pasta galeria/ ou na raiz
        const imagePath = ['img482.jpg', 'img489.jpg', 'img497.jpg', 'img502.jpg', 'img507.jpg', 'img512.jpg', 'img517.jpg', 'img522.jpg'].includes(filename) 
            ? `galeria/${filename}` 
            : filename;
        
        item.innerHTML = `
            <img src="${imagePath}" alt="${info.title}" loading="lazy">
            <div class="gallery-overlay">
                <div class="overlay-content">
                    <h3>${info.title}</h3>
                    <p>${info.description}</p>
                    <button class="view-btn">
                        <i class="fas fa-expand"></i>
                        <span>Ver Detalhes</span>
                    </button>
                </div>
            </div>
        `;

        return item;
    }

    // Função para carregar todas as imagens
    function loadGalleryImages() {
        galleryMasonry.innerHTML = '';
        
        Object.keys(imageCategories).forEach(category => {
            imageCategories[category].forEach(filename => {
                const galleryItem = createGalleryItem(filename, category);
                galleryMasonry.appendChild(galleryItem);
            });
        });

        addGalleryEventListeners();
    }

    // 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 overlay = this.querySelector('.gallery-overlay');
                const title = overlay.querySelector('h3').textContent;
                const description = overlay.querySelector('p').textContent;

                if (modalImage) modalImage.src = img.src;
                if (modalImage) modalImage.alt = img.alt;
                if (modalTitle) modalTitle.textContent = title;
                if (modalDescription) modalDescription.textContent = description;
                if (modal) {
                    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');
            
            filterBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            filterGallery(filter);
        });
    });

    // Event listeners para modal
    function closeModal() {
        if (modal) {
            modal.style.display = 'none';
            document.body.style.overflow = '';
        }
    }

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

    loadGalleryImages();
}

// 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');

    if (!plantsGrid) return;

    // Definir as plantas disponíveis
    const plantsCategories = {
        todas: [
            'img608.jpg', 'img624.jpg', 'img640.jpg', 'img654.jpg'
        ]
    };

    // Função para obter informações das plantas
    function getPlantInfo(filename, category) {
        const titles = {
            'img608.jpg': 'Planta de Estrutura',
            'img624.jpg': 'Detalhes Estruturais',
            'img640.jpg': 'Planta de Lajes',
            'img654.jpg': 'Planta de Pilares'
        };

        return {
            title: titles[filename] || filename.replace('.jpg', ''),
            description: 'Planta arquitetônica do empreendimento EDEN PARK'
        };
    }

    // 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>
            <div class="plant-details">
                <h3>${info.title}</h3>
                <p>${info.description}</p>
                <div class="plant-actions">
                    <button class="action-btn zoom" title="Ampliar">
                        <i class="fas fa-search-plus"></i>
                    </button>
                    <button class="action-btn download" title="Baixar">
                        <i class="fas fa-download"></i>
                    </button>
                    <button class="action-btn share" title="Compartilhar">
                        <i class="fas fa-share"></i>
                    </button>
                </div>
            </div>
        `;

        return item;
    }

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

        addPlantsEventListeners();
    }

    // Função para adicionar event listeners
    function addPlantsEventListeners() {
        const plantItems = document.querySelectorAll('.plant-item');
        
        plantItems.forEach(item => {
            const downloadBtn = item.querySelector('.download');
            const shareBtn = item.querySelector('.share');
            const zoomBtn = item.querySelector('.zoom');
            const img = item.querySelector('img');
            const title = item.querySelector('h3').textContent;
            const description = item.querySelector('p').textContent;
            
            // Click na imagem ou no card abre o modal
            item.addEventListener('click', function(e) {
                if (!e.target.closest('.action-btn')) {
                    if (plantsModalImage) plantsModalImage.src = img.src;
                    if (plantsModalImage) plantsModalImage.alt = img.alt;
                    if (plantsModalTitle) plantsModalTitle.textContent = title;
                    if (plantsModalDescription) plantsModalDescription.textContent = description;
                    if (plantsModal) {
                        plantsModal.style.display = 'block';
                        document.body.style.overflow = 'hidden';
                    }
                }
            });

            if (zoomBtn) {
                zoomBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    if (plantsModalImage) plantsModalImage.src = img.src;
                    if (plantsModalImage) plantsModalImage.alt = img.alt;
                    if (plantsModalTitle) plantsModalTitle.textContent = title;
                    if (plantsModalDescription) plantsModalDescription.textContent = description;
                    if (plantsModal) {
                        plantsModal.style.display = 'block';
                        document.body.style.overflow = 'hidden';
                    }
                });
            }

            if (downloadBtn) {
                downloadBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    const link = document.createElement('a');
                    link.href = img.src;
                    link.download = img.alt + '.jpg';
                    link.click();
                });
            }

            if (shareBtn) {
                shareBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    if (navigator.share) {
                        navigator.share({
                            title: title,
                            text: description,
                            url: window.location.href
                        });
                    } else {
                        navigator.clipboard.writeText(window.location.href);
                        alert('Link copiado para a área de transferência!');
                    }
                });
            }
        });
    }


    // Event listeners para modal
    function closePlantsModal() {
        if (plantsModal) {
            plantsModal.style.display = 'none';
            document.body.style.overflow = '';
        }
    }

    if (plantsCloseBtn) {
        plantsCloseBtn.addEventListener('click', closePlantsModal);
    }
    
    if (plantsModal) {
        plantsModal.addEventListener('click', function(e) {
            if (e.target === plantsModal) {
                closePlantsModal();
            }
        });
    }

    loadPlants();
}

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

    if (!contactForm) return;

    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;
        
        setTimeout(() => {
            submitBtn.innerHTML = '<i class="fas fa-check"></i> Enviado!';
            submitBtn.style.background = '#4CAF50';
            
            this.reset();
            
            setTimeout(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
                submitBtn.style.background = '';
            }, 3000);
            
            if (typeof gtag !== 'undefined') {
                gtag('event', 'form_submit', {
                    'form_name': 'contact_form',
                    'event_category': 'engagement'
                });
            }
        }, 2000);
    });
}

// Floating CTA Functionality
function initFloatingCTA() {
    const floatingCTA = document.getElementById('floatingCta');
    
    if (floatingCTA) {
        floatingCTA.addEventListener('click', function() {
            scrollToSection('contato');
        });
        
        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.8';
                }
            }, 2000);
        });
    }
}

// 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');
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, observerOptions);

    const animateElements = document.querySelectorAll('.feature, .amenity-item, .plant-item');
    animateElements.forEach((el, index) => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(50px)';
        el.style.transition = `opacity 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) ${index * 0.1}s, transform 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) ${index * 0.1}s`;
        observer.observe(el);
    });
}

// Video Background Functionality
function initVideoBackground() {
    const heroVideo = document.getElementById('hero-video');
    let fadeOutTriggered = false;
    let pageLoadTime = null;

    if (!heroVideo) return;

    pageLoadTime = Date.now();
    monitorVideoTime();

    function monitorVideoTime() {
        setInterval(() => {
            if (!pageLoadTime) return;
            
            const currentTime = Date.now();
            const elapsedTime = (currentTime - pageLoadTime) / 1000;
            
            if (elapsedTime >= 25 && !fadeOutTriggered) {
                fadeOutHeroContent();
                fadeOutTriggered = true;
            }
            
            if (elapsedTime >= 85 && fadeOutTriggered) {
                fadeInHeroContent();
                fadeOutTriggered = false;
                pageLoadTime = Date.now();
            }
        }, 1000);
    }

    function fadeOutHeroContent() {
        const heroContent = document.querySelector('.hero-content');
        if (heroContent) {
            heroContent.classList.add('fade-out');
        }
    }

    function fadeInHeroContent() {
        const heroContent = document.querySelector('.hero-content');
        if (heroContent) {
            heroContent.classList.remove('fade-out');
        }
    }

    const style = document.createElement('style');
    style.textContent = `
        .hero-content {
            transition: all 1s ease-in-out;
        }
        
        .hero-content.fade-out {
            opacity: 0;
            transform: translateY(-30px);
        }
    `;
    document.head.appendChild(style);
}

// Navbar Scroll Effect
window.addEventListener('scroll', function() {
    const navbar = document.querySelector('.navbar');
    const scrollY = window.scrollY;
    
    if (scrollY > 100) {
        navbar.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
    } else {
        navbar.style.boxShadow = 'none';
    }
});

// Console welcome message
console.log(`
🏢 EDEN PARK 🏢
by Dror

Desenvolvido com atenção aos detalhes.
`);
