// ============================================
// AniCineHub - Main JavaScript
// ============================================

document.addEventListener('DOMContentLoaded', () => {
    // Initialize all components
    initLoadingScreen();
    initNavbar();
    initScrollToTop();
    initCookieConsent();
    initModal();
    initLazyLoading();
    initScrollReveal();
});

// Loading Screen
function initLoadingScreen() {
    const loadingScreen = document.getElementById('loadingScreen');
    if (loadingScreen) {
        window.addEventListener('load', () => {
            setTimeout(() => {
                loadingScreen.classList.add('hidden');
            }, 500);
        });
    }
}

// Navbar Functionality
function initNavbar() {
    const navbar = document.getElementById('navbar');
    const hamburger = document.getElementById('hamburger');
    const navMenu = document.getElementById('navMenu');
    const mobileMenuOverlay = document.getElementById('mobileMenuOverlay');
    const searchToggle = document.getElementById('searchToggle');
    const searchDropdown = document.getElementById('searchDropdown');
    const closeSearch = document.getElementById('closeSearch');
    const nightModeToggle = document.getElementById('nightModeToggle');

    // Scroll effect
    window.addEventListener('scroll', () => {
        if (window.scrollY > 50) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
    });

    // Mobile menu toggle
    if (hamburger && navMenu) {
        hamburger.addEventListener('click', () => {
            hamburger.classList.toggle('active');
            navMenu.classList.toggle('active');
            mobileMenuOverlay.classList.toggle('active');
        });

        // Close menu when clicking overlay
        mobileMenuOverlay.addEventListener('click', () => {
            hamburger.classList.remove('active');
            navMenu.classList.remove('active');
            mobileMenuOverlay.classList.remove('active');
        });

        // Close menu when clicking a link
        const navLinks = navMenu.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
            link.addEventListener('click', () => {
                hamburger.classList.remove('active');
                navMenu.classList.remove('active');
                mobileMenuOverlay.classList.remove('active');
            });
        });
    }

    // Search dropdown toggle
    if (searchToggle && searchDropdown) {
        searchToggle.addEventListener('click', () => {
            searchDropdown.classList.add('active');
            setTimeout(() => {
                document.getElementById('navSearchInput')?.focus();
            }, 100);
        });

        closeSearch.addEventListener('click', () => {
            searchDropdown.classList.remove('active');
        });
    }

    // Night mode toggle
    if (nightModeToggle) {
        // Check saved preference - default to dark mode
        const nightMode = getCookie('night_mode');

        // If no preference set, default to night mode
        if (nightMode === null) {
            document.body.classList.add('night-mode');
            nightModeToggle.innerHTML = '<i class="fas fa-sun"></i>';
            setCookie('night_mode', 'true', 365);
        } else if (nightMode === 'false') {
            document.body.classList.remove('night-mode');
            nightModeToggle.innerHTML = '<i class="fas fa-moon"></i>';
        } else {
            document.body.classList.add('night-mode');
            nightModeToggle.innerHTML = '<i class="fas fa-sun"></i>';
        }

        nightModeToggle.addEventListener('click', () => {
            const isCurrentlyNight = document.body.classList.contains('night-mode');

            if (isCurrentlyNight) {
                // Switch to light mode
                document.body.classList.remove('night-mode');
                setCookie('night_mode', 'false', 365);
                nightModeToggle.innerHTML = '<i class="fas fa-moon"></i>';
            } else {
                // Switch to night mode
                document.body.classList.add('night-mode');
                setCookie('night_mode', 'true', 365);
                nightModeToggle.innerHTML = '<i class="fas fa-sun"></i>';
            }
        });
    }
}

// Scroll to Top Button
function initScrollToTop() {
    const scrollBtn = document.getElementById('scrollToTop');
    if (!scrollBtn) return;

    window.addEventListener('scroll', () => {
        if (window.scrollY > 500) {
            scrollBtn.classList.add('visible');
        } else {
            scrollBtn.classList.remove('visible');
        }
    });

    scrollBtn.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// Cookie Consent
function initCookieConsent() {
    const cookieConsent = document.getElementById('cookieConsent');
    const acceptBtn = document.getElementById('acceptCookies');

    if (!cookieConsent) return;

    // Check if user already accepted
    if (!getCookie('cookies_accepted')) {
        setTimeout(() => {
            cookieConsent.classList.add('show');
        }, 2000);
    }

    if (acceptBtn) {
        acceptBtn.addEventListener('click', () => {
            setCookie('cookies_accepted', 'true', 365);
            cookieConsent.classList.remove('show');
        });
    }
}

// Modal System
function initModal() {
    const modal = document.getElementById('trailerModal');
    const modalOverlay = document.getElementById('modalOverlay');
    const modalClose = document.getElementById('modalClose');
    const trailerFrame = document.getElementById('trailerFrame');

    if (!modal) return;

    // Close modal
    const closeModal = () => {
        modal.classList.remove('active');
        trailerFrame.src = '';
    };

    modalOverlay?.addEventListener('click', closeModal);
    modalClose?.addEventListener('click', closeModal);

    // ESC key to close
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && modal.classList.contains('active')) {
            closeModal();
        }
    });
}

// Play Trailer Function
function playTrailer(videoKey) {
    const modal = document.getElementById('trailerModal');
    const trailerFrame = document.getElementById('trailerFrame');

    if (modal && trailerFrame && videoKey) {
        trailerFrame.src = `https://www.youtube.com/embed/${videoKey}?autoplay=1`;
        modal.classList.add('active');
    }
}

// Lazy Loading Images
function initLazyLoading() {
    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));
}

// Scroll Reveal Animation
function initScrollReveal() {
    const revealElements = document.querySelectorAll('.scroll-reveal, .card-entrance');

    const revealObserver = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                setTimeout(() => {
                    entry.target.classList.add('visible', 'revealed');
                }, index * 50);
                revealObserver.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });

    revealElements.forEach(el => revealObserver.observe(el));
}

// Cookie Helper Functions
function setCookie(name, value, days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    const expires = "expires=" + date.toUTCString();
    document.cookie = name + "=" + value + ";" + expires + ";path=/";
}

function getCookie(name) {
    const nameEQ = name + "=";
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

// Show Notification
function showNotification(message, type = 'success') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
        <span>${message}</span>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        notification.style.animation = 'fadeOut 0.3s ease-out';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// Format Number
function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num;
}

// Truncate Text
function truncateText(text, maxLength) {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
}
