// BlurText — word-by-word blur-in triggered when 10% visible.
// Splits by spaces; staggers each word; 3-step keyframes per word.

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

function BlurText({ text, className, stepDuration = 0.35 }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setVisible(true);
            io.disconnect();
          }
        });
      },
      { threshold: 0.1 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const words = (text || '').split(/\s+/).filter(Boolean);

  return (
    <p
      ref={ref}
      className={className}
      style={{
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'center',
        rowGap: '0.1em',
        margin: 0,
      }}
    >
      {words.map((w, i) => (
        <motion.span
          key={i}
          initial={{ filter: 'blur(10px)', opacity: 0, y: 50 }}
          animate={
            visible
              ? {
                  filter: ['blur(10px)', 'blur(5px)', 'blur(0px)'],
                  opacity: [0, 0.5, 1],
                  y: [50, -5, 0],
                }
              : {}
          }
          transition={{
            duration: stepDuration * 2,
            times: [0, 0.5, 1],
            ease: 'easeOut',
            delay: (i * 100) / 1000,
          }}
          style={{
            display: 'inline-block',
            marginRight: '0.28em',
            willChange: 'transform, filter, opacity',
          }}
        >
          {w}
        </motion.span>
      ))}
    </p>
  );
}

Object.assign(window, { BlurText });
