/* CLONEAI — Landing "Em operação" demo: animated agent chat (Telegram skin) */
const { useState, useEffect, useRef } = React;
const { IOSDevice } = window;

const check = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4"><path d="m5 12 4.5 4.5L19 7"/></svg>';
const checks = (
  <svg className="checks" viewBox="0 0 16 11" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
    <path d="M1 6 4 9 9.3 2.4"/><path d="M7 8.6 7.5 9 12.8 2.4"/>
  </svg>
);

// — internal-support scenarios (PT-BR): the agent supports the OWNER and the TEAM —
const VERTS = [
  { id:'dono', label:'Dono · Pequena empresa',
    tag:'Te entrega o negócio pronto toda manhã — e age sozinho.',
    out:'06:30 · proativo', when:'Hoje', clock:'06:30',
    msgs:[
      {f:'a', t:'Bom dia, Marina. Antecipei o fechamento da semana enquanto você dormia.', d:1400},
      {f:'a', t:'Receita R$ 142.300 (+12%). Risco: duas contas grandes vencem antes da folha — o caixa fica negativo no dia 14.', d:1700},
      {f:'u', t:'Como resolvemos?', d:850},
      {f:'a', t:'Montei 3 cenários. O melhor: antecipar o recebível da Aurora (custo 1,8%) cobre o buraco e ainda sobram R$ 22 mil.', d:1700},
      {f:'u', t:'Pode fazer.', d:750},
      {f:'a', t:'Solicitado. Te aviso assim que a Aurora confirmar.', d:1200},
      {f:'tool', t:'Antecipação solicitada · CFO avisado'}
    ]},
  { id:'comercial', label:'Time comercial', who:'Rafael · Vendas',
    tag:'Prepara o vendedor antes da reunião, com dados do CRM.',
    out:'briefing em 15s', when:'Hoje', clock:'14:45',
    msgs:[
      {f:'u', t:'Tenho call com a Aurora às 15h. Me passa o resumo?'},
      {f:'a', t:'Aurora Log — cliente há 2 anos, R$ 38k/mês. Atenção: 2 chamados abertos e o NPS caiu pra 6.', d:1500},
      {f:'a', t:'Sugestão: leve o upgrade do plano + um desconto de retenção. Já deixei o briefing e a proposta no seu e-mail.', d:1700},
      {f:'u', t:'Mandou bem. E a margem?', d:900},
      {f:'a', t:'Tabela anexada com a margem mínima destacada — você negocia sem risco de furar o piso.', d:1400},
      {f:'tool', t:'Briefing + proposta enviados · CRM atualizado'}
    ]},
  { id:'operacoes', label:'Time de operações', who:'Lia · Operações',
    tag:'Resolve a rotina da equipe e só pede o seu "ok".',
    out:'rotina resolvida', when:'Hoje', clock:'07:20',
    msgs:[
      {f:'u', t:'Fecha a escala da semana que vem?'},
      {f:'a', t:'Fechei. Cobri os 3 turnos; só faltou sábado à noite — o João pediu folga.', d:1500},
      {f:'a', t:'Sugiro chamar a Carla: topou cobrir e está dentro do limite de horas. Confirmo com ela?', d:1700},
      {f:'u', t:'Confirma.', d:750},
      {f:'a', t:'Feito. Escala publicada e equipe avisada no grupo.', d:1300},
      {f:'tool', t:'Escala publicada · Carla confirmada · equipe notificada'}
    ]}
];

