// ACE Health Website JavaScript - Enhanced with Scroll Animations

// Mobile Navigation Toggle
const hamburger = document.getElementById('hamburger');
const navMenu = document.getElementById('nav-menu');
const navLinks = document.querySelectorAll('.nav-link');

hamburger.addEventListener('click', () => {
    navMenu.classList.toggle('active');
    
    // Animate hamburger icon
    const spans = hamburger.querySelectorAll('span');
    if (navMenu.classList.contains('active')) {
        spans[0].style.transform = 'rotate(45deg) translate(5px, 5px)';
        spans[1].style.opacity = '0';
        spans[2].style.transform = 'rotate(-45deg) translate(7px, -6px)';
    } else {
        spans[0].style.transform = 'none';
        spans[1].style.opacity = '1';
        spans[2].style.transform = 'none';
    }
});

// Close mobile menu when clicking on a link
navLinks.forEach(link => {
    link.addEventListener('click', () => {
        navMenu.classList.remove('active');
        const spans = hamburger.querySelectorAll('span');
        spans[0].style.transform = 'none';
        spans[1].style.opacity = '1';
        spans[2].style.transform = 'none';
    });
});

// Navbar scroll effect
const navbar = document.getElementById('navbar');
let lastScroll = 0;

window.addEventListener('scroll', () => {
    const currentScroll = window.pageYOffset;
    
    if (currentScroll > 100) {
        navbar.style.boxShadow = '0 4px 20px rgba(29, 34, 37, 0.12)';
    } else {
        navbar.style.boxShadow = '0 2px 20px rgba(29, 34, 37, 0.08)';
    }
    
    lastScroll = currentScroll;
});

// Product Carousel
const track = document.getElementById('carouselTrack');
const slides = Array.from(track.children);
const nextButton = document.getElementById('nextBtn');
const prevButton = document.getElementById('prevBtn');
const indicatorsContainer = document.getElementById('indicators');

let currentIndex = 0;

// Create indicators
slides.forEach((_, index) => {
    const indicator = document.createElement('div');
    indicator.classList.add('indicator');
    if (index === 0) indicator.classList.add('active');
    indicator.addEventListener('click', () => goToSlide(index));
    indicatorsContainer.appendChild(indicator);
});

const indicators = Array.from(indicatorsContainer.children);

function updateCarousel() {
    const slideWidth = slides[0].getBoundingClientRect().width;
    track.style.transform = `translateX(-${currentIndex * slideWidth}px)`;
    
    // Update indicators
    indicators.forEach((indicator, index) => {
        if (index === currentIndex) {
            indicator.classList.add('active');
        } else {
            indicator.classList.remove('active');
        }
    });
}

function goToSlide(index) {
    currentIndex = index;
    updateCarousel();
}

nextButton.addEventListener('click', () => {
    currentIndex = (currentIndex + 1) % slides.length;
    updateCarousel();
});

prevButton.addEventListener('click', () => {
    currentIndex = (currentIndex - 1 + slides.length) % slides.length;
    updateCarousel();
});

// Auto-advance carousel every 5 seconds
let autoAdvance = setInterval(() => {
    currentIndex = (currentIndex + 1) % slides.length;
    updateCarousel();
}, 5000);

// Pause auto-advance on hover
const carouselContainer = document.querySelector('.carousel-container');
if (carouselContainer) {
    carouselContainer.addEventListener('mouseenter', () => {
        clearInterval(autoAdvance);
    });

    carouselContainer.addEventListener('mouseleave', () => {
        autoAdvance = setInterval(() => {
            currentIndex = (currentIndex + 1) % slides.length;
            updateCarousel();
        }, 5000);
    });
}

// Update carousel on window resize
window.addEventListener('resize', () => {
    updateCarousel();
});

// Smooth scroll for anchor links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if (target) {
            const navbarHeight = navbar.offsetHeight;
            const targetPosition = target.offsetTop - navbarHeight;
            
            window.scrollTo({
                top: targetPosition,
                behavior: 'smooth'
            });
        }
    });
});

// Advanced Scroll Reveal Animations
const revealOptions = {
    threshold: 0.15,
    rootMargin: '0px 0px -100px 0px'
};

const revealObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('revealed');
            // Optionally unobserve after revealing
            // revealObserver.unobserve(entry.target);
        }
    });
}, revealOptions);

// Observe all reveal elements
const revealElements = document.querySelectorAll(
    '.reveal-left, .reveal-right, .reveal-title, .reveal-scale'
);

revealElements.forEach(element => {
    revealObserver.observe(element);
});

// Service cards animation
const serviceObserverOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -80px 0px'
};

const serviceObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry, index) => {
        if (entry.isIntersecting) {
            setTimeout(() => {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }, index * 100);
        }
    });
}, serviceObserverOptions);

// Observe service cards
const serviceCards = document.querySelectorAll('.service-card');
serviceCards.forEach(card => {
    card.style.opacity = '0';
    card.style.transform = 'translateY(30px)';
    card.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    serviceObserver.observe(card);
});

// Value cards animation
const valueCards = document.querySelectorAll('.value-card');
valueCards.forEach((card, index) => {
    card.style.opacity = '0';
    card.style.transform = 'translateX(-30px)';
    card.style.transition = `opacity 0.6s ease ${index * 0.1}s, transform 0.6s ease ${index * 0.1}s`;
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateX(0)';
            }
        });
    }, { threshold: 0.2 });
    
    observer.observe(card);
});

