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
        while(topValue < (height)) {
            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("c-scroll-icon");
            scrollIcon.src = iconSource.dataset.scrollIcon;
            scrollIcon.style.top = `${topValue}px`;
            // Sets distance from left screen side with a simple sine wave
            // The division is used to make this sine wave inverse to the rotation sine wave above
            // This makes sure that the orientation matches the position of the icon
            // Increasing this value makes the curve bigger, but the rotation also has to be divided (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);
            // Increase or decrease this value to make the distance between icons bigger or smaller
            topValue = topValue + 150;
        }

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

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