/**
 * Enhanced Animations for Public Pages
 * Includes scroll-triggered animations, parallax, and micro-interactions
 */

(function () {
    'use strict';

    // Check for reduced motion preference
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (prefersReducedMotion) return;

    // ============================================================================
    // SCROLL-TRIGGERED ANIMATIONS (Intersection Observer)
    // ============================================================================

    const observerOptions = {
        root: null,
        rootMargin: '0px 0px -100px 0px',
        threshold: 0.1
    };

    const animateOnScroll = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-in');
                // Stagger children if present
                const children = entry.target.querySelectorAll('.stagger-child');
                children.forEach((child, index) => {
                    child.style.transitionDelay = `${index * 100}ms`;
                    child.classList.add('animate-in');
                });
            }
        });
    }, observerOptions);

    // Observe all animatable elements
    document.querySelectorAll('.animate-on-scroll, .card, .section-header, .filter-bar').forEach(el => {
        el.classList.add('pre-animate');
        animateOnScroll.observe(el);
    });

    // ============================================================================
    // 3D TILT CARD EFFECT
    // ============================================================================

    const cards = document.querySelectorAll('.card');

    cards.forEach(card => {
        card.addEventListener('mousemove', (e) => {
            const rect = card.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;

            const centerX = rect.width / 2;
            const centerY = rect.height / 2;

            const rotateX = (y - centerY) / 20;
            const rotateY = (centerX - x) / 20;

            card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) translateZ(10px)`;

            // Spotlight effect
            const spotX = (x / rect.width) * 100;
            const spotY = (y / rect.height) * 100;
            card.style.setProperty('--spot-x', `${spotX}%`);
            card.style.setProperty('--spot-y', `${spotY}%`);
        });

        card.addEventListener('mouseleave', () => {
            card.style.transform = 'perspective(1000px) rotateX(0) rotateY(0) translateZ(0)';
        });
    });

    // ============================================================================
    // MAGNETIC BUTTONS
    // ============================================================================

    const magneticElements = document.querySelectorAll('.btn-primary, .btn-lg');

    magneticElements.forEach(btn => {
        btn.addEventListener('mousemove', (e) => {
            const rect = btn.getBoundingClientRect();
            const x = e.clientX - rect.left - rect.width / 2;
            const y = e.clientY - rect.top - rect.height / 2;

            btn.style.transform = `translate(${x * 0.2}px, ${y * 0.2}px)`;
        });

        btn.addEventListener('mouseleave', () => {
            btn.style.transform = 'translate(0, 0)';
        });
    });

    // ============================================================================
    // PARALLAX BACKGROUND
    // ============================================================================

    const parallaxElements = document.querySelectorAll('.hero, [data-parallax]');

    window.addEventListener('scroll', () => {
        const scrolled = window.pageYOffset;

        parallaxElements.forEach(el => {
            const speed = el.dataset.parallaxSpeed || 0.5;
            const yPos = -(scrolled * speed);
            el.style.setProperty('--parallax-y', `${yPos}px`);
        });
    }, { passive: true });

    // ============================================================================
    // TYPING EFFECT FOR HERO
    // ============================================================================

    const heroBadge = document.querySelector('.hero-badge');
    if (heroBadge) {
        const text = heroBadge.textContent;
        heroBadge.textContent = '';
        heroBadge.style.opacity = '1';

        let i = 0;
        const typeEffect = setInterval(() => {
            if (i < text.length) {
                heroBadge.textContent += text.charAt(i);
                i++;
            } else {
                clearInterval(typeEffect);
            }
        }, 50);
    }

    // ============================================================================
    // SMOOTH COUNTER ANIMATION
    // ============================================================================

    const counters = document.querySelectorAll('[data-counter]');

    const animateCounter = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const target = parseInt(entry.target.dataset.counter);
                let current = 0;
                const increment = target / 50;
                const duration = 1500;
                const stepTime = duration / 50;

                const counter = setInterval(() => {
                    current += increment;
                    if (current >= target) {
                        entry.target.textContent = target;
                        clearInterval(counter);
                    } else {
                        entry.target.textContent = Math.floor(current);
                    }
                }, stepTime);

                animateCounter.unobserve(entry.target);
            }
        });
    }, { threshold: 0.5 });

    counters.forEach(counter => animateCounter.observe(counter));

    // ============================================================================
    // RIPPLE EFFECT ON BUTTONS
    // ============================================================================

    document.querySelectorAll('.btn').forEach(btn => {
        btn.addEventListener('click', function (e) {
            const rect = btn.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;

            const ripple = document.createElement('span');
            ripple.className = 'ripple-effect';
            ripple.style.left = x + 'px';
            ripple.style.top = y + 'px';

            btn.appendChild(ripple);

            setTimeout(() => ripple.remove(), 600);
        });
    });

    // ============================================================================
    // SMOOTH SCROLL REVEAL FOR SECTIONS
    // ============================================================================

    const sections = document.querySelectorAll('.section');
    let lastScrollY = window.scrollY;

    window.addEventListener('scroll', () => {
        const currentScrollY = window.scrollY;
        const scrollDirection = currentScrollY > lastScrollY ? 'down' : 'up';

        sections.forEach(section => {
            const rect = section.getBoundingClientRect();
            const isVisible = rect.top < window.innerHeight * 0.8;

            if (isVisible) {
                section.style.opacity = '1';
                section.style.transform = 'translateY(0)';
            }
        });

        lastScrollY = currentScrollY;
    }, { passive: true });

    // ============================================================================
    // CURSOR TRAILER (Optional - Premium Effect)
    // ============================================================================

    if (window.innerWidth > 768) {
        const trailer = document.createElement('div');
        trailer.className = 'cursor-trailer';
        document.body.appendChild(trailer);

        let mouseX = 0, mouseY = 0;
        let trailerX = 0, trailerY = 0;

        window.addEventListener('mousemove', (e) => {
            mouseX = e.clientX;
            mouseY = e.clientY;
        });

        function animateTrailer() {
            trailerX += (mouseX - trailerX) * 0.1;
            trailerY += (mouseY - trailerY) * 0.1;

            trailer.style.left = trailerX + 'px';
            trailer.style.top = trailerY + 'px';

            requestAnimationFrame(animateTrailer);
        }

        animateTrailer();

        // Scale up on hover over interactive elements
        document.querySelectorAll('a, button, .card').forEach(el => {
            el.addEventListener('mouseenter', () => {
                trailer.style.transform = 'translate(-50%, -50%) scale(2)';
                trailer.style.background = 'rgba(37, 99, 235, 0.2)';
            });
            el.addEventListener('mouseleave', () => {
                trailer.style.transform = 'translate(-50%, -50%) scale(1)';
                trailer.style.background = 'rgba(37, 99, 235, 0.1)';
            });
        });
    }

    // ============================================================================
    // SKILL BADGES ANIMATION
    // ============================================================================

    const skills = document.querySelectorAll('.skill-badge');
    skills.forEach((skill, index) => {
        skill.style.animationDelay = `${index * 0.1}s`;
        skill.classList.add('skill-pop');
    });

    // ============================================================================
    // NAVBAR SCROLL EFFECT
    // ============================================================================

    const navbar = document.querySelector('.navbar');
    if (navbar) {
        window.addEventListener('scroll', () => {
            if (window.scrollY > 100) {
                navbar.classList.add('navbar-scrolled');
            } else {
                navbar.classList.remove('navbar-scrolled');
            }
        }, { passive: true });
    }

    console.log('✨ Premium animations loaded');
})();
