const { useEffect: useBlurEffect, useRef: useBlurRef, useState } = React;
const { motion } = window.Motion;

function BlurText({ text, className = "", as = "p" }) {
  const rootRef = useBlurRef(null);
  const [visible, setVisible] = useState(false);
  const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const Tag = as;

  useBlurEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setVisible(true);
        observer.disconnect();
      }
    }, { threshold: 0.1 });
    if (rootRef.current) observer.observe(rootRef.current);
    return () => observer.disconnect();
  }, []);

  return (
    <Tag ref={rootRef} className={className} style={{ display: "flex", flexWrap: "wrap", justifyContent: "center", rowGap: "0.1em" }}>
      {text.split(" ").map((word, i) => (
        <motion.span
          key={`${word}-${i}`}
          initial={reducedMotion ? false : { filter: "blur(10px)", opacity: 0, y: 50 }}
          animate={visible ? (reducedMotion ? { filter: "blur(0px)", opacity: 1, y: 0 } : { filter: ["blur(10px)", "blur(5px)", "blur(0px)"], opacity: [0, 0.5, 1], y: [50, -5, 0] }) : {}}
          transition={reducedMotion ? { duration: 0 } : { duration: 0.7, times: [0, 0.5, 1], ease: "easeOut", delay: (i * 100) / 1000 }}
          style={{ display: "inline-block", marginRight: "0.28em" }}
        >{word}</motion.span>
      ))}
    </Tag>
  );
}

window.BlurText = BlurText;
