/* Cirux Landing Page Scripts */

(function() {
    'use strict';

    // DOM Elements
    const navbar = document.getElementById('navbar');
    const mobileMenuBtn = document.getElementById('mobileMenuBtn');
    const navLinks = document.getElementById('navLinks');
    const heroVideo = document.getElementById('heroVideo');
    const videoOverlay = document.getElementById('videoOverlay');
    const playBtn = document.getElementById('playBtn');
    const ctaForm = document.getElementById('ctaForm');
    const successModal = document.getElementById('successModal');
    const closeModalBtn = document.getElementById('closeModal');

    // Navbar scroll effect
    function handleScroll() {
        if (window.scrollY > 50) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
    }

    window.addEventListener('scroll', handleScroll, { passive: true });
    handleScroll();

    // Mobile menu toggle
    if (mobileMenuBtn && navLinks) {
        mobileMenuBtn.addEventListener('click', function() {
            const isOpen = navLinks.classList.toggle('mobile-open');
            mobileMenuBtn.classList.toggle('active', isOpen);
            document.body.classList.toggle('menu-open', isOpen);
        });
    }

    // Hero video play
    if (heroVideo && playBtn && videoOverlay) {
        playBtn.addEventListener('click', function() {
            heroVideo.play().then(function() {
                videoOverlay.classList.add('hidden');
            }).catch(function(err) {
                console.log('Autoplay prevented:', err);
                videoOverlay.classList.add('hidden');
                heroVideo.setAttribute('controls', 'controls');
            });
        });

        // Pause video when out of viewport
        const videoObserver = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (!entry.isIntersecting && !heroVideo.paused) {
                    heroVideo.pause();
                    videoOverlay.classList.remove('hidden');
                }
            });
        }, { threshold: 0.3 });

        videoObserver.observe(heroVideo);
    }

    // Smooth scroll for anchor links
    document.querySelectorAll('a[href^="#"]').forEach(function(anchor) {
        anchor.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (href === '#') return;
            const target = document.querySelector(href);
            if (target) {
                e.preventDefault();
                const offset = 80;
                const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - offset;
                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });
                // Close mobile menu if open
                if (navLinks) {
                    navLinks.classList.remove('mobile-open');
                    mobileMenuBtn.classList.remove('active');
                    document.body.classList.remove('menu-open');
                }
            }
        });
    });

    // CTA Form submission
    if (ctaForm) {
        ctaForm.addEventListener('submit', function(e) {
            e.preventDefault();

            // Collect form data
            const formData = new FormData(ctaForm);
            const data = {};
            formData.forEach(function(value, key) {
                data[key] = value;

                // Send data to WhatsApp API
                const apiUrl = 'https://api.whatsapp.com/send?phone=573236570699;
                window.open(apiUrl, '_blank');
            });

            // Here you would typically send to your backend
            console.log('Form submitted:', data);

            // Show success modal
            if (successModal) {
                successModal.classList.add('active');
                document.body.style.overflow = 'hidden';
            }

            // Reset form
            ctaForm.reset();
        });
    }

    // Close modal
    if (closeModalBtn && successModal) {
        closeModalBtn.addEventListener('click', function() {
            successModal.classList.remove('active');
            document.body.style.overflow = '';
        });

        successModal.addEventListener('click', function(e) {
            if (e.target === successModal) {
                successModal.classList.remove('active');
                document.body.style.overflow = '';
            }
        });
    }

    // Close modal on Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && successModal && successModal.classList.contains('active')) {
            successModal.classList.remove('active');
            document.body.style.overflow = '';
        }
    });

    // Scroll reveal animation
    const revealElements = document.querySelectorAll(
        '.step-card, .pain-card, .testimonial-card, .benefit-item, .section-header'
    );

    const revealObserver = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
                revealObserver.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });

    revealElements.forEach(function(el) {
        el.style.opacity = '0';
        el.style.transform = 'translateY(20px)';
        el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        revealObserver.observe(el);
    });

    // Number counter animation for stats
    const statNumbers = document.querySelectorAll('.stat-number');
    let statsAnimated = false;

    function animateStats() {
        if (statsAnimated) return;
        const statsSection = document.querySelector('.hero-stats');
        if (!statsSection) return;
        const rect = statsSection.getBoundingClientRect();
        if (rect.top < window.innerHeight && rect.bottom > 0) {
            statsAnimated = true;
            statNumbers.forEach(function(stat) {
                const text = stat.textContent;
                const hasPlus = text.includes('+');
                const hasPercent = text.includes('%');
                const num = parseInt(text.replace(/\D/g, ''), 10);
                const suffix = hasPlus ? '+' : (hasPercent ? '%' : '');
                const prefix = text.startsWith('$') ? '$' : '';

                let current = 0;
                const increment = Math.ceil(num / 40);
                const duration = 1200;
                const stepTime = duration / (num / increment);

                const timer = setInterval(function() {
                    current += increment;
                    if (current >= num) {
                        current = num;
                        clearInterval(timer);
                    }
                    stat.textContent = prefix + current.toLocaleString() + suffix;
                }, stepTime);
            });
        }
    }

    window.addEventListener('scroll', animateStats, { passive: true });
    animateStats();

    // Benefits float card subtle parallax
    const benefitsVisual = document.querySelector('.benefits-visual');
    if (benefitsVisual) {
        window.addEventListener('scroll', function() {
            const rect = benefitsVisual.getBoundingClientRect();
            const centerOffset = (rect.top + rect.height / 2 - window.innerHeight / 2) / window.innerHeight;
            const floatCard = benefitsVisual.querySelector('.benefits-float-card');
            if (floatCard) {
                floatCard.style.transform = 'translateY(' + (centerOffset * -15) + 'px)';
            }
        }, { passive: true });
    }

    // Console welcome message
    console.log('%c Cirux ', 'background: #22c55e; color: #2e4057; font-size: 20px; font-weight: bold; padding: 8px 16px; border-radius: 8px;');
    console.log('%cSoftware de automatización para cirujanos', 'color: #fdf8f5; font-size: 14px;');

})();
