/**
 * Travel Mountain Theme - Main JavaScript
 * Handles animations, interactions, and dynamic features
 */

document.addEventListener('DOMContentLoaded', function() {
    
    // Initialize all modules
    initHeader();
    initMobileMenu();
    initDestinationsSlider();
    initDemoSidebar();
    initScrollAnimations();
    initParallax();
    initCounters();
    
});

/**
 * Header Scroll Effect
 */
function initHeader() {
    const header = document.querySelector('.header');
    let lastScroll = 0;
    
    window.addEventListener('scroll', function() {
        const currentScroll = window.pageYOffset;
        
        if (currentScroll > 100) {
            header.classList.add('scrolled');
            header.style.cssText = `
                position: fixed;
                top: 0;
                background: rgba(30, 61, 42, 0.95);
                backdrop-filter: blur(10px);
                padding: 15px 0;
                box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            `;
        } else {
            header.classList.remove('scrolled');
            header.style.cssText = `
                position: absolute;
                top: 40px;
                background: transparent;
                backdrop-filter: none;
                padding: 20px 0;
                box-shadow: none;
            `;
        }
        
        lastScroll = currentScroll;
    });
}

/**
 * Mobile Menu Toggle
 */
function initMobileMenu() {
    const menuBtn = document.querySelector('.mobile-menu-btn');
    const nav = document.querySelector('.main-nav');
    
    if (!menuBtn || !nav) return;
    
    menuBtn.addEventListener('click', function() {
        this.classList.toggle('active');
        nav.classList.toggle('active');
        
        // Toggle menu button animation
        const spans = this.querySelectorAll('span');
        if (this.classList.contains('active')) {
            spans[0].style.transform = 'rotate(45deg) translate(5px, 5px)';
            spans[1].style.opacity = '0';
            spans[2].style.transform = 'rotate(-45deg) translate(5px, -5px)';
            
            // Show mobile nav
            nav.style.cssText = `
                display: flex;
                position: absolute;
                top: 100%;
                left: 0;
                right: 0;
                background: rgba(30, 61, 42, 0.98);
                padding: 20px;
                flex-direction: column;
            `;
            
            const navList = nav.querySelector('.nav-list');
            if (navList) {
                navList.style.cssText = `
                    flex-direction: column;
                    gap: 0;
                `;
                
                navList.querySelectorAll('.nav-item > a').forEach(link => {
                    link.style.padding = '15px 20px';
                    link.style.display = 'block';
                    link.style.borderBottom = '1px solid rgba(255,255,255,0.1)';
                });
            }
        } else {
            spans[0].style.transform = 'none';
            spans[1].style.opacity = '1';
            spans[2].style.transform = 'none';
            nav.style.display = '';
        }
    });
    
    // Close menu on window resize
    window.addEventListener('resize', function() {
        if (window.innerWidth > 768) {
            menuBtn.classList.remove('active');
            nav.classList.remove('active');
            nav.style.display = '';
            
            const spans = menuBtn.querySelectorAll('span');
            spans[0].style.transform = 'none';
            spans[1].style.opacity = '1';
            spans[2].style.transform = 'none';
        }
    });
}

/**
 * Destinations Slider
 */
function initDestinationsSlider() {
    const track = document.querySelector('.destinations-track');
    const prevBtn = document.querySelector('.slider-btn.prev');
    const nextBtn = document.querySelector('.slider-btn.next');
    
    if (!track || !prevBtn || !nextBtn) return;
    
    const cards = track.querySelectorAll('.destination-card');
    let currentIndex = 0;
    let cardsPerView = getCardsPerView();
    
    function getCardsPerView() {
        if (window.innerWidth <= 768) return 1;
        if (window.innerWidth <= 992) return 2;
        if (window.innerWidth <= 1200) return 3;
        return 4;
    }
    
    function updateSlider() {
        const cardWidth = cards[0].offsetWidth + 30; // Include gap
        const maxIndex = Math.max(0, cards.length - cardsPerView);
        currentIndex = Math.min(currentIndex, maxIndex);
        track.style.transform = `translateX(-${currentIndex * cardWidth}px)`;
        
        // Update button states
        prevBtn.style.opacity = currentIndex === 0 ? '0.5' : '1';
        nextBtn.style.opacity = currentIndex >= maxIndex ? '0.5' : '1';
    }
    
    prevBtn.addEventListener('click', function() {
        if (currentIndex > 0) {
            currentIndex--;
            updateSlider();
        }
    });
    
    nextBtn.addEventListener('click', function() {
        const maxIndex = cards.length - cardsPerView;
        if (currentIndex < maxIndex) {
            currentIndex++;
            updateSlider();
        }
    });
    
    // Handle resize
    window.addEventListener('resize', function() {
        cardsPerView = getCardsPerView();
        updateSlider();
    });
    
    // Touch/Swipe support
    let touchStartX = 0;
    let touchEndX = 0;
    
    track.addEventListener('touchstart', function(e) {
        touchStartX = e.changedTouches[0].screenX;
    }, { passive: true });
    
    track.addEventListener('touchend', function(e) {
        touchEndX = e.changedTouches[0].screenX;
        handleSwipe();
    }, { passive: true });
    
    function handleSwipe() {
        const diff = touchStartX - touchEndX;
        if (Math.abs(diff) > 50) {
            if (diff > 0) {
                nextBtn.click();
            } else {
                prevBtn.click();
            }
        }
    }
    
    // Initialize
    updateSlider();
}

/**
 * Demo Sidebar Toggle
 */
