/* ==========================================================================
   VENTURE FABRICATIONS - JAVASCRIPT CONTROLLER
   ========================================================================== */

document.addEventListener('DOMContentLoaded', () => {

    // 1. Mobile Menu Toggle
    const menuToggle = document.getElementById('menuToggle');
    const navMenu = document.getElementById('navMenu');
    const navLinks = document.querySelectorAll('.nav-link');

    if (menuToggle && navMenu) {
        menuToggle.addEventListener('click', () => {
            menuToggle.classList.toggle('active');
            navMenu.classList.toggle('open');
        });

        // Close menu when clicking navigation link
        navLinks.forEach(link => {
            link.addEventListener('click', () => {
                menuToggle.classList.remove('active');
                navMenu.classList.remove('open');
            });
        });
    }

    // 2. Scroll Active Navigation Link Highlight & Sticky Header
    const mainHeader = document.querySelector('.main-header');
    const sections = document.querySelectorAll('section');

    const handleScroll = () => {
        // Sticky Header Class
        if (window.scrollY > 50) {
            mainHeader.classList.add('scrolled');
        } else {
            mainHeader.classList.remove('scrolled');
        }

        // Active Nav Link Highlight based on scroll position
        let currentSectionId = '';
        sections.forEach(section => {
            const sectionTop = section.offsetTop - 120; // offset header height
            const sectionHeight = section.offsetHeight;
            if (window.scrollY >= sectionTop && window.scrollY < sectionTop + sectionHeight) {
                currentSectionId = section.getAttribute('id');
            }
        });

        if (currentSectionId) {
            navLinks.forEach(link => {
                link.classList.remove('active');
                if (link.getAttribute('href') === `#${currentSectionId}`) {
                    link.classList.add('active');
                }
            });
        }
    };

    window.addEventListener('scroll', handleScroll);
    handleScroll(); // Trigger initial execution

    // 3. Scroll Triggered Entrance Animations
    const animateElements = document.querySelectorAll('[data-animate]');
    
    const animationObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                // Apply delays if specified via data-delay attribute
                const delay = entry.target.getAttribute('data-delay') || 0;
                setTimeout(() => {
                    entry.target.classList.add('animated');
                }, delay);
                observer.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.05,
        rootMargin: '0px 0px -30px 0px'
    });

    animateElements.forEach(elem => {
        animationObserver.observe(elem);
    });

    // 4. Statistics Counter Animation
    const counterNumbers = document.querySelectorAll('.counter-number');
    let countersAnimated = false;

    const animateCounters = () => {
        counterNumbers.forEach(counter => {
            const target = parseInt(counter.getAttribute('data-target'), 10);
            let count = 0;
            const duration = 2000; // 2 seconds total animation time
            const steps = 60;
            const increment = target / steps;
            const stepDuration = duration / steps;

            const updateCount = () => {
                count += increment;
                if (count < target) {
                    counter.innerText = Math.floor(count);
                    setTimeout(updateCount, stepDuration);
                } else {
                    counter.innerText = target;
                }
            };
            updateCount();
        });
    };

    const statsSection = document.querySelector('.statistics-section');
    if (statsSection) {
        const statsObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting && !countersAnimated) {
                    animateCounters();
                    countersAnimated = true;
                    observer.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.3
        });

        statsObserver.observe(statsSection);
    }

    // 5. Portfolio Gallery Filters
    const filterButtons = document.querySelectorAll('.filter-btn');
    const projectItems = document.querySelectorAll('.project-item');

    filterButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            // Remove active state from all filters and add to this one
            filterButtons.forEach(f => f.classList.remove('active'));
            btn.classList.add('active');

            const filterValue = btn.getAttribute('data-filter');

            projectItems.forEach(item => {
                const category = item.getAttribute('data-category');
                
                // Add scale down transition effect
                item.style.transform = 'scale(0.85)';
                item.style.opacity = '0';
                
                setTimeout(() => {
                    if (filterValue === 'all' || category === filterValue) {
                        item.style.display = 'block';
                        setTimeout(() => {
                            item.style.transform = 'scale(1)';
                            item.style.opacity = '1';
                        }, 50);
                    } else {
                        item.style.display = 'none';
                    }
                }, 300);
            });
        });
    });

    // 6. Contact Form Validation and Simulation
    const contactForm = document.getElementById('contactForm');
    const formStatus = document.getElementById('formStatus');

    if (contactForm) {
        contactForm.addEventListener('submit', (e) => {
            e.preventDefault();

            // Inputs
            const nameInput = document.getElementById('name');
            const emailInput = document.getElementById('email');
            const messageInput = document.getElementById('message');
            const submitBtn = document.getElementById('submitBtn');

            // Errors
            const nameError = document.getElementById('name-error');
            const emailError = document.getElementById('email-error');
            const messageError = document.getElementById('message-error');

            let isValid = true;

            // Reset States
            nameInput.parentElement.classList.remove('invalid');
            emailInput.parentElement.classList.remove('invalid');
            messageInput.parentElement.classList.remove('invalid');
            formStatus.className = 'form-status';
            formStatus.innerText = '';

            // Name validation
            if (!nameInput.value.trim()) {
                nameInput.parentElement.classList.add('invalid');
                isValid = false;
            }

            // Email validation
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailInput.value.trim() || !emailRegex.test(emailInput.value.trim())) {
                emailInput.parentElement.classList.add('invalid');
                isValid = false;
            }

            // Message validation
            if (!messageInput.value.trim()) {
                messageInput.parentElement.classList.add('invalid');
                isValid = false;
            }

            if (isValid) {
                // Change UI state to submitting
                submitBtn.disabled = true;
                submitBtn.innerHTML = 'Sending Details... <i class="fa-solid fa-circle-notch fa-spin"></i>';

                // Simulate API call delay (1.5 seconds)
                setTimeout(() => {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = 'Submit Project Details <i class="fa-solid fa-paper-plane"></i>';
                    
                    formStatus.classList.add('success');
                    formStatus.innerText = 'Thank you! Your quotation request has been received. Our estimating team will contact you within 24 hours.';
                    
                    // Reset fields
                    contactForm.reset();
                    
                    // Hide success message after 8 seconds
                    setTimeout(() => {
                        formStatus.className = 'form-status';
                        formStatus.innerText = '';
                    }, 8000);

                }, 1500);
            } else {
                formStatus.classList.add('error');
                formStatus.innerText = 'Please correct the highlighted errors before submitting.';
            }
        });
    }

    // 7. Newsletter Form Handling
    const newsletterForm = document.getElementById('newsletterForm');
    const newsletterStatus = document.getElementById('newsletterStatus');

    if (newsletterForm && newsletterStatus) {
        newsletterForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const emailInput = newsletterForm.querySelector('input[type="email"]');
            
            newsletterStatus.className = 'newsletter-status success';
            newsletterStatus.innerText = 'Subscribed successfully!';
            
            emailInput.value = '';
            
            setTimeout(() => {
                newsletterStatus.innerText = '';
                newsletterStatus.className = 'newsletter-status';
            }, 4000);
        });
    }

    // 8. Dropdown Accordion Toggle on Mobile
    const dropdowns = document.querySelectorAll('.dropdown');
    
    dropdowns.forEach(dropdown => {
        const toggle = dropdown.querySelector('.dropdown-toggle');
        if (toggle) {
            toggle.addEventListener('click', (e) => {
                if (window.innerWidth <= 768) {
                    e.preventDefault(); // Stop default navigation on mobile
                    
                    // Close other dropdowns
                    dropdowns.forEach(other => {
                        if (other !== dropdown) {
                            other.classList.remove('active');
                        }
                    });
                    
                    dropdown.classList.toggle('active');
                }
            });
        }
    });

    // 9. Lightbox Modal Gallery
    const galleryItems = document.querySelectorAll('.gallery-img-wrapper');
    const lightboxModal = document.getElementById('lightboxModal');
    
    if (galleryItems.length > 0 && lightboxModal) {
        const lightboxImg = lightboxModal.querySelector('.lightbox-content');
        const closeBtn = lightboxModal.querySelector('.lightbox-close');
        const prevBtn = lightboxModal.querySelector('.lightbox-prev');
        const nextBtn = lightboxModal.querySelector('.lightbox-next');
        
        let currentIndex = 0;
        const images = Array.from(galleryItems).map(item => item.querySelector('img').src);
        
        const openLightbox = (index) => {
            currentIndex = index;
            lightboxImg.src = images[currentIndex];
            lightboxModal.classList.add('active');
            document.body.style.overflow = 'hidden';
        };
        
        const closeLightbox = () => {
            lightboxModal.classList.remove('active');
            document.body.style.overflow = '';
        };
        
        const showNext = () => {
            currentIndex = (currentIndex + 1) % images.length;
            lightboxImg.style.opacity = '0';
            setTimeout(() => {
                lightboxImg.src = images[currentIndex];
                lightboxImg.style.opacity = '1';
            }, 150);
        };
        
        const showPrev = () => {
            currentIndex = (currentIndex - 1 + images.length) % images.length;
            lightboxImg.style.opacity = '0';
            setTimeout(() => {
                lightboxImg.src = images[currentIndex];
                lightboxImg.style.opacity = '1';
            }, 150);
        };
        
        galleryItems.forEach((item, index) => {
            item.addEventListener('click', () => openLightbox(index));
        });
        
        if (closeBtn) closeBtn.addEventListener('click', closeLightbox);
        if (nextBtn) nextBtn.addEventListener('click', showNext);
        if (prevBtn) prevBtn.addEventListener('click', showPrev);
        
        lightboxModal.addEventListener('click', (e) => {
            if (e.target === lightboxModal) {
                closeLightbox();
            }
        });
        
        document.addEventListener('keydown', (e) => {
            if (!lightboxModal.classList.contains('active')) return;
            if (e.key === 'Escape') closeLightbox();
            if (e.key === 'ArrowRight') showNext();
            if (e.key === 'ArrowLeft') showPrev();
        });
    }

    // 7. Hero Banner Image Slider
    const heroSlides = document.querySelectorAll('.hero-slide');
    const heroDots = document.querySelectorAll('.slider-dot');
    const heroPrevBtn = document.getElementById('hero-prev');
    const heroNextBtn = document.getElementById('hero-next');
    
    if (heroSlides.length > 0) {
        let currentSlide = 0;
        let slideInterval;
        const intervalTime = 6000; // 6 seconds

        const showSlide = (index) => {
            heroSlides.forEach(slide => slide.classList.remove('active'));
            heroDots.forEach(dot => dot.classList.remove('active'));

            currentSlide = (index + heroSlides.length) % heroSlides.length;
            heroSlides[currentSlide].classList.add('active');
            if (heroDots[currentSlide]) heroDots[currentSlide].classList.add('active');
        };

        const nextSlide = () => {
            showSlide(currentSlide + 1);
        };

        const prevSlide = () => {
            showSlide(currentSlide - 1);
        };

        const startAutoSlide = () => {
            clearInterval(slideInterval);
            slideInterval = setInterval(nextSlide, intervalTime);
        };

        if (heroNextBtn) {
            heroNextBtn.addEventListener('click', () => {
                nextSlide();
                startAutoSlide();
            });
        }

        if (heroPrevBtn) {
            heroPrevBtn.addEventListener('click', () => {
                prevSlide();
                startAutoSlide();
            });
        }

        heroDots.forEach((dot, index) => {
            dot.addEventListener('click', () => {
                showSlide(index);
                startAutoSlide();
            });
        });

        // Initialize auto slide
        startAutoSlide();
    }
});
