// Animated Telegram-style chat — messages stream in on a loop, with typing dots.
const { useEffect: useEffectChat, useState: useStateChat, useRef: useRefChat } = React;

const SCRIPT = [
  { from: 'me',  text: 'brief me on today', delay: 800 },
  { from: 'bot', typing: 1200, text: '**Good morning, Max.**\n\n3 drafts ready · 1 meeting at 14:00 with Helen Ng · Horizon grant due in 12 days', delay: 2400 },
  { from: 'me',  text: 'show me the helen one', delay: 1000 },
  { from: 'bot', typing: 1400, text: '*Drafted reply, ready to send:*\n\n"Friday works — I\'ve held 14:00 BST on your calendar. I\'ll bring the Meadow runtime one-pager and a short demo. Anything specific you\'d like covered?"', delay: 3000 },
  { from: 'me',  text: 'send it', delay: 800 },
  { from: 'bot', typing: 900, text: '✓ Sent to helen.ng@tate.org.uk · slot held on your calendar', delay: 2400 },
  { from: 'me',  text: 'any new grants worth a look?', delay: 1100 },
  { from: 'bot', typing: 1500, text: '*Horizon Europe CCI-2026-04* — fit 0.71, deadline 12 Jun, needs a consortium.\n\nWant me to draft an outline against your previous Tate proposal?', delay: 3000 },
];

const renderBubble = (t) => {
  // very light markdown: **bold**, *italic*, line breaks
  const parts = t.split(/(\*\*[^*]+\*\*|\*[^*]+\*)/g);
  return parts.map((p, i) => {
    if (p.startsWith('**')) return <b key={i}>{p.slice(2,-2)}</b>;
    if (p.startsWith('*'))  return <em key={i} style={{ opacity: 0.75 }}>{p.slice(1,-1)}</em>;
    return <span key={i}>{p.split('\n').map((line, j, arr) => (
      <React.Fragment key={j}>{line}{j < arr.length - 1 && <br/>}</React.Fragment>
    ))}</span>;
  });
};

const ChatAnimation = () => {
  const [visible, setVisible] = useStateChat([]);
  const [typing, setTyping] = useStateChat(false);
  const scrollRef = useRefChat(null);

  useEffectChat(() => {
    let cancelled = false;
    let timers = [];

    const run = async () => {
      while (!cancelled) {
        setVisible([]);
        setTyping(false);
        await new Promise(r => timers.push(setTimeout(r, 600)));

        for (let i = 0; i < SCRIPT.length; i++) {
          if (cancelled) return;
          const msg = SCRIPT[i];
          if (msg.from === 'bot' && msg.typing) {
            setTyping(true);
            await new Promise(r => timers.push(setTimeout(r, msg.typing)));
            if (cancelled) return;
            setTyping(false);
          }
          setVisible(v => [...v, msg]);
          await new Promise(r => timers.push(setTimeout(r, msg.delay)));
        }

        // pause at end before looping
        await new Promise(r => timers.push(setTimeout(r, 3500)));
      }
    };
    run();

    return () => { cancelled = true; timers.forEach(clearTimeout); };
  }, []);

  useEffectChat(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [visible, typing]);

  return (
    <div style={{
      width: '100%',
      maxWidth: 360,
      background: '#fff',
      border: '1px solid rgba(0,0,0,0.08)',
      borderRadius: 32,
      padding: 8,
      boxShadow: '0 30px 80px -20px rgba(0,0,0,0.18), 0 10px 30px -10px rgba(0,0,0,0.08)',
    }}>
      {/* phone-y top */}
      <div style={{ height: 24, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <div style={{ width: 80, height: 5, background: '#e5e5e7', borderRadius: 999 }}></div>
      </div>
      {/* chat header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 14px 12px', borderBottom: '1px solid rgba(0,0,0,0.06)' }}>
        <img src={window.__resources ? window.__resources.markSvg : "mark.svg"} style={{ width: 28, height: 28 }} alt="" />
        <div>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#1d1d1f' }}>exoteam</div>
          <div style={{ fontSize: 11, color: '#34c759' }}>● online · running locally</div>
        </div>
      </div>
      <div ref={scrollRef} style={{
        height: 460, overflowY: 'auto',
        padding: '14px 12px',
        display: 'flex', flexDirection: 'column', gap: 8,
        scrollBehavior: 'smooth',
      }}>
        {visible.map((m, i) => (
          <div key={i} style={{
            alignSelf: m.from === 'me' ? 'flex-end' : 'flex-start',
            maxWidth: '82%',
            padding: '9px 13px',
            borderRadius: 18,
            borderBottomRightRadius: m.from === 'me' ? 6 : 18,
            borderBottomLeftRadius: m.from === 'bot' ? 6 : 18,
            background: m.from === 'me' ? '#007aff' : '#f2f2f7',
            color: m.from === 'me' ? '#fff' : '#1d1d1f',
            fontSize: 14, lineHeight: 1.42,
            animation: 'chatPop 0.32s cubic-bezier(0.32, 0.72, 0, 1)',
          }}>{renderBubble(m.text)}</div>
        ))}
        {typing && (
          <div style={{
            alignSelf: 'flex-start', padding: '11px 15px',
            borderRadius: 18, borderBottomLeftRadius: 6,
            background: '#f2f2f7',
            display: 'flex', gap: 4, alignItems: 'center',
            animation: 'chatPop 0.2s ease',
          }}>
            <span className="td td1"></span>
            <span className="td td2"></span>
            <span className="td td3"></span>
          </div>
        )}
      </div>
      <style>{`
        @keyframes chatPop { from { transform: scale(0.9) translateY(6px); opacity: 0; } to { transform: scale(1) translateY(0); opacity: 1; } }
        @keyframes tdblink { 0%, 60%, 100% { opacity: 0.3; } 30% { opacity: 1; } }
        .td { width: 7px; height: 7px; border-radius: 50%; background: #86868b; animation: tdblink 1.3s infinite; }
        .td2 { animation-delay: 0.18s; }
        .td3 { animation-delay: 0.36s; }
      `}</style>
    </div>
  );
};

window.ChatAnimation = ChatAnimation;
