import { motion } from 'framer-motion';
import { Fragment, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { isInitialLoaderVisible } from '../../api/storage';
import { RootState } from '../../redux/store';
import styles from './AnimatedPhrase.module.scss';

const phraseVariants = {
  hide: {
    transition: {
      staggerChildren: 0.114,
      staggerDirection: -1,
    },
  },
  show: (delay: boolean) => ({
    transition: {
      staggerChildren: 0.014,
      delayChildren: delay ? 1 : 0,
    },
  }),
};

const variants = {
  hide: {
    y: '100%',
  },
  show: {
    y: '0%',
    transition: {
      duration: 0.35,
      ease: [0.09, 0.6, 0, 1],
    },
  },
};

interface Props {
  phrase: string;
}

const AnimatedPhrase = (props: Props) => {

  const { phrase } = props;
  const { previousRoute, isVisible } = useSelector((state: RootState) => ({
    ...state.router,
    ...state.initialLoader,
  }));
  const [delayChildren] = useState(previousRoute !== '' ? true : false);
  const isLoaderVisible = !isVisible || !isInitialLoaderVisible();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    if (isLoaderVisible) {
      setMounted(true);
    }
  }, [isLoaderVisible]);

  if (!mounted || !phrase) return <div style={{ opacity: 0 }}>{phrase}</div>;
  return (
    <motion.span
      variants={phraseVariants}
      custom={delayChildren}
      initial="hide"
      animate={'show'}
      className={styles.container}
    >
      {[...phrase.split(/\r?\n|\r|\s/g)].map((word) => (
        <Fragment key={word + '_' + Math.random()}>
          <span className={styles.word} key={word}>
            {[...word].map((letter: string, id: number) => (
              <motion.span
                className={styles.letter}
                style={{ display: 'inline-block' }}
                key={id + word?.length - 1}
                variants={variants}
              >
                {letter}
              </motion.span>
            ))}
          </span>
          <span className={styles.space}> </span>
        </Fragment>
      ))}
    </motion.span>
  );
};

export default AnimatedPhrase;
