/* WhatsAppSim.jsx — conversa multimodal animada dentro do celular.
   Mostra o agente entendendo texto, áudio, imagem e documento. */
const WhatsAppSim = () => {
  const script = [
    { from: 'agent', type: 'text', text: 'Olá! Seja bem-vindo à Agência AR. Como posso ajudar a sua empresa hoje?' },
    { from: 'user',  type: 'audio', dur: '0:09' },
    { from: 'agent', type: 'text', proc: 'audio', procLabel: 'ouvindo áudio', text: 'Entendi seu áudio: você quer automatizar o atendimento da sua loja. Posso cuidar disso para você.' },
    { from: 'user',  type: 'image', caption: 'foto-produto.jpg' },
    { from: 'agent', type: 'text', proc: 'image', procLabel: 'analisando imagem', text: 'Recebi a foto do produto. Já consigo tirar dúvidas sobre ele e indicar para os clientes certos.' },
    { from: 'user',  type: 'doc', file: 'tabela-precos.pdf', size: '240 KB' },
    { from: 'agent', type: 'text', proc: 'doc', procLabel: 'lendo documento', text: 'Li sua tabela de preços. A partir dela, gero orçamentos na hora durante a conversa.' },
    { from: 'agent', type: 'text', text: 'Atendo por texto, áudio, imagem e documento — em qualquer canal, 24 horas por dia.' },
  ];

  const [shown, setShown] = React.useState(0);     // messages visible
  const [typing, setTyping] = React.useState(false);
  const [typeLabel, setTypeLabel] = React.useState(null);
  const [started, setStarted] = React.useState(false);
  const rootRef = React.useRef(null);
  const phoneRef = React.useRef(null);
  const feedRef = React.useRef(null);
  const timers = React.useRef([]);

  // Start when the phone scrolls into view (scroll-based — robusto neste runtime)
  React.useEffect(() => {
    let done = false;
    const check = () => {
      if (done) return;
      const el = phoneRef.current || rootRef.current;
      if (!el) return;
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight * 0.85 && r.bottom > 0) {
        done = true; setStarted(true);
        window.removeEventListener('scroll', check);
      }
    };
    check();
    window.addEventListener('scroll', check, { passive: true });
    const t = setTimeout(check, 400);
    return () => { window.removeEventListener('scroll', check); clearTimeout(t); };
  }, []);

  React.useEffect(() => {
    if (!started) return;

    const run = () => {
      timers.current.forEach(clearTimeout);
      timers.current = [];
      setShown(0); setTyping(false); setTypeLabel(null);
      let t = 600;
      script.forEach((m, i) => {
        if (m.from === 'agent') {
          timers.current.push(setTimeout(() => { setTyping(true); setTypeLabel(m.procLabel ? { kind: m.proc, label: m.procLabel } : null); }, t));
          t += m.proc ? 1500 : 1150;
          timers.current.push(setTimeout(() => { setTyping(false); setTypeLabel(null); setShown(i + 1); }, t));
          t += 650;
        } else {
          // user messages: media gets a touch more dwell time
          timers.current.push(setTimeout(() => setShown(i + 1), t));
          t += (m.type === 'text' ? 1000 : 1350);
        }
      });
      timers.current.push(setTimeout(run, t + 4600));
    };
    run();
    return () => timers.current.forEach(clearTimeout);
  }, [started]);

  React.useEffect(() => {
    if (feedRef.current) feedRef.current.scrollTop = feedRef.current.scrollHeight;
    window.lucide && window.lucide.createIcons();
  }, [shown, typing, typeLabel]);

  return (
    <section ref={rootRef} style={{ background: 'var(--ar-bg-main)', padding: '116px 0', overflow: 'hidden' }}>
      <Container className="grid-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'center' }}>
        {/* Copy */}
        <div>
          <SectionHead
            eyebrow="ATENDIMENTO COM IA"
            title={<>Conversas que <GradText>qualificam e convertem</GradText>, 24 horas por dia</>}
            sub="O agente entende a intenção do cliente, responde com o contexto do seu negócio e encaminha as oportunidades certas para a equipe — em qualquer canal."
          />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 30 }}>
            {[
              ['message-square', 'Respostas naturais', 'Entende perguntas em linguagem real, sem menus engessados.'],
              ['mic', 'Entende áudio, imagem e PDF', 'Multimodal: ouve áudios, lê imagens e documentos enviados pelo cliente.'],
              ['filter', 'Qualificação de leads', 'Separa curiosos de oportunidades e prioriza quem está pronto.'],
              ['share-2', 'Multicanal', 'A mesma inteligência no WhatsApp, Instagram, site e CRM.'],
            ].map(([ic, t, d], i) => (
              <Reveal key={t} delay={i * 80}>
                <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                  <div style={{ width: 40, height: 40, borderRadius: 11, flexShrink: 0, background: 'rgba(0,212,255,0.10)', border: '1px solid rgba(0,212,255,0.30)', color: '#00D4FF', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <i data-lucide={ic} style={{ width: 18, height: 18 }}></i>
                  </div>
                  <div>
                    <div style={{ fontFamily: 'var(--ar-font-title)', fontWeight: 600, fontSize: 16, color: 'var(--ar-text-main)' }}>{t}</div>
                    <div style={{ fontFamily: 'var(--ar-font-body)', fontSize: 14, color: 'var(--ar-text-muted)', marginTop: 2, lineHeight: 1.5 }}>{d}</div>
                  </div>
                </div>
              </Reveal>
            ))}
          </div>
        </div>

        {/* Phone */}
        <Reveal delay={120} style={{ display: 'flex', justifyContent: 'center' }}>
          <div ref={phoneRef} style={{ position: 'relative' }}>
            <div style={{ position: 'absolute', inset: -50, background: 'radial-gradient(circle at 50% 40%, rgba(0,94,255,0.30), transparent 65%)', filter: 'blur(24px)', pointerEvents: 'none' }} />
            <Phone>
              {/* chat header */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '42px 14px 12px', background: 'linear-gradient(135deg, rgba(0,94,255,0.34), rgba(0,212,255,0.18))', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
                <div style={{ width: 36, height: 36, borderRadius: 999, background: 'linear-gradient(135deg,#005EFF,#00D4FF)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', boxShadow: '0 0 14px rgba(0,212,255,0.5)' }}>
                  <i data-lucide="bot" style={{ width: 18, height: 18 }}></i>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'var(--ar-font-title)', fontWeight: 700, fontSize: 14, color: '#fff' }}>Agente AR</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontFamily: 'var(--ar-font-body)', fontSize: 11, color: '#1FD17B' }}>
                    <span className="ar-pulse" style={{ width: 6, height: 6, borderRadius: 999, background: '#1FD17B' }} />online
                  </div>
                </div>
                <i data-lucide="more-vertical" style={{ width: 18, height: 18, color: 'rgba(255,255,255,0.6)' }}></i>
              </div>

              {/* feed */}
              <div ref={feedRef} style={{
                flex: 1, overflowY: 'auto', padding: '16px 12px', display: 'flex', flexDirection: 'column', gap: 8,
                background: 'linear-gradient(180deg, #0B1020, #05070D)',
                backgroundImage: 'radial-gradient(rgba(255,255,255,0.025) 1px, transparent 1px)', backgroundSize: '16px 16px',
              }}>
                {script.slice(0, shown).map((m, i) => <Bubble key={i} m={m} />)}
                {typing && <TypingBubble info={typeLabel} />}
              </div>

              {/* input */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', borderTop: '1px solid rgba(255,255,255,0.08)', background: '#05070D' }}>
                <i data-lucide="paperclip" style={{ width: 18, height: 18, color: 'var(--ar-text-dim)', flexShrink: 0 }}></i>
                <div style={{ flex: 1, background: 'var(--ar-bg-card)', border: '1px solid rgba(255,255,255,0.10)', borderRadius: 999, padding: '9px 14px', fontFamily: 'var(--ar-font-body)', fontSize: 12.5, color: 'var(--ar-text-dim)' }}>Escreva uma mensagem…</div>
                <div style={{ width: 36, height: 36, borderRadius: 999, background: 'linear-gradient(135deg,#005EFF,#00D4FF)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', flexShrink: 0 }}>
                  <i data-lucide="send" style={{ width: 16, height: 16 }}></i>
                </div>
              </div>
            </Phone>
          </div>
        </Reveal>
      </Container>

      <style>{`
        .ar-typ { display: inline-block; animation: arTyp 1s var(--ar-ease) infinite; }
        @keyframes arTyp { 0%,60%,100% { opacity:0.3; transform: translateY(0);} 30% { opacity:1; transform: translateY(-3px);} }
        .ar-pulse { animation: arPulse 1.7s var(--ar-ease) infinite; }
        @keyframes arPulse { 0%,100%{ box-shadow:0 0 0 0 rgba(31,209,123,0.5);} 50%{ box-shadow:0 0 0 5px rgba(31,209,123,0);} }
        .wa-eq { transform-origin: bottom; animation: waEq 1s ease-in-out infinite; }
        @keyframes waEq { 0%,100%{ transform: scaleY(0.4);} 50%{ transform: scaleY(1);} }
        @media (prefers-reduced-motion: reduce) { .ar-typ,.ar-pulse,.wa-eq { animation:none !important; } }
      `}</style>
    </section>
  );
};

