// src/resources/js/scrollfx/index.js

import ScrollEngine from './ScrollEngine.js';
import ScrollTrigger from './ScrollTrigger.js';
import {fadeScrollTrigger, fixedZoomScrollTrigger, zoomScrollTrigger} from "./Tween";

export function createTrigger(config) {
    const elements = typeof config.element === 'string'
        ? document.querySelectorAll(config.element)
        : [config.element];

    const triggers = [];

    elements.forEach(el => {
        const trigger = new ScrollTrigger({ ...config, element: el });
        ScrollEngine.register(trigger);
        triggers.push(trigger);
    });

    return triggers.length === 1 ? triggers[0] : triggers;
}

export function init(config = {}) {
    const {
        selector = '.fade-in-on-scroll, .zoom-in, .fade-out, .fade',
        offset = 0.85,        // z.B. 85 % Viewport-Höhe
        baseDelay = 0.05,     // delay pro Element (stagger)
        once = true           // nur 1× triggern?
    } = config;

    const elements = Array.from(document.querySelectorAll(selector))
        .map(el => ({ el, triggered: false }));

    function update() {
        const triggerY = window.innerHeight * offset;

        elements.forEach((obj, index) => {
            if (obj.triggered && once) return;

            const rect = obj.el.getBoundingClientRect();

            if (rect.top < triggerY) {
                obj.el.style.transitionDelay = `${index * baseDelay}s`;
                obj.el.classList.add('visible', 'entered');
                obj.el.classList.remove('fade-out');
                obj.triggered = true;
            } else if (!once) {
                obj.el.classList.remove('visible', 'entered');
                obj.triggered = false;
            }
        });

        requestAnimationFrame(update);
    }

    requestAnimationFrame(update);
}