// Workflow steps animation
const workflowSteps = document.querySelectorAll('.workflow-step');
const workflowObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry, index) => {
        if (entry.isIntersecting) {
            setTimeout(() => {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }, index * 150);
        }
    });
}, { threshold: 0.15 });

workflowSteps.forEach(step => {
    step.style.opacity = '0';
    step.style.transform = 'translateY(30px)';
    step.style.transition = 'opacity 0.8s ease, transform 0.8s ease';
    workflowObserver.observe(step);
});

// Active nav link highlighting based on scroll position
const sections = document.querySelectorAll('section[id]');

function highlightNavLink() {
    const scrollY = window.pageYOffset;
    
    sections.forEach(section => {
        const sectionHeight = section.offsetHeight;
        const sectionTop = section.offsetTop - navbar.offsetHeight - 100;
        const sectionId = section.getAttribute('id');
        const navLink = document.querySelector(`.nav-link[href="#${sectionId}"]`);
        
        if (navLink) {
            if (scrollY > sectionTop && scrollY <= sectionTop + sectionHeight) {
                navLink.style.color = 'var(--health-blue)';
                navLink.style.fontWeight = '600';
            } else {
                navLink.style.color = 'var(--black-sand)';
                navLink.style.fontWeight = '500';
            }
        }
    });
}

window.addEventListener('scroll', highlightNavLink);

// Parallax effect for section images
window.addEventListener('scroll', () => {
    const scrolled = window.pageYOffset;
    const sectionImages = document.querySelectorAll('.section-image img');
    
    sectionImages.forEach(img => {
        const imageTop = img.getBoundingClientRect().top;
        const imageVisible = imageTop < window.innerHeight && imageTop > -img.offsetHeight;
        
        if (imageVisible) {
            const parallaxSpeed = 0.2;
            const yPos = 70-(0.1*scrolled - img.offsetTop) * parallaxSpeed;
            img.style.transform = `translateY(${yPos}px) scale(1.35)`;
        }
    });
});

// Counter animation for numbers (if you want to add stats)
function animateCounter(element, target, duration = 2000) {
    let start = 0;
    const increment = target / (duration / 16);
    
    const timer = setInterval(() => {
        start += increment;
        if (start >= target) {
            element.textContent = Math.round(target);
            clearInterval(timer);
        } else {
            element.textContent = Math.round(start);
        }
    }, 16);
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    updateCarousel();
    highlightNavLink();
    
    // Add smooth reveal to initial viewport elements
    setTimeout(() => {
        const initialElements = document.querySelectorAll('.fade-in-up');
        initialElements.forEach((el, index) => {
            setTimeout(() => {
                el.style.opacity = '1';
                el.style.transform = 'translateY(0)';
            }, index * 100);
        });
    }, 100);
});

// Keyboard navigation for carousel
document.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowLeft') {
        currentIndex = (currentIndex - 1 + slides.length) % slides.length;
        updateCarousel();
        clearInterval(autoAdvance);
    } else if (e.key === 'ArrowRight') {
        currentIndex = (currentIndex + 1) % slides.length;
        updateCarousel();
        clearInterval(autoAdvance);
    }
});

// Add touch support for carousel
let touchStartX = 0;
let touchEndX = 0;

if (track) {
    track.addEventListener('touchstart', (e) => {
        touchStartX = e.changedTouches[0].screenX;
    }, false);

    track.addEventListener('touchend', (e) => {
        touchEndX = e.changedTouches[0].screenX;
        handleSwipe();
    }, false);
}

function handleSwipe() {
    if (touchEndX < touchStartX - 50) {
        // Swipe left - next slide
        currentIndex = (currentIndex + 1) % slides.length;
        updateCarousel();
        clearInterval(autoAdvance);
    }
    if (touchEndX > touchStartX + 50) {
        // Swipe right - previous slide
        currentIndex = (currentIndex - 1 + slides.length) % slides.length;
        updateCarousel();
        clearInterval(autoAdvance);
    }
}

// Add custom cursor effect on interactive elements (optional enhancement)
const interactiveElements = document.querySelectorAll('a, button, .service-card, .value-card, .trust-item');

interactiveElements.forEach(element => {
    element.addEventListener('mouseenter', () => {
        document.body.style.cursor = 'pointer';
    });
    
    element.addEventListener('mouseleave', () => {
        document.body.style.cursor = 'default';
    });
});

// Performance optimization: Debounce scroll events
function debounce(func, wait = 10) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Apply debounce to scroll-heavy functions
const debouncedHighlight = debounce(highlightNavLink, 10);
window.addEventListener('scroll', debouncedHighlight);

// Lazy loading for images (browser native)
const images = document.querySelectorAll('img[loading="lazy"]');
images.forEach(img => {
    img.addEventListener('load', () => {
        img.style.opacity = '1';
    });
});

// Add entrance animation for trust items
const trustItems = document.querySelectorAll('.trust-item');
const trustObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry, index) => {
        if (entry.isIntersecting) {
            setTimeout(() => {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'scale(1)';
            }, index * 150);
        }
    });
}, { threshold: 0.1 });

trustItems.forEach(item => {
    item.style.opacity = '0';
    item.style.transform = 'scale(0.95)';
    item.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    trustObserver.observe(item);
});