/* ---- typing indicator (contextual: ouvindo áudio / analisando imagem / lendo documento) ---- */
const TypingBubble = ({ info }) => {
  const icon = info ? ({ audio: 'audio-lines', image: 'scan-eye', doc: 'file-search' }[info.kind] || 'sparkles') : null;
  return (
    <div className="wa-in" style={{
      alignSelf: 'flex-end', background: 'linear-gradient(135deg,#005EFF,#00D4FF)',
      borderRadius: '14px 14px 4px 14px', padding: info ? '9px 13px' : '12px 14px',
      display: 'flex', alignItems: 'center', gap: 8, boxShadow: '0 6px 18px rgba(0,94,255,0.3)',
    }}>
      {info && <i data-lucide={icon} style={{ width: 14, height: 14, color: '#fff' }}></i>}
      {info && <span style={{ fontFamily: 'var(--ar-font-body)', fontSize: 11.5, fontWeight: 500, color: '#fff' }}>{info.label}</span>}
      <span style={{ display: 'flex', gap: 4 }}>
        {[0, 1, 2].map(d => <span key={d} className="ar-typ" style={{ width: 6, height: 6, borderRadius: 999, background: '#fff', animationDelay: `${d * 0.16}s` }} />)}
      </span>
    </div>
  );
};

