// Hero chat — scripted demo that types out ONE illustrative exchange.
// Not wired to Claude (that's in LiveDemo). Just sets expectation.
const { useState, useEffect, useRef } = React;

function HeroChat() {
  const [msgs, setMsgs] = useState([]);
  const [typing, setTyping] = useState(false);
  const scrollRef = useRef(null);

  const script = [
    { role: 'user', text: '¿Cuánto sale el m² acá comparado con la zona?' },
    {
      role: 'ai',
      text: 'Este lote está a US$ 121/m². La media de Surubi\'í en los últimos 6 meses es US$ 134/m², así que está un 10% por debajo de mercado.',
      sources: ['Índice Lote · Luque', '32 comparables']
    },
    { role: 'user', text: '¿Qué puedo construir?' },
    {
      role: 'ai',
      text: 'Zonificación R2: casa unifamiliar hasta 3 plantas, retiro frontal 3m. La municipalidad aprobó 14 proyectos similares en la manzana durante 2025.',
      sources: ['Municipalidad de Luque', 'R2 · resolución 214/23']
    }
  ];

  useEffect(() => {
    let cancelled = false;
    let i = 0;
    const run = async () => {
      while (!cancelled && i < script.length) {
        const m = script[i];
        if (m.role === 'ai') {
          setTyping(true);
          await new Promise(r => setTimeout(r, 900));
          if (cancelled) return;
          setTyping(false);
        }
        setMsgs(prev => [...prev, m]);
        i++;
        await new Promise(r => setTimeout(r, m.role === 'user' ? 900 : 1800));
      }
    };
    const t = setTimeout(run, 600);
    return () => { cancelled = true; clearTimeout(t); };
  }, []);

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

  return (
    <div ref={scrollRef} style={{ maxHeight: 280, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 10 }}>
      {msgs.map((m, idx) => (
        <div key={idx} className={`bubble ${m.role}`}>
          {m.role === 'ai' && (
            <div className="meta"><span className="dot"></span>Lote · IA</div>
          )}
          <div>{m.text}</div>
          {m.sources && (
            <div className="source">
              {m.sources.map((s, i) => <span key={i} className="chip">{s}</span>)}
            </div>
          )}
        </div>
      ))}
      {typing && (
        <div className="bubble ai">
          <div className="meta"><span className="dot"></span>Lote · IA</div>
          <div className="typing"><span></span><span></span><span></span></div>
        </div>
      )}
    </div>
  );
}

window.HeroChat = HeroChat;