function initDemoSidebar() {
    const sidebar = document.querySelector('.demo-sidebar');
    const toggle = document.querySelector('.demo-toggle');
    
    if (!sidebar || !toggle) return;
    
    toggle.addEventListener('click', function() {
        sidebar.classList.toggle('active');
        
        // Rotate icon
        const icon = this.querySelector('i');
        if (sidebar.classList.contains('active')) {
            icon.style.transform = 'rotate(180deg)';
        } else {
            icon.style.transform = 'rotate(0deg)';
        }
    });
    
    // Close on outside click
    document.addEventListener('click', function(e) {
        if (!sidebar.contains(e.target) && sidebar.classList.contains('active')) {
            sidebar.classList.remove('active');
            toggle.querySelector('i').style.transform = 'rotate(0deg)';
        }
    });
}

/**
 * Scroll Animations
 */
function initScrollAnimations() {
    const animatedElements = document.querySelectorAll(`
        .package-card,
        .destination-card,
        .testimonial-card,
        .pricing-card,
        .blog-card,
        .blog-card-small,
        .service-card,
        .adventure-content,
        .adventure-image,
        .discover-content,
        .discover-images,
        .section-header,
        .search-content
    `);
    
    // Add initial styles
    animatedElements.forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(30px)';
        el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    });
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                // Staggered animation delay
                setTimeout(() => {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }, index * 100);
                
                observer.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });
    
    animatedElements.forEach(el => observer.observe(el));
}

/**
 * Parallax Effects
 */
function initParallax() {
    const parallaxElements = document.querySelectorAll('.hero-bg, .cta-section');
    
    window.addEventListener('scroll', function() {
        const scrolled = window.pageYOffset;
        
        parallaxElements.forEach(el => {
            const rate = 0.3;
            el.style.backgroundPositionY = `${scrolled * rate}px`;
        });
        
        // Mountain layers parallax
        const mountains = document.querySelectorAll('.mountain-layer');
        mountains.forEach((mountain, index) => {
            const speed = 0.1 * (index + 1);
            mountain.style.transform = `translateY(${scrolled * speed}px)`;
        });
    });
}

/**
 * Animated Counters
 */
function initCounters() {
    const counters = document.querySelectorAll('.pricing-amount .price');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const counter = entry.target;
                const target = parseInt(counter.textContent);
                animateCounter(counter, target);
                observer.unobserve(counter);
            }
        });
    }, { threshold: 0.5 });
    
    counters.forEach(counter => observer.observe(counter));
}

function animateCounter(element, target) {
    let current = 0;
    const duration = 1500;
    const step = target / (duration / 16);
    
    function update() {
        current += step;
        if (current < target) {
            element.textContent = Math.floor(current);
            requestAnimationFrame(update);
        } else {
            element.textContent = target;
        }
    }
    
    update();
}

/**
 * Smooth Scroll for Anchor Links
 */
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
        const href = this.getAttribute('href');
        if (href === '#') return;
        
        e.preventDefault();
        const target = document.querySelector(href);
        
        if (target) {
            target.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    });
});

/**
 * Form Handling
 */
document.querySelectorAll('form').forEach(form => {
    form.addEventListener('submit', function(e) {
        // Only prevent default for forms without action attribute
        if (!this.getAttribute('action') || this.getAttribute('action') === '#') {
            e.preventDefault();
            
            // Get form data
            const formData = new FormData(this);
            const data = Object.fromEntries(formData);
            
            // Simulate form submission
            const button = this.querySelector('button[type="submit"]');
            const originalText = button.innerHTML;
            
            button.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            button.disabled = true;
            
            setTimeout(() => {
                button.innerHTML = '<i class="fas fa-check"></i> Sent!';
                button.style.background = '#4a8c62';
                
                setTimeout(() => {
                    button.innerHTML = originalText;
                    button.disabled = false;
                    button.style.background = '';
                    this.reset();
                }, 2000);
            }, 1500);
        }
    });
});

/**
 * Lazy Loading Images
 */
function initLazyLoading() {
    const images = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.removeAttribute('data-src');
                imageObserver.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
}

/**
 * Preloader (Optional)
 */
window.addEventListener('load', function() {
    document.body.classList.add('loaded');
    
    // Trigger hero animations
    const heroContent = document.querySelector('.hero-content');
    if (heroContent) {
        heroContent.style.animation = 'fadeInUp 1s ease forwards';
    }
});

/**
 * Add CSS for animations via JavaScript
 */
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    .hero-content {
        opacity: 0;
    }
    
    body.loaded .hero-content {
        animation: fadeInUp 1s ease 0.3s forwards;
    }
    
    body.loaded .hero-subtitle {
        animation: fadeInUp 0.8s ease 0.5s forwards;
        opacity: 0;
    }
    
    body.loaded .hero-tagline {
        animation: fadeInUp 0.8s ease 0.7s forwards;
        opacity: 0;
    }
    
    body.loaded .hero-title {
        animation: fadeInUp 0.8s ease 0.9s forwards;
        opacity: 0;
    }
    
    body.loaded .hero-description {
        animation: fadeInUp 0.8s ease 1.1s forwards;
        opacity: 0;
    }
    
    body.loaded .hero-content .btn {
        animation: fadeInUp 0.8s ease 1.3s forwards;
        opacity: 0;
    }
    
    /* Hover effects for cards */
    .package-card:hover .package-image img,
    .blog-card:hover .blog-image img {
        transform: scale(1.1);
    }
    
    /* Button pulse effect */
    .btn-primary:hover {
        animation: pulse 0.5s ease;
    }
    
    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.05); }
        100% { transform: scale(1); }
    }
`;
document.head.appendChild(style);

console.log('🏔️ Travel Mountain Theme Loaded Successfully!');