import {
  motion,
  useScroll,
  useMotionValueEvent,
  useInView,
} from 'framer-motion';
import { useRef, useState } from 'react';

function AppearanceItem({ text, order }: { text: string; order: number }) {
  const ref = useRef<HTMLSpanElement>(null);
  const [isShowed, setIsShowed] = useState(false);

  const { scrollY } = useScroll({});
  const isInView = useInView(ref, {
    once: true,
    margin: '0px 0px -33%',
  });

  useMotionValueEvent(scrollY, 'change', latest => {
    setIsShowed(
      latest >= (ref.current!.offsetTop ?? 0) - (window.innerHeight / 3) * 2,
    );
  });

  return (
    <motion.span
      ref={ref}
      initial={{ opacity: 0 }}
      animate={{ opacity: isShowed || isInView ? 1 : 0.06 }}
      transition={{ duration: 0.9, delay: 0.1 * order }}
    >
      {text}
    </motion.span>
  );
}

export function AppearanceText({
  splits,
  className = '',
}: {
  splits: string[];
  className?: string;
}) {
  return (
    <h3 className={'font-medium h3 ' + className}>
      {splits.map((text, index) => (
        <AppearanceItem key={text} text={text} order={index} />
      ))}
    </h3>
  );
}
