"use client";

import { useEffect, useRef, useState } from "react";

import styles from "./GPTAnimationText.module.scss";

interface GPTAnimationTextProps {
  points: Array<string>;
  totalAnimationTime: number;
}

function GPTAnimationText({
  points,
  totalAnimationTime,
}: GPTAnimationTextProps) {
  const listRef = useRef<Array<HTMLParagraphElement | null>>([]);
  const [listHeight, setListHeight] = useState(0);

  useEffect(() => {
    let maxHeight = 0;
    listRef.current.forEach(item => {
      if (item?.offsetHeight && item.offsetHeight > maxHeight) {
        maxHeight = item.offsetHeight;
      }
    });
    setListHeight(maxHeight);
  }, [listRef]);

  return (
    <div
      className={styles.list}
      style={{
        height: `${listHeight}px`,
      }}
    >
      {points.map((element, index) => (
        <p
          key={element}
          className={styles.item}
          ref={el => {
            listRef.current[index] = el;
          }}
          style={{
            animationDuration: `${totalAnimationTime / points.length}ms`,
            animationDelay: `${index * (totalAnimationTime / points.length)}ms`,
          }}
        >
          {element}
          <span
            className={styles.line}
            style={{
              animationDuration: `${totalAnimationTime / points.length}ms`,
            }}
          />
        </p>
      ))}
    </div>
  );
}

export default GPTAnimationText;
