// ========== DOCUMENT READY ========== //
document.addEventListener('DOMContentLoaded', function() {
    // Initialize all functionality
    initNavigation();
    initSmoothScrolling();
    initApiNavigation();
    initServiceCards();
    initValueCards();
    initAnimations();
    initContactForm();
    initMobileMenu();
});

// ========== NAVIGATION ========== //
function initNavigation() {
    const navLinks = document.querySelectorAll('.nav__link');
    const sections = document.querySelectorAll('.section');
    
    // Update active nav link on scroll
    window.addEventListener('scroll', () => {
        let currentSection = '';
        
        sections.forEach(section => {
            const rect = section.getBoundingClientRect();
            if (rect.top <= 100 && rect.bottom >= 100) {
                currentSection = section.id;
            }
        });
        
        navLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === `#${currentSection}`) {
                link.classList.add('active');
            }
        });
    });
    
    // Header background on scroll
    const header = document.querySelector('.header');
    window.addEventListener('scroll', () => {
        if (window.scrollY > 50) {
            header.style.backgroundColor = 'rgba(255, 255, 255, 0.98)';
            header.style.boxShadow = '0 2px 20px rgba(0, 0, 0, 0.1)';
        } else {
            header.style.backgroundColor = 'rgba(255, 255, 255, 0.95)';
            header.style.boxShadow = 'none';
        }
    });
}

// ========== 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; // Account for header height
                
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
                
                // Close mobile menu if open
                const navMenu = document.getElementById('nav-menu');
                navMenu.classList.remove('show-menu');
            }
        });
    });
}

// ========== MOBILE MENU ========== //
function initMobileMenu() {
    const navToggle = document.getElementById('nav-toggle');
    const navClose = document.getElementById('nav-close');
    const navMenu = document.getElementById('nav-menu');
    
    // Show menu
    if (navToggle) {
        navToggle.addEventListener('click', () => {
            navMenu.classList.add('show-menu');
        });
    }
    
    // Hide menu
    if (navClose) {
        navClose.addEventListener('click', () => {
            navMenu.classList.remove('show-menu');
        });
    }
    
    // Hide menu when clicking nav links
    const navLinks = document.querySelectorAll('.nav__link');
    navLinks.forEach(link => {
        link.addEventListener('click', () => {
            navMenu.classList.remove('show-menu');
        });
    });
}

// ========== API NAVIGATION ========== //
function initApiNavigation() {
    const apiNavLinks = document.querySelectorAll('.api__nav-link');
    const apiSections = document.querySelectorAll('.api__section');
    
    apiNavLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Remove active class from all nav links and sections
            apiNavLinks.forEach(navLink => navLink.classList.remove('active'));
            apiSections.forEach(section => section.classList.remove('active'));
            
            // Add active class to clicked link
            this.classList.add('active');
            
            // Show corresponding section
            const targetId = this.getAttribute('href').substring(1);
            const targetSection = document.getElementById(targetId);
            if (targetSection) {
                targetSection.classList.add('active');
            }
        });
    });
    
    // Make endpoint headers clickable to expand/collapse content
    const endpointHeaders = document.querySelectorAll('.endpoint__header');
    endpointHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const content = this.nextElementSibling;
            if (content && content.classList.contains('endpoint__content')) {
                const isVisible = content.style.display !== 'none';
                content.style.display = isVisible ? 'none' : 'block';
                
                // Add animation
                if (!isVisible) {
                    content.style.animation = 'fadeInUp 0.3s ease-out';
                }
            }
        });
    });
}

