// BlurText — word-by-word blur-in, IntersectionObserver-triggered (10% visible).
// Falls back to instant render if framer-motion isn't available.
function BlurText({ text, className = "", style = {}, startDelay = 0, perWord = 100 }) {
  const M = window.Motion || {};
  const motion = M.motion;
  const ref = React.useRef(null);
  const [v, setV] = React.useState(false);

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

  const words = String(text).split(" ");

  // Fallback: if motion isn't loaded, render plain words
  if (!motion) {
    return (
      <p ref={ref} className={className}
         style={{ display: "flex", flexWrap: "wrap", justifyContent: "center", rowGap: "0.1em", ...style }}>
        {words.map((w, i) => (
          <span key={i} style={{ display: "inline-block", marginRight: "0.28em" }}>{w}</span>
        ))}
      </p>
    );
  }

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

window.BlurText = BlurText;
