// Light Theme Landing Page JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // Initialize all components
    initNavbar();
    initLoginForm();
    initAnimations();
    initScrollEffects();
    initFloatingElements();
    initCounterAnimations();
    initEarningsFeed();
    initAccordion();
    initScrollToTop();
});

// Navbar functionality
function initNavbar() {
    const navbar = document.querySelector('.light-nav');
    const navLinks = document.querySelectorAll('.nav-link');
    
    // Navbar scroll effect
    window.addEventListener('scroll', function() {
        if (window.scrollY > 50) {
            navbar.style.background = 'rgba(255, 255, 255, 0.98)';
            navbar.style.backdropFilter = 'blur(20px)';
            navbar.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)';
        } else {
            navbar.style.background = 'rgba(255, 255, 255, 0.95)';
            navbar.style.backdropFilter = 'blur(15px)';
            navbar.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)';
        }
    });
    
    // Smooth scroll for navigation links
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (href.startsWith('#')) {
                e.preventDefault();
                const target = document.querySelector(href);
                if (target) {
                    const offsetTop = target.offsetTop - 80;
                    window.scrollTo({
                        top: offsetTop,
                        behavior: 'smooth'
                    });
                }
            }
        });
    });
}

// Login form functionality
function initLoginForm() {
    const loginForm = document.querySelector('#loginForm');
    const emailInput = document.querySelector('#email');
    
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const email = emailInput.value.trim();
            
            if (validateEmail(email)) {
                // Show loading state
                const submitBtn = this.querySelector('.light-btn-primary');
                const originalText = submitBtn.innerHTML;
                
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
                submitBtn.disabled = true;
                
                // Simulate API call
                setTimeout(() => {
                    showSuccessMessage('Welcome to CryptoFaucet Pro! Check your email for login instructions.');
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                    emailInput.value = '';
                }, 2000);
            } else {
                showErrorMessage('Please enter a valid email address.');
            }
        });
    }
    
    // Email input validation
    if (emailInput) {
        emailInput.addEventListener('blur', function() {
            const email = this.value.trim();
            if (email && !validateEmail(email)) {
                this.style.borderColor = '#f5576c';
                showErrorMessage('Please enter a valid email address.');
            } else if (email) {
                this.style.borderColor = '#43e97b';
            }
        });
        
        emailInput.addEventListener('input', function() {
            this.style.borderColor = '';
            hideMessages();
        });
    }
}

// Email validation
function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// Message system
function showSuccessMessage(message) {
    showMessage(message, 'success');
}

function showErrorMessage(message) {
    showMessage(message, 'error');
}

function showMessage(message, type) {
    // Remove existing messages
    hideMessages();
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} light-alert`;
    messageDiv.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
        ${message}
    `;
    
    const loginCard = document.querySelector('.login-card');
    loginCard.insertBefore(messageDiv, loginCard.querySelector('.login-form'));
    
    // Auto-hide after 5 seconds
    setTimeout(() => {
        hideMessages();
    }, 5000);
}

function hideMessages() {
    const messages = document.querySelectorAll('.light-alert');
    messages.forEach(msg => msg.remove());
}

// Scroll animations
function initScrollEffects() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
                
                // Add staggered animation for cards
                if (entry.target.classList.contains('feature-card') || 
                    entry.target.classList.contains('step-card') || 
                    entry.target.classList.contains('stat-card')) {
                    const cards = entry.target.parentElement.querySelectorAll('.feature-card, .step-card, .stat-card');
                    cards.forEach((card, index) => {
                        setTimeout(() => {
                            card.style.opacity = '1';
                            card.style.transform = 'translateY(0)';
                        }, index * 100);
                    });
                }
            }
        });
    }, observerOptions);
    
    // Observe elements for animation
    const animatedElements = document.querySelectorAll('.feature-card, .step-card, .stat-card, .section-header');
    animatedElements.forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(30px)';
        el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(el);
    });
}

// Floating elements animation
function initFloatingElements() {
    const elements = document.querySelectorAll('.element');
    
    elements.forEach((element, index) => {
        // Add random movement
        setInterval(() => {
            const randomX = Math.random() * 20 - 10;
            const randomY = Math.random() * 20 - 10;
            element.style.transform = `translate(${randomX}px, ${randomY}px)`;
        }, 3000 + index * 500);
    });
}

