import styles from "./autoscroll.module.scss"
import { useEffect, useRef, useState } from 'react'

type AutoScrollProps = {
  isScrolling: boolean
  onTouch?: () => void
  children: JSX.Element
}
/**
 * This component autoscroll the content from left to right
 * automatically
 *
 */
export const AutoScroll = ({children, isScrolling, onTouch}: AutoScrollProps) => {

  const [step, setStep] = useState(0)
  const [direction, setDirection] = useState<'left' | 'right'>('right')
  const wrapper = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if(wrapper && wrapper.current) {
      if (isScrolling) {
        const scrollSpeed = 30; // 30px per second
        const toScroll = wrapper.current.scrollWidth - window.innerWidth;

        // nothing to scroll
        if (toScroll <= 0) {
          return;
        }

        const steps = toScroll/scrollSpeed * 1000

        const t = setTimeout(() => {
          let left = toScroll * step/steps

          if(wrapper.current) {
            wrapper.current.scrollTo({
              left: left,
            })
          }

          if(step >= steps) {
            setDirection("left")
          }

          if(step <= 0) {
            setDirection("right")
          }

          setStep(direction === "right" ? step + 1 : step - 1)

          return () => clearTimeout(t);
        }, 1);
      }

    }}, [wrapper, step, setStep, direction, setDirection])

  return (
    <div
      className={styles.wrapper}
      ref={wrapper}
      onTouchStart={onTouch}
    >
      {children}
    </div>
  )
}