// modules/sticky-steps/index.js
import { Logger } from '../../core/logger.js';
import {registerFrameTask, unregisterFrameTask} from '../../core/frameloop.js';

export function init(config = {}) {
    Logger.info('StickySteps init');

    const defaultConfig = {
        containerSelector: '[data-sticky-container]',
        stepSelector: '[data-sticky-step]',
        activeClass: 'is-sticky-active',
        datasetKey: 'activeStickyStep'
    };

    const settings = { ...defaultConfig, ...config };
    const containers = document.querySelectorAll(settings.containerSelector);

    containers.forEach(container => {
        const steps = container.querySelectorAll(settings.stepSelector);
        const containerOffsetTop = container.offsetTop;

        function update() {
            const scrollY = window.scrollY;
            const containerHeight = container.offsetHeight;

            steps.forEach((step, index) => {
                const stepOffset = containerOffsetTop + index * (containerHeight / steps.length);
                const nextStepOffset = containerOffsetTop + (index + 1) * (containerHeight / steps.length);

                const isActive = scrollY >= stepOffset && scrollY < nextStepOffset;
                step.classList.toggle(settings.activeClass, isActive);

                if (isActive) {
                    container.dataset[settings.datasetKey] = index;
                }
            });
        }

        registerFrameTask(`sticky-steps-${container.dataset.moduleId || Math.random()}`, update, { autoStart: true });
    });
}

export function destroy() {
    unregisterFrameTask('sticky-steps');
}