// Counter animations
function initCounterAnimations() {
    const stats = document.querySelectorAll('.stat-number, .stat-value');
    
    const counterObserver = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                animateCounter(entry.target);
                counterObserver.unobserve(entry.target);
            }
        });
    });
    
    stats.forEach(stat => {
        counterObserver.observe(stat);
    });
}

function animateCounter(element) {
    const text = element.textContent;
    const numberMatch = text.match(/[\d,]+/);
    
    if (numberMatch) {
        const finalNumber = parseInt(numberMatch[0].replace(/,/g, ''));
        const duration = 2000;
        const increment = finalNumber / (duration / 16);
        let current = 0;
        
        const timer = setInterval(() => {
            current += increment;
            if (current >= finalNumber) {
                current = finalNumber;
                clearInterval(timer);
            }
            
            const formattedNumber = Math.floor(current).toLocaleString();
            element.textContent = text.replace(/[\d,]+/, formattedNumber);
        }, 16);
    }
}

// Earnings feed functionality
function initEarningsFeed() {
    const earningsList = document.querySelector('.earnings-list');
    
    // Simulate live updates
    setInterval(() => {
        addNewEarning();
    }, 10000);
    
    // Add initial earnings with animation
    const earningItems = document.querySelectorAll('.earning-item');
    earningItems.forEach((item, index) => {
        item.style.opacity = '0';
        item.style.transform = 'translateX(-20px)';
        item.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        
        setTimeout(() => {
            item.style.opacity = '1';
            item.style.transform = 'translateX(0)';
        }, index * 200);
    });
}

function addNewEarning() {
    const earningsList = document.querySelector('.earnings-list');
    const earningItem = document.createElement('div');
    earningItem.className = 'earning-item';
    
    const users = ['CryptoMaster', 'BitcoinEarner', 'EthCollector', 'LiteCoinPro', 'CryptoNinja'];
    const cryptos = [
        { icon: 'fab fa-bitcoin', name: 'Bitcoin', symbol: 'BTC' },
        { icon: 'fab fa-ethereum', name: 'Ethereum', symbol: 'ETH' },
        { icon: 'fas fa-coins', name: 'Litecoin', symbol: 'LTC' }
    ];
    
    const randomUser = users[Math.floor(Math.random() * users.length)];
    const randomCrypto = cryptos[Math.floor(Math.random() * cryptos.length)];
    const randomAmount = (Math.random() * 0.01).toFixed(5);
    const randomUsd = (Math.random() * 100 + 50).toFixed(2);
    
    earningItem.innerHTML = `
        <div class="user-info">
            <div class="user-avatar">
                <i class="fas fa-user"></i>
            </div>
            <div class="user-details">
                <span class="username">${randomUser}${Math.floor(Math.random() * 1000)}</span>
                <span class="time">Just now</span>
            </div>
        </div>
        <div class="earning-details">
            <div class="crypto-info">
                <i class="${randomCrypto.icon}"></i>
                <span>${randomCrypto.name}</span>
            </div>
            <div class="amount">
                <span class="crypto-amount">${randomAmount} ${randomCrypto.symbol}</span>
                <span class="usd-amount">≈ $${randomUsd}</span>
            </div>
        </div>
    `;
    
    earningItem.style.opacity = '0';
    earningItem.style.transform = 'translateX(-20px)';
    earningItem.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    
    earningsList.insertBefore(earningItem, earningsList.firstChild);
    
    setTimeout(() => {
        earningItem.style.opacity = '1';
        earningItem.style.transform = 'translateX(0)';
    }, 100);
    
    // Remove old items if too many
    const items = earningsList.querySelectorAll('.earning-item');
    if (items.length > 5) {
        items[items.length - 1].remove();
    }
}

// Accordion functionality
function initAccordion() {
    const accordionButtons = document.querySelectorAll('.accordion-button');
    
    accordionButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Add ripple effect
            const ripple = document.createElement('div');
            ripple.className = 'ripple-effect';
            
            const rect = this.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = event.clientX - rect.left - size / 2;
            const y = event.clientY - rect.top - size / 2;
            
            ripple.style.cssText = `
                position: absolute;
                width: ${size}px;
                height: ${size}px;
                left: ${x}px;
                top: ${y}px;
                background: radial-gradient(circle, rgba(102, 126, 234, 0.3) 0%, transparent 70%);
                border-radius: 50%;
                transform: scale(0);
                animation: ripple 0.6s linear;
                pointer-events: none;
            `;
            
            this.style.position = 'relative';
            this.appendChild(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    });
}

