"use client";

import { animate, motion, useMotionValue, useTransform } from "framer-motion";
import { Courier_Prime } from "next/font/google";
import React, { useEffect, useState } from "react";

const special_elite = Courier_Prime({ weight: "400", subsets: ["latin"] });

type props = {
  children: string;
  styles: string;
  duration: number;
  delay: number;
};

const FramerTextAnimate = ({ children, styles, duration, delay }: props) => {
  const count = useMotionValue(0);
  const baseText = children as string;

  const [durationInternal, setDurationInternal] = useState<number>(duration);

  const rounded = useTransform(count, (latest) => Math.round(latest));
  const displayText = useTransform(rounded, (latest) =>
    baseText.slice(0, latest)
  );

  //   Skip the animation on mouse press
  useEffect(() => {
    const handleClick = (event: MouseEvent) => {
      setDurationInternal(0.5);
    };
    document.addEventListener("click", handleClick);
    return () => {
      document.removeEventListener("click", handleClick);
    };
  }, []);

  useEffect(() => {
    // Delay the animation start
    const delayTimeout = setTimeout(() => {
      const controls = animate(count, baseText.length, {
        duration: durationInternal,
        ease: "easeInOut",
      });
      return () => controls.stop();
    }, delay * 1000);

    // Clear the timeout on unmount to prevent memory leaks
    return () => clearTimeout(delayTimeout);
  }, [durationInternal]);

  const handleUserInput = () => {
    setDurationInternal(0);
    console.log("test");
  };

  return (
    <>
      <motion.span
        onClick={handleUserInput}
        className={`${special_elite.className} ${styles}`}
      >
        {displayText}
      </motion.span>
    </>
  );
};

export default FramerTextAnimate;
