import { onPageLoadComplete } from '@nimius/event-utility';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

/* eslint-disable */
const initSitePathAnimation = () => {
    const iconWrapper = document.querySelector(".c-scroll-icon__wrapper");

    if (iconWrapper) {
        const body = document.body;
        const html = document.documentElement;
        const height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
        // Limit width to 50% of whole screen width. Is used to set max. expansion of icon distribution
        const width = (screen.width / 100) * 50;
        const iconSource = document.querySelector('[data-scroll-icon]');
        let topValue = 0;

        // Limit the addition of icons to site height + add one icon in the end
        while(topValue < (height + 150)) {
            const scrollIcon = document.createElement('img');
            // Calculate rotation of each icon, so their orientation follows the scroll path
            // Adjust first value (50) for more swing and last value (180) for different center value
            let rotation = (50 * Math.sin(topValue)) + 180;

            scrollIcon.classList.add("footprint");
            scrollIcon.src = iconSource.dataset.scrollIcon;
            scrollIcon.style.top = `${topValue}px`;
            // Sets distance to left screen side with a simple sine wave
            // The division is used to make this sine wave inverse to the rotation wave above
            // This makes sure that the orientation matches the position of the icon
            // Increasing the value makes the curve bigger, but the orientation also has to be adjusted (divide through half the value of this one)
            scrollIcon.style.left = `${Math.abs((width * Math.sin((topValue / 2))))}px`;
            scrollIcon.style.transform = `rotate(${rotation}deg)`;

            iconWrapper.appendChild(scrollIcon);
            topValue = topValue + 150;
        }

        // gsap scroll trigger settings
        ScrollTrigger.batch(".footprint", {
            start: "top 60%",
            onEnter: elements => gsap.to(elements, {opacity: 1, stagger: .2}),
            onLeaveBack: elements => gsap.set(elements, {opacity: 0})
        });
    }
}

onPageLoadComplete(() => {
    //register plugin
    gsap.registerPlugin(ScrollTrigger);
    initSitePathAnimation();
});
/* eslint-enable */
