export function createAutoScroller(container, isActive) {
  let frameId = null;
  let speed = 0;
  let lastTs = null;

  function track(clientY) {
    const vh      = window.innerHeight;
    const topLine = vh * 0.1;
    const botLine = vh * 0.9;

    if (clientY < topLine) {
      const ratio = clientY / topLine;
      start(-vh * (1 - 0.8 * ratio));
    } else if (clientY > botLine) {
      const ratio = (clientY - botLine) / (vh * 0.1);
      start(vh * (0.2 + 0.8 * ratio));
    } else {
      stop();
    }
  }

  function start(nextSpeed) {
    speed = nextSpeed;
    if (!frameId) {
      lastTs  = performance.now();
      frameId = requestAnimationFrame(tick);
    }
  }

  function stop() {
    speed = 0;
    if (frameId) {
      cancelAnimationFrame(frameId);
      frameId = null;
    }
  }

  function tick(now) {
    if (!isActive()) {
      stop();
      return;
    }

    const dt = (now - lastTs) / 1000;
    lastTs = now;
    container.scrollTop += speed * dt;
    frameId = requestAnimationFrame(tick);
  }

  return { track, stop };
}