/* ---- message bubble (text / audio / image / doc) ---- */
const Bubble = ({ m }) => {
  const agent = m.from === 'agent';
  const base = {
    alignSelf: agent ? 'flex-end' : 'flex-start', maxWidth: '82%',
    background: agent ? 'linear-gradient(135deg,#005EFF,#00D4FF)' : 'var(--ar-bg-card)',
    border: agent ? 'none' : '1px solid rgba(255,255,255,0.08)',
    color: agent ? '#fff' : 'var(--ar-text-main)',
    borderRadius: agent ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
    boxShadow: agent ? '0 6px 18px rgba(0,94,255,0.3)' : 'none',
  };

  let inner;
  if (m.type === 'audio') {
    const bars = [5, 9, 14, 8, 12, 16, 7, 11, 15, 6, 10, 13, 8, 5, 9, 12, 7];
    inner = (
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '9px 12px' }}>
        <div style={{ width: 28, height: 28, borderRadius: 999, flexShrink: 0, background: 'rgba(0,212,255,0.16)', border: '1px solid rgba(0,212,255,0.4)', color: '#00D4FF', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <i data-lucide="play" style={{ width: 13, height: 13 }}></i>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 2.5, height: 22 }}>
          {bars.map((h, i) => <span key={i} className="wa-eq" style={{ width: 2.5, height: h, borderRadius: 999, background: i < 6 ? '#00D4FF' : 'rgba(255,255,255,0.28)', animationDelay: `${i * 0.07}s` }} />)}
        </div>
        <span style={{ fontFamily: 'var(--ar-font-body)', fontSize: 11, color: 'var(--ar-text-dim)', flexShrink: 0 }}>{m.dur}</span>
      </div>
    );
  } else if (m.type === 'image') {
    inner = (
      <div style={{ padding: 5 }}>
        <div style={{ width: 188, height: 116, borderRadius: 10, position: 'relative', overflow: 'hidden', background: 'linear-gradient(135deg, #14223f 0%, #0b1830 60%, #102a4a 100%)', border: '1px solid rgba(255,255,255,0.08)' }}>
          {/* stylized product scene */}
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 32% 38%, rgba(0,212,255,0.32), transparent 55%), radial-gradient(circle at 72% 72%, rgba(0,94,255,0.32), transparent 55%)' }} />
          <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 34, background: 'linear-gradient(180deg, transparent, rgba(5,7,13,0.7))' }} />
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(255,255,255,0.5)' }}>
            <i data-lucide="image" style={{ width: 30, height: 30 }}></i>
          </div>
          <div style={{ position: 'absolute', left: 8, bottom: 7, display: 'flex', alignItems: 'center', gap: 5, fontFamily: 'var(--ar-font-body)', fontSize: 10.5, color: 'rgba(255,255,255,0.85)' }}>
            <i data-lucide="paperclip" style={{ width: 11, height: 11 }}></i>{m.caption}
          </div>
        </div>
      </div>
    );
  } else if (m.type === 'doc') {
    inner = (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 13px' }}>
        <div style={{ width: 36, height: 36, borderRadius: 9, flexShrink: 0, background: 'rgba(255,77,94,0.14)', border: '1px solid rgba(255,77,94,0.34)', color: '#FF6B7A', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <i data-lucide="file-text" style={{ width: 18, height: 18 }}></i>
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--ar-font-body)', fontSize: 12.5, fontWeight: 600, color: 'var(--ar-text-main)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.file}</div>
          <div style={{ fontFamily: 'var(--ar-font-body)', fontSize: 10.5, color: 'var(--ar-text-dim)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ fontWeight: 600, color: '#FF6B7A' }}>PDF</span> · {m.size}
          </div>
        </div>
      </div>
    );
  } else {
    inner = <div style={{ padding: '10px 13px', fontFamily: 'var(--ar-font-body)', fontSize: 13, lineHeight: 1.45 }}>{m.text}</div>;
  }

  return (
    <div className="wa-in" style={base}>
      {inner}
      <style>{`.wa-in{ animation: waIn 320ms var(--ar-ease) both; } @keyframes waIn { from { opacity:0; transform: translateY(8px) scale(0.97);} to { opacity:1; transform:none;} }`}</style>
    </div>
  );
};

const Phone = ({ children }) => (
  <div className="wa-phone" style={{
    position: 'relative', width: 300, height: 600, borderRadius: 44, padding: 11,
    background: 'linear-gradient(160deg, #1a2238, #05070d)',
    border: '1px solid rgba(255,255,255,0.12)',
    boxShadow: '0 50px 110px -30px rgba(0,0,0,0.85), 0 0 0 1px rgba(0,212,255,0.12), inset 0 0 0 2px rgba(255,255,255,0.04)',
  }}>
    <div style={{ position: 'absolute', top: 13, left: '50%', transform: 'translateX(-50%)', width: 82, height: 18, background: '#05070d', borderRadius: 999, zIndex: 3 }} />
    <div style={{ width: '100%', height: '100%', borderRadius: 34, overflow: 'hidden', display: 'flex', flexDirection: 'column', background: '#05070D' }}>
      {children}
    </div>
  </div>
);

window.WhatsAppSim = WhatsAppSim;
