import React, { useEffect, useState } from 'react';
import styled from 'styled-components';

interface IProps {
  text: string;
  onFinish?: () => void;
  onStart?: () => void;
}

export const DynamicText: React.FC<IProps> = ({ text, onFinish, onStart }) => {
  const [textState, setTextState] = useState<string>('');

  useEffect(() => {
    let i = 0;
    const interval = setInterval(() => {
      // on every interval, show one more character

      if (i === 0) {
        if (onStart) {
          onStart();
        }
      }

      if (i < text.length) {
        setTextState(text.substring(0, i + 1));
        i++;
      } else {
        clearInterval(interval);
        if (onFinish) {
          onFinish();
        }
      }
    }, 25);

    return () => {
      clearInterval(interval);
    };
  }, [text]);

  return <TextContainer>{textState}</TextContainer>;
};

const TextContainer = styled.p`
  font-size: 0.7rem !important;
  color: white;
  text-shadow: 1px 1px 0px #000000;
  letter-spacing: 1.2px;
  word-break: normal;
`;
