const enum Direction {
  Forward = 1,
  Backward = -1,
}
const InitialPosition = 1

// Type character by character at `speed`, wait for `delay`, delete character by character, next
export function typingAnimation({
  element,
  texts,
  speed,
  delay,
  index = 0,
  position = InitialPosition,
  direction = Direction.Forward,
}: {
  element: HTMLElement
  texts: string[]
  speed: number
  delay: number
  index?: number
  position?: number
  direction?: Direction
}) {
  if (!element.isConnected)
    return

  const text = texts[index % texts.length]
  element.textContent = text.slice(0, position * direction)

  const shouldSwitchDirection = position === text.length
  const shouldDelay = direction === Direction.Forward && shouldSwitchDirection
  const shouldGoNext = direction === Direction.Backward && shouldSwitchDirection

  setTimeout(() => typingAnimation({
    element,
    texts,
    speed,
    delay,
    index: shouldGoNext ? index + 1 : index,
    position: shouldSwitchDirection ? InitialPosition : position + 1,
    direction: shouldSwitchDirection ? direction * -1 : direction,
  }), shouldDelay ? delay : speed)
}