import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const dir = document.documentElement.getAttribute('dir') === 'rtl' ? -1 : 1;

function animateCount(el, target, duration = 1.2) {
    const obj = { val: 0 };
    gsap.to(obj, {
        val: target,
        duration,
        ease: 'power2.out',
        onUpdate: () => {
            el.textContent = Math.round(obj.val).toLocaleString();
        },
    });
}

function initHero() {
    const hero = document.querySelector('[data-hero]');
    if (!hero) return;

    const bg = hero.querySelector('.hero-scene__bg');
    const lights = hero.querySelector('.hero-scene__lights');
    const lines = hero.querySelectorAll('.hero-headline-line');
    const ctas = hero.querySelectorAll('.hero-cta');

    if (reducedMotion) {
        if (bg) bg.style.transform = 'scale(1)';
        return;
    }

    const tl = gsap.timeline({ defaults: { ease: 'power2.out' } });

    if (bg) {
        tl.fromTo(bg, { scale: 1.04 }, { scale: 1, duration: 1.2 }, 0);
    }

    tl.from(lines, { yPercent: 110, duration: 0.7, stagger: 0.1 }, 0.15);
    tl.from(ctas, { y: 16, opacity: 0, duration: 0.5, stagger: 0.08 }, 0.45);

    hero.addEventListener('mousemove', (event) => {
        const rect = hero.getBoundingClientRect();
        const x = ((event.clientX - rect.left) / rect.width - 0.5) * 24 * dir;
        const y = ((event.clientY - rect.top) / rect.height - 0.5) * 16;
        const clampedX = Math.max(-12, Math.min(12, x));
        const clampedY = Math.max(-12, Math.min(12, y));

        if (bg) gsap.to(bg, { x: clampedX * 0.4, y: clampedY * 0.3, duration: 0.6, overwrite: 'auto' });
        if (lights) gsap.to(lights, { x: clampedX, y: clampedY, duration: 0.8, overwrite: 'auto' });
    });

    hero.addEventListener('mouseleave', () => {
        if (bg) gsap.to(bg, { x: 0, y: 0, duration: 0.8 });
        if (lights) gsap.to(lights, { x: 0, y: 0, duration: 0.8 });
    });
}

function initStats() {
    document.querySelectorAll('.stat-number[data-target]').forEach((el) => {
        const target = parseInt(el.getAttribute('data-target') || '0', 10);
        if (Number.isNaN(target)) return;

        ScrollTrigger.create({
            trigger: el,
            start: 'top 90%',
            once: true,
            onEnter: () => {
                if (reducedMotion) {
                    el.textContent = target.toLocaleString();
                } else {
                    animateCount(el, target);
                }
            },
        });
    });
}

function initReveals() {
    if (reducedMotion) return;

    gsap.utils.toArray('.popular-games, .upcoming-events, .rail-panel, .community-card').forEach((section) => {
        gsap.from(section, {
            y: 24,
            opacity: 0,
            duration: 0.6,
            ease: 'power2.out',
            scrollTrigger: {
                trigger: section,
                start: 'top 88%',
                once: true,
            },
        });
    });
}

function initHorizontalScroll() {
    document.querySelectorAll('[data-h-scroll]').forEach((scroller) => {
        scroller.addEventListener('keydown', (event) => {
            if (event.key === 'ArrowRight') {
                scroller.scrollBy({ left: 180 * dir, behavior: 'smooth' });
                event.preventDefault();
            }
            if (event.key === 'ArrowLeft') {
                scroller.scrollBy({ left: -180 * dir, behavior: 'smooth' });
                event.preventDefault();
            }
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {
    if (!document.querySelector('[data-dashboard]')) return;
    initHero();
    initStats();
    initReveals();
    initHorizontalScroll();
});