// ========== SERVICE CARDS ========== //
function initServiceCards() {
    const servicesGrid = document.querySelector('.services__grid');
    
    if (!servicesGrid) return;
    
    const services = [
        {
            icon: 'ri-leaf-line',
            title: 'Relaxation (Swedish)',
            description: 'A gentle, full-body massage that promotes overall relaxation, improves circulation, and relieves muscle tension.',
            duration: '60 min',
            price: 'Frw 15,000'
        },
        {
            icon: 'ri-contrast-2-line',
            title: 'Deep Tissue Massage',
            description: 'Targets deeper layers of muscles and connective tissues, perfect for relieving chronic aches and pains.',
            duration: '90 min',
            price: 'Frw 20,000'
        },
        {
            icon: 'ri-temp-hot-line',
            title: 'Hot Stone Massage',
            description: 'Uses smooth, heated stones placed on key points of the body to deeply relax tight muscles.',
            duration: '60-90 min',
            price: 'Frw 35,000-40,000'
        },
        {
            icon: 'ri-focus-2-line',
            title: 'Shiatsu Massage',
            description: 'A Japanese therapy that uses finger pressure on energy lines to restore balance and boost vitality.',
            duration: '90 min',
            price: 'Frw 20,000'
        },
        {
            icon: 'ri-run-line',
            title: 'Sports Massage',
            description: 'Designed to enhance athletic performance and recovery. Reduces soreness and prevents injury.',
            duration: '90 min',
            price: 'Frw 20,000'
        },
        {
            icon: 'ri-drop-line',
            title: 'Candle Massage',
            description: 'A unique massage using warm, aromatic candle wax that nourishes the skin and deeply relaxes.',
            duration: '60 min',
            price: 'Frw 22,000'
        },
        {
            icon: 'ri-star-smile-line',
            title: 'Facial Treatments',
            description: 'Soothing and revitalizing treatments that cleanse, exfoliate, and nourish the skin.',
            duration: '60 min',
            price: 'Frw 22,000'
        },
        {
            icon: 'ri-footprint-line',
            title: 'Full Reflexology',
            description: 'Focuses on pressure points in the feet, believed to correspond to organs and systems of the body.',
            duration: '60 min',
            price: 'Frw 15,000'
        },
        {
            icon: 'ri-massage-line',
            title: 'Back-Neck-Shoulders',
            description: 'A focused massage designed to relieve tension and stress in common areas of strain.',
            duration: '40-60 min',
            price: 'Frw 15,000-20,000'
        },
        {
            icon: 'ri-plant-line',
            title: 'Aromatherapy Massage',
            description: 'Combines the power of essential oils with soothing massage techniques for enhanced well-being.',
            duration: '30-60 min',
            price: 'Frw 10,000-15,000'
        }
    ];
    
    // Generate service cards
    services.forEach(service => {
        const serviceCard = createServiceCard(service);
        servicesGrid.appendChild(serviceCard);
    });
}

function createServiceCard(service) {
    const card = document.createElement('div');
    card.className = 'service-card animate-on-scroll';
    
    card.innerHTML = `
        <div class="service-card__icon">
            <i class="${service.icon}"></i>
        </div>
        <h3 class="service-card__title">${service.title}</h3>
        <p class="service-card__description">${service.description}</p>
        <div class="service-card__price">
            <span class="service-card__duration">${service.duration}</span>
            <span class="service-card__cost">${service.price}</span>
        </div>
    `;
    
    return card;
}

// ========== VALUE CARDS ========== //
function initValueCards() {
    // Add animation classes to value cards in the new values section
    const valueCards = document.querySelectorAll('.value-card');
    valueCards.forEach(card => {
        card.classList.add('animate-on-scroll');
    });
    
    // Initialize stats counter animation for about section
    initAboutStats();
}

// ========== ABOUT STATS ANIMATION ========== //
function initAboutStats() {
    const statNumbers = document.querySelectorAll('.stat-card__number');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const statElement = entry.target;
                const targetText = statElement.textContent;
                const targetNumber = parseInt(targetText.replace(/\D/g, ''));
                const suffix = targetText.replace(/[0-9]/g, '');
                
                if (targetNumber > 0) {
                    animateCounter(statElement, 0, targetNumber, suffix, 2000);
                }
                
                observer.unobserve(statElement);
            }
        });
    }, { threshold: 0.5 });
    
    statNumbers.forEach(stat => observer.observe(stat));
}

function animateCounter(element, start, end, suffix, duration) {
    const increment = (end - start) / (duration / 16);
    let current = start;
    
    const timer = setInterval(() => {
        current += increment;
        if (current >= end) {
            element.textContent = end + suffix;
            clearInterval(timer);
        } else {
            element.textContent = Math.floor(current) + suffix;
        }
    }, 16);
}

