function ChatAnimation({ questions }) {
  const textRef = React.useRef(null);
  const wrapRef = React.useRef(null);

  React.useEffect(() => {
    const el = textRef.current;
    const wrap = wrapRef.current;
    if (!el || !wrap) return;

    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    let cancelled = false;
    const sleep = ms => new Promise(r => setTimeout(r, ms));

    async function run() {
      let idx = 0;
      while (!cancelled) {
        const q = questions[idx % questions.length];
        idx++;

        wrap.style.transition = 'none';
        wrap.style.opacity = '1';
        el.textContent = '';

        if (prefersReduced) {
          el.textContent = q;
          await sleep(3000);
        } else {
          for (let i = 0; i <= q.length; i++) {
            if (cancelled) return;
            el.textContent = q.slice(0, i);
            await sleep(40);
          }
          if (cancelled) return;
          await sleep(2500);
        }

        if (cancelled) return;
        wrap.style.transition = 'opacity 600ms ease';
        wrap.style.opacity = '0';
        await sleep(700);

        if (cancelled) return;
        el.textContent = '';
        await sleep(800);
      }
    }

    run();
    return () => { cancelled = true; };
  }, []);

  return (
    <div className="q-chat-animation">
      <div ref={wrapRef}>
        <span ref={textRef} className="q-chat-text"></span>
        <span className="q-chat-cursor"></span>
      </div>
    </div>
  );
}

Object.assign(window, { ChatAnimation });