function Chat({ vert, count, typing }){
  const bodyRef = useRef(null);
  useEffect(()=>{ const el=bodyRef.current; if(el) el.scrollTop=el.scrollHeight; },[count,typing]);
  const shown = vert.msgs.slice(0,count);
  return (
    <div className="chat">
      <div className="chat__hdr">
        <svg className="chat__back" viewBox="0 0 12 20" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 2 2 10l8 8"/></svg>
        <div className="chat__ava"><img src="assets/icon_blue.png" alt=""/></div>
        <div className="chat__id">
          <b>Atlas · Agente CLONEAI</b>
          <span>bot · sempre ativo</span>
        </div>
        <svg className="chat__menu" viewBox="0 0 5 19" fill="currentColor"><circle cx="2.5" cy="2.5" r="2"/><circle cx="2.5" cy="9.5" r="2"/><circle cx="2.5" cy="16.5" r="2"/></svg>
      </div>
      <div className="chat__body" ref={bodyRef}>
        <div className="chat__when">{vert.when}</div>
        {shown.map((m,i)=>{
          if(m.f==='tool') return <div className="msg msg--tool" key={i}><span dangerouslySetInnerHTML={{__html:check}}/> {m.t}</div>;
          const isU = m.f==='u';
          return (
            <div className={'msg msg--'+(isU?'user':'agent')} key={i}>
              {m.t}
              <span className="msg__meta">{vert.clock}{isU && checks}</span>
            </div>
          );
        })}
        {typing && <div className="typing"><i></i><i></i><i></i></div>}
      </div>
      <div className="chat__input">
        <svg className="chat__clip" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5 12.5 20a5 5 0 0 1-7-7l8.3-8.3a3.2 3.2 0 0 1 4.6 4.6l-8.1 8.1a1.6 1.6 0 0 1-2.3-2.3l7.4-7.4"/></svg>
        <div className="fakefield">Mensagem</div>
        <div className="chat__send"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7Z"/></svg></div>
      </div>
    </div>
  );
}

function Demo(){
  const [vi, setVi] = useState(0);
  const [count, setCount] = useState(0);
  const [typing, setTyping] = useState(false);
  const [playing, setPlaying] = useState(false);
  const timer = useRef(null);
  const vert = VERTS[vi];

  useEffect(()=>{
    const kick=setTimeout(()=>setPlaying(true), 700);
    const root=document.getElementById('demo-root');
    if(root){
      const io=new IntersectionObserver((e)=>{ if(e[0].isIntersecting){ setPlaying(true); io.disconnect(); } },{threshold:.2});
      io.observe(root); return ()=>{ clearTimeout(kick); io.disconnect(); };
    }
    return ()=>clearTimeout(kick);
  },[]);

  useEffect(()=>{
    if(!playing) return;
    clearTimeout(timer.current);
    if(count < vert.msgs.length){
      const next = vert.msgs[count];
      if(next.f==='a'){
        setTyping(true);
        timer.current=setTimeout(()=>{ setTyping(false); setCount(c=>c+1); }, next.d||1200);
      } else {
        setTyping(false);
        timer.current=setTimeout(()=>{ setCount(c=>c+1); }, next.d||700);
      }
    } else {
      timer.current=setTimeout(()=>{ setVi(v=>(v+1)%VERTS.length); setCount(0); }, 3400);
    }
    return ()=>clearTimeout(timer.current);
  },[playing,count,vi]);

  const pick=(i)=>{ if(i===vi)return; clearTimeout(timer.current); setVi(i); setCount(0); setTyping(false); setPlaying(true); };

  return (
    <React.Fragment>
      <div className="demo__intro">
        <p className="demo__framing">Um agente que <em>não dorme, não esquece</em> e responde em segundos.</p>
        <div className="vsel" role="tablist">
          {VERTS.map((v,i)=>(
            <button className="vsel__item" role="tab" aria-selected={i===vi} key={v.id} onClick={()=>pick(i)}>
              <span className="vsel__no">{String(i+1).padStart(2,'0')}</span>
              <span className="vsel__name">{v.label}</span>
              <span className="vsel__out">{v.out}</span>
              <span className="vsel__tag">{v.tag}</span>
              {i===vi && <span className="vsel__prog" key={'p'+vi}></span>}
            </button>
          ))}
        </div>
      </div>
      <div className="demo__phonewrap">
        <div className="phone-box">
          <IOSDevice dark>
            <Chat vert={vert} count={count} typing={typing}/>
          </IOSDevice>
        </div>
      </div>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('demo-root')).render(<Demo/>);