// ========== ANIMATIONS ========== //
function initAnimations() {
    // Intersection Observer for scroll animations
    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('animated');
            }
        });
    }, observerOptions);
    
    // Observe all elements with animation class
    const animateElements = document.querySelectorAll('.animate-on-scroll');
    animateElements.forEach(el => observer.observe(el));
    
    // Counter animation for stats
    animateCounters();
    
    // Typing effect for home title
    initTypingEffect();
}

function animateCounters() {
    const counters = document.querySelectorAll('.stat__number');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const counter = entry.target;
                const target = counter.textContent.replace(/[^0-9]/g, '');
                const increment = target / 50;
                let current = 0;
                
                const timer = setInterval(() => {
                    current += increment;
                    if (current >= target) {
                        counter.textContent = counter.textContent.replace(/[0-9]+/, target);
                        clearInterval(timer);
                    } else {
                        counter.textContent = counter.textContent.replace(/[0-9]+/, Math.floor(current));
                    }
                }, 50);
                
                observer.unobserve(counter);
            }
        });
    });
    
    counters.forEach(counter => observer.observe(counter));
}

function initTypingEffect() {
    const titleElement = document.querySelector('.home__title');
    if (!titleElement) return;
    
    const text = titleElement.textContent;
    titleElement.textContent = '';
    
    let index = 0;
    const timer = setInterval(() => {
        if (index < text.length) {
            titleElement.textContent += text.charAt(index);
            index++;
        } else {
            clearInterval(timer);
        }
    }, 100);
}

// ========== CONTACT FORM ========== //
function initContactForm() {
    const contactForm = document.getElementById('contact-form');
    
    if (!contactForm) return;
    
    contactForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Get form data
        const formData = new FormData(this);
        const data = Object.fromEntries(formData);
        
        // Validate required fields
        if (!data.name || !data.email) {
            showNotification('Please fill in all required fields', 'error');
            return;
        }
        
        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(data.email)) {
            showNotification('Please enter a valid email address', 'error');
            return;
        }
        
        // Show loading state
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="ri-loader-2-line"></i> Sending...';
        submitBtn.disabled = true;
        
        // Submit to API
        submitContactForm(data)
            .then(response => {
                if (response.success) {
                    // Show success message
                    showNotification('Message sent successfully! We\'ll get back to you soon.', 'success');
                    
                    // Reset form
                    this.reset();
                    
                    // Track submission for analytics (optional)
                    if (typeof gtag !== 'undefined') {
                        gtag('event', 'contact_form_submit', {
                            'event_category': 'engagement',
                            'event_label': data.service || 'general_inquiry'
                        });
                    }
                } else {
                    // Show error message
                    const errorMsg = response.message || 'Failed to send message. Please try again.';
                    showNotification(errorMsg, 'error');
                    
                    // Log validation errors if present
                    if (response.data && response.data.errors) {
                        console.log('Validation errors:', response.data.errors);
                        handleValidationErrors(response.data.errors);
                    }
                }
            })
            .catch(error => {
                console.error('Contact form error:', error);
                showNotification('Network error. Please check your connection and try again.', 'error');
            })
            .finally(() => {
                // Reset button
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
    });
}

/**
 * Submit contact form data to API
 */
async function submitContactForm(data) {
    // Try multiple endpoint URLs as fallbacks
    const endpoints = [
        '/backend/contact.php',      // Direct PHP file
        '/backend/contact',          // API routing via .htaccess
        '/backend/index.php/contact' // Explicit index.php routing
    ];
    
    const requestData = {
        ...data,
        source: 'website',
        timestamp: new Date().toISOString()
    };
    
    let lastError = null;
    
    // Try each endpoint until one works
    for (const endpoint of endpoints) {
        try {
            console.log(`Trying endpoint: ${endpoint}`);
            
            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(requestData)
            });
            
            // Check if response is JSON
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                throw new Error(`Server returned ${contentType} instead of JSON`);
            }
            
            const result = await response.json();
            
            if (!response.ok) {
                throw new Error(result.message || `HTTP error! status: ${response.status}`);
            }
            
            console.log(`✅ Success with endpoint: ${endpoint}`);
            return result;
            
        } catch (error) {
            console.warn(`❌ Failed with endpoint ${endpoint}:`, error.message);
            lastError = error;
            
            // Continue to next endpoint
            continue;
        }
    }
    
    // If all endpoints failed
    console.error('All contact endpoints failed:', lastError);
    throw lastError || new Error('All contact endpoints are unavailable');
}

