/* Looping product demo. All messages and the trade review are illustrative. */
const TextBankDemo = () => {
  const [reducedMotion, setReducedMotion] = useState(() => matchMedia("(prefers-reduced-motion: reduce)").matches);
  const [beat, setBeat] = useState(0);
  const conversation = useRef(null);
  useEffect(() => {
    const preference = matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReducedMotion(preference.matches);
    preference.addEventListener("change", update);
    return () => preference.removeEventListener("change", update);
  }, []);
  useEffect(() => {
    if (reducedMotion) return;
    const timer = setInterval(() => setBeat(value => (value + 1) % 6), 2000);
    return () => clearInterval(timer);
  }, [reducedMotion]);
  const stage = reducedMotion ? 4 : Math.min(beat, 4);
  React.useLayoutEffect(() => {
    const node = conversation.current;
    if (!node || reducedMotion) return;
    const previousTop = node.scrollTop;
    node.scrollTop = stage === 0 ? 0 : node.scrollHeight - node.clientHeight;
    const distance = stage === 0 ? 0 : node.scrollTop - previousTop;
    const messages = Array.from(node.children);
    // Move the conversation and the new bubble together before the next paint.
    // This avoids competing native smooth-scroll and entrance animations.
    const animations = messages.map((message, index) => {
      const newest = index === messages.length - 1;
      return message.animate([
        { transform: `translateY(${distance + (newest ? 12 : 0)}px) scale(${newest ? .98 : 1})`, opacity: newest ? 0 : 1 },
        { transform: "translateY(0) scale(1)", opacity: 1 },
      ], { duration: 420, easing: "cubic-bezier(.22,1,.36,1)" });
    });
    return () => animations.forEach(animation => animation.cancel());
  }, [stage, reducedMotion]);
  return <div className="ld-text-demo" aria-label="Example conversation: check your account and prepare a $10 SPCX investment">
    <div className="ld-text-preview-wash" aria-hidden="true" />
    <div className="ld-demo-conversation" ref={conversation} tabIndex={0} aria-label="Example iMessage conversation">
      <div className="ld-text-bubble ld-text-outgoing">How’s my account doing today?</div>
      {stage >= 1 && <div className="ld-text-bubble ld-text-incoming">Your investments are up 2.3% today, led by SPCX. Your cash is a bit above your 10% target. Looking good.</div>}
      {stage >= 2 && <div className="ld-text-bubble ld-text-outgoing">Great, let’s invest $10 more in SPCX.</div>}
      {stage >= 3 && <div className="ld-text-bubble ld-text-incoming">Sure, setting that up.</div>}
      {stage >= 4 && <article className="message-card" aria-label="Example trade review: buy $10 of SPCX">
        <div className="card-hero"><p className="eyebrow">Yoshi · Trade</p><div className="hero-summary"><h3 className="card-title">Buy SPCX</h3><p className="card-value">$10.00</p></div></div>
        <div className="card-details"><div className="detail-row"><span>Order type</span><strong>Market buy</strong></div><span className="card-action">Review in Yoshi <span className="action-arrow" aria-hidden="true">↗</span></span></div>
      </article>}
    </div>
  </div>;
};

/* Final onboarding invitation. All connection and sending behavior is simulated. */
const ConnectImessage = ({ onConnect, onSkip }) => {
  const [reviewing, setReviewing] = useState(false);
  const heading = useRef(null);
  const copy = window.YOSHI_IMESSAGE_COPY;
  useEffect(() => { heading.current?.focus(); }, [reviewing]);

  return (
    <section className="ld-text-bank" aria-labelledby="text-bank-title" data-screen-label="Connect iMessage">
      <div className={`ld-text-bank-content scroll${reviewing ? "" : " is-invitation"}`}>
        {reviewing ? (
          <>
            <button className="press ld-text-back" onClick={() => setReviewing(false)} aria-label="Back to invitation"><Icon name="back" size={20} /></button>
            <h1 className="ld-heading" id="text-bank-title" ref={heading} tabIndex={-1}>Before you text.</h1>
            <p className="ld-text-bank-description">{copy.body}</p>
            <div className="ld-text-consent">
              <p>{copy.authorization}</p>
              <p>{copy.dataScope}</p>
              <p>{copy.audience}</p>
              <p>{copy.disclosure}</p>
              <div className="ld-text-legal">
                <a href="https://yoshi.ai/termsofservice/" target="_blank" rel="noreferrer">Terms of Service</a>
                <a href="https://yoshi.ai/privacypolicy/" target="_blank" rel="noreferrer">Privacy Policy</a>
              </div>
            </div>
          </>
        ) : (
          <>
            <h1 className="ld-heading" id="text-bank-title" ref={heading} tabIndex={-1}>Ready to text your bank?</h1>
            <p className="ld-text-bank-description">Your money has a new contact. Ask questions, move money, and get guidance over text.</p>
            <TextBankDemo />
            <p className="ld-text-bank-note">You approve every money move in Yoshi.</p>
          </>
        )}
      </div>
      <div className="ld-text-bank-actions">
        <Btn full size="large" onClick={reviewing ? onConnect : () => setReviewing(true)}>{reviewing ? copy.continueLabel : "Connect iMessage"}</Btn>
        <button className="press ld-text-skip" onClick={onSkip}>Not now</button>
      </div>
    </section>
  );
};
window.ConnectImessage = ConnectImessage;
