// ============================================
// RYLL STORE - CUSTOM JAVASCRIPT
// ============================================

// Banner Slider Component for Alpine.js
function bannerSlider() {
    return {
        activeSlide: 0,
        slides: [
            '/images/banner/ml.png',
            '/images/banner/ff.png',
            '/images/banner/valo.png'
        ],
        autoSlideInterval: null,

        // Start auto slide
        startAutoSlide() {
            this.autoSlideInterval = setInterval(() => {
                this.nextSlide();
            }, 4000); // Change slide every 4 seconds
        },

        // Stop auto slide
        stopAutoSlide() {
            if (this.autoSlideInterval) {
                clearInterval(this.autoSlideInterval);
            }
        },

        // Next slide
        nextSlide() {
            this.activeSlide = (this.activeSlide + 1) % this.slides.length;
        },

        // Previous slide
        prevSlide() {
            this.activeSlide = (this.activeSlide - 1 + this.slides.length) % this.slides.length;
        },

        // Go to specific slide
        goToSlide(index) {
            this.activeSlide = index;
        }
    }
}

// ============================================
// SMOOTH SCROLL TO SECTION
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    // Smooth scroll for anchor links
    const anchorLinks = document.querySelectorAll('a[href^="#"]');
    
    anchorLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            
            // Skip if href is just "#"
            if (href === '#') return;
            
            e.preventDefault();
            
            const target = document.querySelector(href);
            if (target) {
                const offsetTop = target.offsetTop - 80; // Account for fixed navbar
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
            }
        });
    });
});

// ============================================
// NAVBAR SCROLL EFFECT
// ============================================
window.addEventListener('scroll', function() {
    const nav = document.querySelector('nav');
    
    if (!nav) return;
    
    if (window.scrollY > 50) {
        nav.classList.add('shadow-lg');
    } else {
        nav.classList.remove('shadow-lg');
    }
});

// ============================================
// LAZY LOAD IMAGES
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    const images = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.removeAttribute('data-src');
                observer.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
});

// ============================================
// GAME CARD CLICK ANALYTICS (Optional)
// ============================================
function trackGameClick(gameName) {
    // Log to console (replace with actual analytics)
    console.log('Game clicked:', gameName);
    
    // Example: Send to Google Analytics
    // if (typeof gtag !== 'undefined') {
    //     gtag('event', 'game_click', {
    //         'event_category': 'engagement',
    //         'event_label': gameName
    //     });
    // }
}

// ============================================
// MOBILE MENU TOGGLE
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    const mobileMenuBtn = document.querySelector('.md\\:hidden button');
    
    if (mobileMenuBtn) {
        mobileMenuBtn.addEventListener('click', function() {
            // Toggle mobile menu (implement your mobile menu here)
            console.log('Mobile menu toggled');
            // You can add mobile menu HTML and toggle it here
        });
    }
});

// ============================================
// SEARCH FUNCTIONALITY (Optional)
// ============================================
function searchGames(query) {
    // 1. Ambil kabeh kartu kategori
    const gameCards = document.querySelectorAll('.game-card');
    
    // 2. Mun kosong, tampilkeun kabeh deui
    if (!query || query.trim() === "") {
        gameCards.forEach(card => card.style.display = 'block');
        return;
    }

    // 3. Bersihkeun input (lowercase & hapus spasi)
    const term = query.toLowerCase().replace(/\s+/g, '');

    gameCards.forEach(card => {
        // Cek teks dina h3 (Ngaran) atawa p (Deskripsi)
        const text = card.innerText.toLowerCase().replace(/\s+/g, '');
        
        if (text.includes(term)) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
}

// ============================================
// SCROLL TO TOP BUTTON
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    // Create scroll to top button
    const scrollBtn = document.createElement('button');
    scrollBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
    scrollBtn.className = 'fixed bottom-8 right-8 w-12 h-12 bg-gradient-to-r from-cyan-500 to-blue-600 rounded-full flex items-center justify-center text-white shadow-lg opacity-0 pointer-events-none transition-all duration-300 z-50';
    scrollBtn.id = 'scrollToTop';
    document.body.appendChild(scrollBtn);
    
    // Show/hide button on scroll
    window.addEventListener('scroll', function() {
        if (window.scrollY > 300) {
            scrollBtn.classList.remove('opacity-0', 'pointer-events-none');
            scrollBtn.classList.add('opacity-100', 'hover:scale-110');
        } else {
            scrollBtn.classList.add('opacity-0', 'pointer-events-none');
            scrollBtn.classList.remove('opacity-100', 'hover:scale-110');
        }
    });
    
    // Scroll to top on click
    scrollBtn.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
});

// ============================================
// PRELOADER (Optional)
// ============================================
window.addEventListener('load', function() {
    const preloader = document.getElementById('preloader');
    if (preloader) {
        preloader.style.opacity = '0';
        setTimeout(() => {
            preloader.style.display = 'none';
        }, 300);
    }
});

// ============================================
// PERFORMANCE MONITORING
// ============================================
if ('performance' in window) {
    window.addEventListener('load', function() {
        const perfData = window.performance.timing;
        const pageLoadTime = perfData.loadEventEnd - perfData.navigationStart;
        console.log('Page load time:', pageLoadTime + 'ms');
    });
}

// ============================================
// ERROR HANDLING FOR IMAGES
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    const images = document.querySelectorAll('img');
    
    images.forEach(img => {
        img.addEventListener('error', function() {
            if (this.src.includes('/images/placeholder.png')) return;
            // Replace with placeholder if image fails to load
            this.src = '/images/placeholder.png';
            this.alt = 'Image not available';
        });
    });
});

// ============================================
// COPY TO CLIPBOARD UTILITY
// ============================================
function copyToClipboard(text) {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
            showNotification('Copied to clipboard!', 'success');
        });
    } else {
        // Fallback for older browsers
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        showNotification('Copied to clipboard!', 'success');
    }
}

// ============================================
// NOTIFICATION SYSTEM
// ============================================
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `fixed top-20 right-4 px-6 py-4 rounded-lg shadow-lg text-white z-50 transition-all duration-300 transform translate-x-full`;
    
    const bgColors = {
        success: 'bg-green-500',
        error: 'bg-red-500',
        warning: 'bg-yellow-500',
        info: 'bg-blue-500'
    };
    
    notification.classList.add(bgColors[type] || bgColors.info);
    notification.innerHTML = `
        <div class="flex items-center gap-3">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'times-circle' : 'info-circle'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // Animate in
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 10);
    
    // Auto remove after 3 seconds
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// ============================================
// FORMAT CURRENCY
// ============================================
function formatCurrency(amount) {
    return new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR',
        minimumFractionDigits: 0
    }).format(amount);
}

// ============================================
// EXPORT FUNCTIONS FOR GLOBAL USE
// ============================================
window.bannerSlider = bannerSlider;
window.trackGameClick = trackGameClick;
window.searchGames = searchGames;
window.copyToClipboard = copyToClipboard;
window.showNotification = showNotification;
window.formatCurrency = formatCurrency;
// ============================================
// View Product
// ============================================