/**
 * Handle validation errors by highlighting fields
 */
function handleValidationErrors(errors) {
    // Clear previous error states
    document.querySelectorAll('.form__input').forEach(input => {
        input.classList.remove('error');
        const errorMsg = input.parentNode.querySelector('.error-message');
        if (errorMsg) {
            errorMsg.remove();
        }
    });
    
    // Add error states for invalid fields
    Object.keys(errors).forEach(field => {
        const input = document.querySelector(`[name="${field}"]`);
        if (input) {
            input.classList.add('error');
            
            // Add error message
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = errors[field];
            errorDiv.style.cssText = `
                color: #ef4444;
                font-size: 0.875rem;
                margin-top: 0.25rem;
                display: block;
            `;
            
            input.parentNode.appendChild(errorDiv);
        }
    });
}

/**
 * Add error styles for form validation
 */
function addFormErrorStyles() {
    const style = document.createElement('style');
    style.textContent = `
        .form__input.error {
            border-color: #ef4444 !important;
            box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1) !important;
        }
        
        .form__input.error:focus {
            border-color: #ef4444 !important;
            box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.2) !important;
        }
    `;
    document.head.appendChild(style);
}

// Initialize error styles when DOM loads
document.addEventListener('DOMContentLoaded', addFormErrorStyles);

// ========== NOTIFICATIONS ========== //
function showNotification(message, type = 'info') {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `notification notification--${type}`;
    notification.innerHTML = `
        <div class="notification__content">
            <i class="ri-${type === 'success' ? 'check' : 'information'}-line"></i>
            <span>${message}</span>
        </div>
        <button class="notification__close">
            <i class="ri-close-line"></i>
        </button>
    `;
    
    // Add styles
    notification.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        background: ${type === 'success' ? '#10B981' : '#3B82F6'};
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 0.75rem;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        z-index: 1060;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        max-width: 400px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    `;
    
    // Add to page
    document.body.appendChild(notification);
    
    // Animate in
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // Auto remove after 5 seconds
    setTimeout(() => {
        removeNotification(notification);
    }, 5000);
    
    // Close button functionality
    const closeBtn = notification.querySelector('.notification__close');
    closeBtn.addEventListener('click', () => {
        removeNotification(notification);
    });
}

function removeNotification(notification) {
    notification.style.transform = 'translateX(100%)';
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 300);
}

// ========== UTILITY FUNCTIONS ========== //
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

// ========== PERFORMANCE OPTIMIZATIONS ========== //
// Optimize scroll events
const optimizedScroll = throttle(() => {
    // Scroll-based animations would go here
}, 16); // ~60fps

window.addEventListener('scroll', optimizedScroll);

// ========== ACCESSIBILITY ========== //
// Keyboard navigation for API sections
document.addEventListener('keydown', function(e) {
    if (e.key === 'Enter' || e.key === ' ') {
        const focusedElement = document.activeElement;
        if (focusedElement.classList.contains('api__nav-link')) {
            e.preventDefault();
            focusedElement.click();
        }
    }
});

// Focus management for mobile menu
function manageFocus() {
    const navMenu = document.getElementById('nav-menu');
    const navToggle = document.getElementById('nav-toggle');
    const navClose = document.getElementById('nav-close');
    
    if (navMenu.classList.contains('show-menu')) {
        navClose.focus();
    } else {
        navToggle.focus();
    }
}

// ========== ERROR HANDLING ========== //
window.addEventListener('error', function(e) {
    console.error('JavaScript error:', e.error);
    // Could send error reports to analytics here
});

// ========== LOADING OPTIMIZATION ========== //
// Lazy load 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.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
}

// Initialize lazy loading if needed
document.addEventListener('DOMContentLoaded', initLazyLoading);

// ========== EXPORT FOR TESTING ========== //
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        initNavigation,
        initApiNavigation,
        initServiceCards,
        showNotification
    };
} 