const Demo = () => {
  const SCRIPT = [
    { who:"user", text:"Oi, vocês têm horário pra limpeza de pele amanhã?" },
    { who:"aria", text:"Oi! 😊 Temos sim. Amanhã consigo às 14h, 16h ou 18h. Qual fica melhor pra você?" },
    { who:"user", text:"16h tá ótimo" },
    { who:"aria", text:"Perfeito! Vou reservar amanhã às 16h. Pode me confirmar seu nome, por favor?" },
    { who:"user", text:"Marina Alves" },
    { who:"aria", text:"Prontinho, Marina! ✅ Agendado para amanhã às 16h. Vou te mandar um lembrete 2h antes. Algo mais que eu possa ajudar?" },
  ];
  const SUGGESTIONS = ["Quais procedimentos vocês fazem?", "Onde fica a clínica?", "Tem horário hoje?"];

  const [shown, setShown] = React.useState(0);
  const [typing, setTyping] = React.useState(false);
  const [extra, setExtra] = React.useState([]);
  const scrollRef = React.useRef(null);
  const started = React.useRef(false);

  // auto-play when section visible
  React.useEffect(() => {
    const sec = document.getElementById("demo");
    if (!sec) return;
    const io = new IntersectionObserver((es)=>{
      es.forEach(e=>{ if(e.isIntersecting && !started.current){ started.current = true; runScript(); } });
    }, { threshold:0.4 });
    io.observe(sec);
    return ()=>io.disconnect();
  }, []);

  const runScript = () => {
    let i = 0;
    const next = () => {
      if (i >= SCRIPT.length) return;
      const msg = SCRIPT[i];
      if (msg.who === "aria") {
        setTyping(true);
        setTimeout(() => { setTyping(false); setShown(s=>s+1); i++; setTimeout(next, 700); }, 1100);
      } else {
        setShown(s=>s+1); i++; setTimeout(next, 900);
      }
    };
    next();
  };

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

  const ANSWERS = {
    "Quais procedimentos vocês fazem?":"Fazemos limpeza de pele, peeling, drenagem e protocolos faciais! Quer que eu te passe a lista completa? 💆",
    "Onde fica a clínica?":"Estamos na Av. Paulista, 1000 — pertinho do metrô. Te envio a localização no mapa? 📍",
    "Tem horário hoje?":"Deixa eu ver… hoje ainda tenho 19h disponível! Quer que eu reserve pra você? ⏰",
  };
  const ask = (q) => {
    setExtra(prev => [...prev, { who:"user", text:q }]);
    setTyping(true);
    setTimeout(() => { setTyping(false); setExtra(prev => [...prev, { who:"aria", text: ANSWERS[q] }]); }, 1100);
  };

  const allMsgs = [...SCRIPT.slice(0, shown), ...extra];

  return (
    <section id="demo" className="section-pad" style={{borderTop:"1px solid var(--line)", background:"var(--bg-2)", overflow:"hidden"}}>
      <div className="wrap">
        <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:56, alignItems:"center"}} className="demo-grid">
          {/* left copy + video placeholder */}
          <div>
            <span className="eyebrow" data-reveal>Demonstração</span>
            <h2 data-reveal data-reveal-delay="1" style={{fontSize:"clamp(34px,3.8vw,52px)", margin:"20px 0 0"}}>
              Veja a Aura<br/><span className="grad-text">atendendo de verdade.</span>
            </h2>
            <p data-reveal data-reveal-delay="2" style={{color:"var(--ink-dim)", fontSize:17, margin:"20px 0 0", maxWidth:440}}>
              Esta é uma conversa real, do jeito que sua paciente veria. Toque em uma pergunta e veja a resposta na hora.
            </p>

            <div data-reveal data-reveal-delay="3" style={{display:"flex", gap:10, flexWrap:"wrap", marginTop:26}}>
              {SUGGESTIONS.map(s=>(
                <button key={s} onClick={()=>ask(s)} className="btn btn-ghost" style={{padding:"11px 16px", fontSize:13.5}}>{s}</button>
              ))}
            </div>

            <div data-reveal data-reveal-delay="4" style={{display:"flex", gap:10, flexWrap:"wrap", marginTop:24}}>
              {[["brain","Entende"],["calendar","Agenda"],["check","Confirma"]].map(([ic,l])=>(
                <span key={l} style={{display:"inline-flex", alignItems:"center", gap:7, fontSize:12.5, color:"var(--ink-dim)", padding:"7px 12px", borderRadius:999, border:"1px solid var(--glass-border)", background:"var(--surface)"}}>
                  <Icon name={ic} size={14} stroke="var(--accent)"/>{l}
                </span>
              ))}
            </div>
          </div>

          {/* phone chat */}
          <div data-reveal data-reveal-delay="2" style={{display:"flex", justifyContent:"center"}}>
            <div style={{width:330, maxWidth:"100%", borderRadius:42, background:"#070A0B", border:"1px solid var(--glass-border)", padding:11, position:"relative",
              boxShadow:"0 50px 110px -50px rgba(0,0,0,.9), 0 0 0 1px rgba(255,255,255,.04)"}}>
              <span aria-hidden style={{position:"absolute", inset:-14, borderRadius:54, border:"1px solid rgba(0,206,201,.25)", animation:"ringpulse 2.6s ease-out infinite", pointerEvents:"none"}}/>
              <div style={{borderRadius:32, overflow:"hidden", background:"var(--bg-2)", height:600, display:"flex", flexDirection:"column"}}>
                {/* chat header */}
                <div style={{padding:"16px 18px", display:"flex", alignItems:"center", gap:12, borderBottom:"1px solid var(--line)", background:"rgba(255,255,255,.02)"}}>
                  <span style={{width:42, height:42, borderRadius:"50%", background:"linear-gradient(135deg, var(--primary), var(--accent))", display:"flex", alignItems:"center", justifyContent:"center"}}>
                    <Icon name="logo" size={24}/>
                  </span>
                  <div style={{flex:1}}>
                    <div style={{fontSize:15, fontWeight:700}}>Aura</div>
                    <div style={{fontSize:11.5, color:"var(--accent)", display:"flex", alignItems:"center", gap:5}}>
                      <span style={{width:6, height:6, borderRadius:"50%", background:"var(--accent)", boxShadow:"0 0 0 3px rgba(0,206,201,.2)", animation:"livepulse 1.6s ease-in-out infinite"}}/>online agora · respondendo em tempo real
                    </div>
                  </div>
                  <Icon name="phone" size={18} stroke="var(--ink-mute)"/>
                </div>

                {/* messages */}
                <div ref={scrollRef} data-native-scroll style={{flex:1, overflowY:"auto", padding:"18px 16px", display:"flex", flexDirection:"column", gap:10}}>
                  {allMsgs.map((m,i)=><Bubble key={i} who={m.who} text={m.text}/>)}
                  {typing && <Typing/>}
                </div>

                {/* input */}
                <div style={{padding:"12px 14px", borderTop:"1px solid var(--line)", display:"flex", alignItems:"center", gap:10}}>
                  <div style={{flex:1, padding:"11px 16px", borderRadius:999, background:"var(--surface-2)", color:"var(--ink-mute)", fontSize:13.5}}>Escreva uma mensagem…</div>
                  <span style={{width:40, height:40, borderRadius:"50%", background:"var(--primary)", display:"flex", alignItems:"center", justifyContent:"center", color:"#fff"}}>
                    <Icon name="arrow" size={18}/>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <style>{`@media (max-width: 920px){ .demo-grid{ grid-template-columns:1fr !important; gap:40px !important;} }`}</style>
      <LiveStyles/>
    </section>
  );
};

