import { prefersReducedMotion, ensureClones, getOriginalSetWidth } from '../_utils/slider-utils.js';

function initLogoSlider(track) {
    if (!track || track.dataset.logoSliderInitialized === '1') return;
    track.dataset.logoSliderInitialized = '1';

    const speed = Number(track.dataset.speed || 35);
    const pauseOnHover = (track.dataset.pauseOnHover || 'true') !== 'false';

    const originalSlides = Array.from(track.children).filter((el) => el.classList.contains('logo-slider__slide'));
    if (!originalSlides.length) return;

    if (prefersReducedMotion()) return;
    if (!Number.isFinite(speed) || speed <= 0) return;

    const rebuild = () => {
        ensureClones(track, originalSlides, { minWidthFactor: 2 });
        originalSetWidth = getOriginalSetWidth(track, originalSlides);
        track.scrollLeft = 0;
        pos = 0;
        lastTs = 0;
    };

    let originalSetWidth = 1;
    let running = true;
    let lastTs = 0;
    let pos = track.scrollLeft;

    const syncPos = () => (pos = track.scrollLeft);
    track.addEventListener('scroll', syncPos, { passive: true });

    const stop = () => (running = false);
    const resume = () => {
        running = true;
        lastTs = 0;
        syncPos();
    };

    const tick = (ts) => {
        if (!lastTs) lastTs = ts;
        const dt = Math.min(Math.max(ts - lastTs, 0), 50) / 1000;
        lastTs = ts;

        if (running) {
            pos += speed * dt;
            if (pos >= originalSetWidth) pos -= originalSetWidth;
            track.scrollLeft = pos;
        }
        requestAnimationFrame(tick);
    };

    rebuild();
    requestAnimationFrame(tick);

    if (pauseOnHover) {
        track.addEventListener('pointerenter', stop);
        track.addEventListener('pointerleave', resume);
    }
    track.addEventListener('focusin', stop);
    track.addEventListener('focusout', resume);

    let resizeTimer = 0;
    window.addEventListener('resize', () => {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(rebuild, 150);
    });
}

function initAllLogoSliders() {
    document.querySelectorAll('.logo-slider__track[data-logo-slider="1"]').forEach(initLogoSlider);
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initAllLogoSliders);
} else {
    initAllLogoSliders();
}