// Scroll to top functionality
function initScrollToTop() {
    const scrollButton = document.createElement('button');
    scrollButton.innerHTML = '<i class="fas fa-arrow-up"></i>';
    scrollButton.className = 'scroll-to-top';
    scrollButton.onclick = () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    };
    
    scrollButton.style.cssText = `
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 50px;
        height: 50px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        border-radius: 50%;
        color: white;
        font-size: 1.2rem;
        cursor: pointer;
        z-index: 1000;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
        box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
    `;
    
    document.body.appendChild(scrollButton);
    
    // Show/hide scroll button
    window.addEventListener('scroll', function() {
        if (window.scrollY > 300) {
            scrollButton.style.opacity = '1';
            scrollButton.style.visibility = 'visible';
        } else {
            scrollButton.style.opacity = '0';
            scrollButton.style.visibility = 'hidden';
        }
    });
    
    scrollButton.addEventListener('mouseenter', function() {
        this.style.transform = 'scale(1.1) rotate(10deg)';
    });
    
    scrollButton.addEventListener('mouseleave', function() {
        this.style.transform = 'scale(1) rotate(0deg)';
    });
}

// Initialize animations
function initAnimations() {
    // Add CSS for animations
    const style = document.createElement('style');
    style.textContent = `
        @keyframes ripple {
            to {
                transform: scale(2);
                opacity: 0;
            }
        }
        
        .light-alert {
            background: rgba(67, 233, 123, 0.1) !important;
            border: 1px solid rgba(67, 233, 123, 0.3) !important;
            color: #43e97b !important;
            border-radius: 12px !important;
            margin-bottom: 1rem;
            padding: 1rem;
            animation: slideIn 0.3s ease;
        }
        
        .alert-danger.light-alert {
            background: rgba(245, 87, 108, 0.1) !important;
            border-color: rgba(245, 87, 108, 0.3) !important;
            color: #f5576c !important;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .feature-card:hover .feature-icon {
            animation: bounce 0.6s ease;
        }
        
        @keyframes bounce {
            0%, 20%, 60%, 100% {
                transform: translateY(0);
            }
            40% {
                transform: translateY(-10px);
            }
            80% {
                transform: translateY(-5px);
            }
        }
        
        .step-card:hover .step-icon {
            animation: rotate 0.6s ease;
        }
        
        @keyframes rotate {
            0% { transform: rotate(0deg) scale(1); }
            50% { transform: rotate(180deg) scale(1.1); }
            100% { transform: rotate(360deg) scale(1); }
        }
        
        .earning-item {
            animation: slideInFromLeft 0.6s ease;
        }
        
        @keyframes slideInFromLeft {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
    `;
    document.head.appendChild(style);
}

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

// Optimize scroll events
const debouncedScrollHandler = debounce(function() {
    // Handle scroll events here if needed
}, 16);

window.addEventListener('scroll', debouncedScrollHandler);

// Add smooth hover effects
document.addEventListener('DOMContentLoaded', function() {
    // Add hover effects to cards
    const cards = document.querySelectorAll('.feature-card, .step-card, .stat-card');
    
    cards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-10px)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });
    
    // Add click effects to buttons
    const buttons = document.querySelectorAll('.light-btn-primary, .light-btn-nav');
    
    buttons.forEach(button => {
        button.addEventListener('click', function(e) {
            const ripple = document.createElement('span');
            const rect = this.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = e.clientX - rect.left - size / 2;
            const y = e.clientY - rect.top - size / 2;
            
            ripple.style.cssText = `
                position: absolute;
                width: ${size}px;
                height: ${size}px;
                left: ${x}px;
                top: ${y}px;
                background: radial-gradient(circle, rgba(255, 255, 255, 0.3) 0%, transparent 70%);
                border-radius: 50%;
                transform: scale(0);
                animation: ripple 0.6s linear;
                pointer-events: none;
            `;
            
            this.style.position = 'relative';
            this.style.overflow = 'hidden';
            this.appendChild(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    });
});