const Bubble = ({ who, text }) => {
  const isAria = who === "aria";
  return (
    <div style={{display:"flex", justifyContent: isAria?"flex-start":"flex-end", animation:"pop .3s cubic-bezier(.2,.8,.2,1)"}}>
      <div style={{maxWidth:"82%", padding:"11px 15px", fontSize:14, lineHeight:1.45,
        borderRadius:18, borderBottomLeftRadius: isAria?5:18, borderBottomRightRadius: isAria?18:5,
        background: isAria ? "var(--surface-2)" : "linear-gradient(180deg,#FF8757,#FF6B35)",
        color: isAria ? "var(--ink)" : "#fff",
        border: isAria ? "1px solid var(--glass-border)" : "none"}}>
        {text}
      </div>
      <style>{`@keyframes pop{from{opacity:0;transform:translateY(8px) scale(.96)}to{opacity:1;transform:none}}`}</style>
    </div>
  );
};

const LiveStyles = () => (<style>{`@keyframes livepulse{0%,100%{opacity:1}50%{opacity:.35}}@keyframes ringpulse{0%{opacity:.5;transform:scale(.98)}100%{opacity:0;transform:scale(1.04)}}`}</style>);
const Typing = () => (
  <div style={{display:"flex", justifyContent:"flex-start"}}>
    <div style={{padding:"13px 17px", borderRadius:18, borderBottomLeftRadius:5, background:"var(--surface-2)", border:"1px solid var(--glass-border)", display:"flex", gap:5}}>
      {[0,1,2].map(i=>(
        <span key={i} style={{width:7, height:7, borderRadius:"50%", background:"var(--ink-mute)", animation:`td 1.2s ${i*0.18}s infinite`}}/>
      ))}
    </div>
    <style>{`@keyframes td{0%,60%,100%{opacity:.3;transform:translateY(0)}30%{opacity:1;transform:translateY(-4px)}}`}</style>
  </div>
);

window.Demo = Demo;
