/* global React, Reveal, Icon, Wordmark */
const { useState: useChat, useRef: useRefChat, useEffect: useEffChat } = React;

// ════════════════════════════════════════════════════════════
//  ATENDIMENTO — Adriana: qualificação guiada que vira lead no CRM
// ════════════════════════════════════════════════════════════
const ATTENDANT = {
  name: 'Adriana',
  fullName: 'Adriana Reina',
  role: 'Sócia de Processos e Operações',
  roleEn: 'Operations & Process Partner',
  bio: 'Transforma operações sobrecarregadas em negócios leves, lucrativos e sustentáveis. Na Convive, estrutura os processos que sustentam o crescimento — do diagnóstico ao acompanhamento contínuo.',
};

// ── Integração com o CRM (envio SERVER-SIDE, chave nunca no navegador) ──
// A Adriana envia o lead pro backend do PRÓPRIO site (mesma origem, sem CORS);
// o backend repassa pro endpoint do CRM com a chave Bearer (ver backend-exemplo/).
// Configure via window.CONVIVE_CRM = { endpoint, source } antes deste script, se quiser.
//   endpoint: rota same-origin do site que recebe o lead (default '/api/lead')
const CRM_CONFIG = Object.assign({
  endpoint: '/api/lead',
  source: 'site-convive/fale-conosco',
}, (typeof window !== 'undefined' && window.CONVIVE_CRM) || {});

function buildLeadPayload(slots, resumo) {
  return {
    // campos no formato esperado pelo intake da Convive
    name: slots.nome || '',
    whatsapp: slots.contato || '',
    email: slots.email || '',
    segmento: slots.segmento || '',
    dor: slots.dor || '',
    teamSize: slots.tamanho || '',
    tools: slots.ferramentas || '',
    summary: resumo || '',
    page: (typeof location !== 'undefined' ? location.href : ''),
    // extras (o backend repassa ou ignora)
    company: slots.empresa || '',
    city: slots.cidade || '',
    faturamento: slots.faturamento || '',
    source: CRM_CONFIG.source,
    created_at: new Date().toISOString(),
  };
}

async function sendToCRM(payload) {
  if (!CRM_CONFIG.endpoint) return { ok: false, demo: true };
  try {
    const res = await fetch(CRM_CONFIG.endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    let data = null;
    try { data = await res.json(); } catch (e) { /* sem corpo */ }
    return { ok: res.ok && (!data || data.ok !== false), status: res.status, leadId: data && data.leadId };
  } catch (e) { return { ok: false, error: String((e && e.message) || e) }; }
}

// Resumo de contexto do lead (pra cair pronto pro vendedor no CRM)
async function buildResumo(slots) {
  try {
    const r = await fetch('/api/resumo', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ slots }),
    });
    const data = await r.json().catch(() => ({}));
    if (r.ok && data.ok && data.text) return data.text.trim();
  } catch (e) { /* fallback */ }
  // Fallback estático se a IA falhar — vendedor ainda recebe um resumo legível
  return `${slots.segmento || 'segmento não informado'} · dor: ${slots.dor || '—'} · equipe: ${slots.tamanho || '—'} · hoje usa: ${slots.ferramentas || '—'}.`;
}

// Roteiro de qualificação (slot-filling). A Adriana sempre avança por aqui;
// a IA só dá a "casca" humana (reconhece a resposta e emenda a próxima pergunta).
const STEPS = [
  {
    id: 'segmento', label: 'Segmento',
    ask: 'Pra eu te ajudar do jeito certo — que tipo de negócio você toca hoje?',
    chips: ['Software house / agência', 'Restaurante / bar', 'Representante comercial', 'Outro tipo'],
  },
  {
    id: 'dor', label: 'Principal dor',
    ask: 'E no dia a dia, o que mais te tira o sossego?',
    chips: ['Gestão espalhada', 'Não sei minha margem real', 'Equipe perdida nas tarefas', 'Comercial bagunçado'],
  },
  {
    id: 'tamanho', label: 'Tamanho',
    ask: 'Quantas pessoas mexem nessa operação com você?',
    chips: ['Só eu / até 5', '6 a 20', 'Mais de 20'],
  },
  {
    id: 'ferramentas', label: 'Hoje usa',
    ask: 'E como você controla tudo isso hoje?',
    chips: ['Planilha e WhatsApp', 'Um sistema que não dá conta', 'Caderno / na cabeça', 'Vários sistemas soltos'],
  },
  {
    id: 'nome', label: 'Nome',
    ask: 'Já tô com um bom retrato do seu cenário 🙂 Como é o seu nome?',
    free: true, placeholder: 'Seu nome…',
  },
  {
    id: 'empresa', label: 'Empresa',
    ask: (s) => `Prazer, ${firstName(s.nome)}! Qual o nome da sua empresa?`,
    free: true, placeholder: 'Nome da empresa…',
  },
  {
    id: 'cidade', label: 'Cidade',
    ask: 'De qual cidade você fala com a gente?',
    free: true, placeholder: 'Cidade / UF…',
  },
  {
    id: 'faturamento', label: 'Faturamento',
    ask: 'Pra eu dimensionar a proposta: qual a faixa de faturamento mensal hoje?',
    chips: ['Até R$ 50 mil', 'R$ 50–200 mil', 'R$ 200 mil–1 mi', 'Acima de R$ 1 mi', 'Prefiro não dizer'],
  },
  {
    id: 'email', label: 'E-mail',
    ask: 'Quase lá! Qual o melhor e-mail pra eu te mandar o material?',
    free: true, placeholder: 'voce@empresa.com', validate: 'email',
  },
  {
    id: 'contato', label: 'WhatsApp',
    ask: (s) => `Perfeito. Por fim, me passa um WhatsApp com DDD que eu já te retorno com um caminho no seu contexto, ${firstName(s.nome)}.`,
    free: true, placeholder: '(11) 90000-0000', validate: 'phone',
  },
];

function firstName(n) { return (n || '').trim().split(/\s+/)[0] || 'tudo bem'; }
function resolveAsk(step, slots) { return typeof step.ask === 'function' ? step.ask(slots) : step.ask; }

function Atendimento() {
  const [messages, setMessages] = useChat([
    { from: 'them', text: 'Oi! Eu sou a Adriana, do time da Convive 👋' },
    { from: 'them', text: 'Vou te fazer umas perguntas rápidas pra entender sua operação — aí já te encaminho pro caminho certo. Bora?' },
    { from: 'them', text: STEPS[0].ask },
  ]);
  const [stepIndex, setStepIndex] = useChat(0);
  const [slots, setSlots] = useChat({});
  const [typing, setTyping] = useChat(false);
  const [input, setInput] = useChat('');
  const [busy, setBusy] = useChat(false);
  const [done, setDone] = useChat(false);
  const bodyRef = useRefChat(null);

  useEffChat(() => {
    const el = bodyRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages, typing]);

  const say = (text) => new Promise(res => {
    setTyping(true);
    const delay = Math.min(1500, 550 + String(text).length * 12);
    setTimeout(() => { setTyping(false); setMessages(m => [...m, { from: 'them', text }]); res(); }, delay);
  });

  // bridge humano via IA — chama o /api/chat (Anthropic Haiku 4.5 server-side)
  const humanBridge = async (step, answer, nextAsk, nextSlots, history) => {
    try {
      // Converte histórico interno (from: 'them'|'me') pro formato da Anthropic.
      // Pula assistentes iniciais (hardcoded openers) até a primeira fala do user,
      // já que a API exige primeira mensagem com role: 'user'.
      const apiMessages = [];
      let firstUserSeen = false;
      for (const m of (history || [])) {
        if (m.from !== 'them' && m.from !== 'me') continue; // pula card/leadcard
        if (!firstUserSeen && m.from === 'them') continue;  // pula opener inicial
        if (m.from === 'me') firstUserSeen = true;
        apiMessages.push({
          role: m.from === 'them' ? 'assistant' : 'user',
          content: m.text || '',
        });
      }
      if (apiMessages.length === 0) {
        apiMessages.push({ role: 'user', content: answer });
      }

      const r = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: apiMessages,
          slots: nextSlots,
          nextQuestion: nextAsk,
        }),
      });
      const data = await r.json().catch(() => ({}));
      if (r.ok && data.ok && data.text) return data.text.trim();
    } catch (e) { /* fallback */ }

    // Fallback se a IA falhar — mantém a conversa rodando sem travar
    const acks = ['Anotado.', 'Entendi.', 'Faz sentido.', 'Show.'];
    return `${acks[Math.floor(Math.random() * acks.length)]} ${nextAsk}`;
  };

  const finalize = async (filledSlots) => {
    await say(`Fechou, ${firstName(filledSlots.nome)}! Deixa eu organizar tudo aqui e registrar pra você 🙂`);
    setTyping(true);
    const resumo = await buildResumo(filledSlots);
    const payload = buildLeadPayload(filledSlots, resumo);
    const result = await sendToCRM(payload);
    setTyping(false);
    const lead = { ...filledSlots, resumo };
    setMessages(m => [...m, { from: 'card', lead, crm: result }]);
    if (result.ok) {
      await say('Prontinho — seu contato já caiu no nosso CRM e me designei pra te atender. Retorno no mesmo dia 😉');
    } else if (result.demo) {
      await say('Registrei tudo aqui e me designei pra te atender. Retorno no mesmo dia 😉');
    } else {
      await say('Anotei tudo certinho! Pra agilizar de vez, me chama direto no WhatsApp aqui embaixo 👇');
    }
    setDone(true);
  };

  const submit = async (answer) => {
    const text = String(answer).trim();
    if (!text || busy || done) return;
    const step = STEPS[stepIndex];
    setBusy(true);
    setInput('');
    const updatedMessages = [...messages, { from: 'me', text }];
    setMessages(updatedMessages);
    const nextSlots = { ...slots, [step.id]: text };
    setSlots(nextSlots);

    if (stepIndex < STEPS.length - 1) {
      const next = STEPS[stepIndex + 1];
      const bridge = await humanBridge(step, text, resolveAsk(next, nextSlots), nextSlots, updatedMessages);
      await say(bridge);
      setStepIndex(stepIndex + 1);
    } else {
      await finalize(nextSlots);
    }
    setBusy(false);
  };

  const restart = () => {
    setMessages([
      { from: 'them', text: `Bora de novo! 🙂 ${STEPS[0].ask}` },
    ]);
    setSlots({}); setStepIndex(0); setDone(false); setInput('');
  };

  const curStep = STEPS[stepIndex];
  const showChips = !done && !typing && !busy && curStep && curStep.chips;
  const progress = done ? STEPS.length : stepIndex;

  return (
    <section id="atendimento" className="section section-cream">
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: '0.85fr 1.15fr', gap: 'clamp(32px,5vw,64px)', alignItems: 'center' }} className="chat-grid">
          {/* the human + contato */}
          <div>
            <Reveal as="div" className="eyebrow">Fale conosco</Reveal>
            <Reveal as="h2" delay={60} className="sec-title">
              Do outro lado<br />tem <em className="it" style={{ color: 'var(--terra)' }}>gente</em>.
            </Reveal>
            <Reveal as="p" delay={120} className="sec-lead">
              A Adriana vai te fazer umas perguntas rápidas, entender sua operação e já te encaminhar — conversa de gente, não formulário chato.
            </Reveal>

            <Reveal delay={160} style={{ marginTop: 30, display: 'inline-flex', flexDirection: 'column', alignItems: 'flex-start', gap: 0 }}>
              <div style={{ position: 'relative' }}>
                <image-slot id="atendente-foto" shape="rounded" radius="22" src="assets/adriana-reina-crop.png" placeholder="Arraste a foto do atendente"
                  style={{ display: 'block', width: 'min(78vw, 300px)', height: 'min(90vw, 346px)', boxShadow: 'var(--shadow-md)', border: '1px solid var(--line)' }}></image-slot>
                <div style={{ position: 'absolute', left: 16, bottom: 16, display: 'inline-flex', alignItems: 'center', gap: 8, background: 'var(--white)', borderRadius: 999, padding: '8px 14px', boxShadow: 'var(--shadow-sm)' }}>
                  <span style={{ width: 9, height: 9, borderRadius: '50%', backgroundColor: 'var(--done)', boxShadow: '0 0 0 3px rgba(116,129,90,.22)' }} />
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>online agora</span>
                </div>
              </div>
              <div style={{ marginTop: 18 }}>
                <div className="serif-display" style={{ fontSize: 26 }}>{ATTENDANT.fullName}</div>
                <div style={{ fontSize: 14.5, color: 'var(--terra-deep)', fontWeight: 600, marginTop: 2 }}>{ATTENDANT.role}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-faint)', fontWeight: 500, letterSpacing: '.04em', textTransform: 'uppercase', marginTop: 1 }}>{ATTENDANT.roleEn}</div>
                <p style={{ fontSize: 14.5, color: 'var(--ink-soft)', lineHeight: 1.55, marginTop: 14, maxWidth: 340 }}>{ATTENDANT.bio}</p>
              </div>

              <div style={{ marginTop: 26, maxWidth: 360 }}>
                <div className="eyebrow" style={{ marginBottom: 14 }}>Contato direto</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                  {[
                    ['whatsapp', 'WhatsApp', '(11) 99476-0504', 'https://wa.me/5511994760504'],
                    ['instagram', 'Instagram', '@convivetecnologia', 'https://instagram.com/convivetecnologia'],
                    ['pin', 'Onde estamos', 'Londrina · Paraná', null],
                  ].map(([ic, label, val, href]) => {
                    const inner = (
                      <React.Fragment>
                        <span style={{ width: 40, height: 40, borderRadius: 11, background: 'var(--white)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', color: 'var(--terra)', flexShrink: 0 }}>
                          <Icon name={ic} size={19} />
                        </span>
                        <span style={{ lineHeight: 1.25 }}>
                          <span style={{ display: 'block', fontSize: 11.5, color: 'var(--ink-faint)', fontWeight: 600, letterSpacing: '.04em', textTransform: 'uppercase' }}>{label}</span>
                          <span style={{ display: 'block', fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{val}</span>
                        </span>
                      </React.Fragment>
                    );
                    const base = { display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none' };
                    return href ? (
                      <a key={label} href={href} target={href.startsWith('http') ? '_blank' : undefined} rel="noopener" style={{ ...base, transition: 'transform .15s' }}
                        onMouseEnter={e => e.currentTarget.style.transform = 'translateX(3px)'}
                        onMouseLeave={e => e.currentTarget.style.transform = 'none'}>{inner}</a>
                    ) : (
                      <div key={label} style={base}>{inner}</div>
                    );
                  })}
                </div>
              </div>
            </Reveal>
          </div>

          {/* the chat */}
          <Reveal delay={100}>
            <div className="card" style={{ overflow: 'hidden', boxShadow: 'var(--shadow-lg)', display: 'flex', flexDirection: 'column', height: 'min(80vh, 620px)' }}>
              {/* header */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px', borderBottom: '1px solid var(--line-soft)', background: 'var(--white)' }}>
                <img src="assets/adriana-reina-crop.png" alt="Adriana" style={{ width: 42, height: 42, borderRadius: '50%', objectFit: 'cover', objectPosition: '50% 14%', flexShrink: 0 }} />
                <div style={{ flex: 1, lineHeight: 1.25 }}>
                  <div style={{ fontSize: 15.5, fontWeight: 600 }}>{ATTENDANT.name}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--done)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--done)' }} /> {typing ? 'digitando…' : 'online · responde no mesmo dia'}
                  </div>
                </div>
                <Wordmark size={17} color="var(--ink)" />
              </div>

              {/* progress */}
              <div style={{ display: 'flex', gap: 5, padding: '10px 18px 0', background: 'var(--cream)' }}>
                {STEPS.map((s, i) => (
                  <div key={s.id} title={s.label} style={{ flex: 1, height: 4, borderRadius: 999, background: i < progress ? 'var(--terra)' : 'var(--line)', transition: 'background .3s' }} />
                ))}
              </div>

              {/* body */}
              <div ref={bodyRef} style={{ flex: 1, overflowY: 'auto', padding: '16px 18px', background: 'var(--cream)', display: 'flex', flexDirection: 'column', gap: 10 }} className="chat-body">
                {messages.map((m, i) => m.from === 'card' ? <LeadCard key={i} lead={m.lead} crm={m.crm} /> : <Bubble key={i} m={m} />)}
                {typing && <TypingBubble />}
              </div>

              {/* chips / input / done */}
              {done ? (
                <div style={{ display: 'flex', gap: 10, alignItems: 'center', padding: 14, flexWrap: 'wrap' }}>
                  <a href="https://wa.me/5511994760504" target="_blank" rel="noopener" className="btn btn-primary" style={{ flex: 1, justifyContent: 'center', minWidth: 180 }}>
                    <Icon name="whatsapp" size={18} /> Falar agora no WhatsApp
                  </a>
                  <button onClick={restart} className="btn btn-ghost">Recomeçar</button>
                </div>
              ) : (
                <React.Fragment>
                  {showChips && (
                    <div style={{ display: 'flex', gap: 8, padding: '12px 14px 0', flexWrap: 'wrap' }}>
                      {curStep.chips.map(opt => (
                        <button key={opt} onClick={() => submit(opt)} disabled={busy}
                          style={{ border: '1px solid var(--line)', background: 'var(--white)', color: 'var(--ink)', borderRadius: 999, padding: '8px 14px', fontSize: 13, fontWeight: 500, cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.55 : 1, transition: 'background .15s, border-color .15s' }}
                          onMouseEnter={e => { if (!busy) { e.currentTarget.style.background = 'var(--peach-soft)'; e.currentTarget.style.borderColor = 'var(--peach)'; } }}
                          onMouseLeave={e => { e.currentTarget.style.background = 'var(--white)'; e.currentTarget.style.borderColor = 'var(--line)'; }}>
                          {opt}
                        </button>
                      ))}
                    </div>
                  )}
                  <div style={{ display: 'flex', gap: 9, alignItems: 'center', padding: 14 }}>
                    <input
                      value={input}
                      onChange={e => setInput(e.target.value)}
                      onKeyDown={e => { if (e.key === 'Enter') submit(input); }}
                      placeholder={curStep && curStep.placeholder ? curStep.placeholder : 'Escreve aqui — pode falar do seu jeito…'}
                      disabled={busy}
                      style={{ flex: 1, border: '1px solid var(--line)', borderRadius: 999, padding: '12px 18px', fontSize: 14.5, fontFamily: 'var(--sans)', color: 'var(--ink)', background: 'var(--white)', outline: 'none' }}
                      onFocus={e => e.currentTarget.style.borderColor = 'var(--terra)'}
                      onBlur={e => e.currentTarget.style.borderColor = 'var(--line)'}
                    />
                    <button onClick={() => submit(input)} disabled={busy || !input.trim()} aria-label="Enviar"
                      style={{ width: 46, height: 46, borderRadius: '50%', border: 0, background: 'var(--terra)', color: 'var(--paper)', display: 'grid', placeItems: 'center', cursor: (busy || !input.trim()) ? 'default' : 'pointer', opacity: (busy || !input.trim()) ? 0.5 : 1, flexShrink: 0, transition: 'opacity .15s' }}>
                      <Icon name="arrow" size={20} stroke={2.3} />
                    </button>
                  </div>
                </React.Fragment>
              )}
            </div>
          </Reveal>
        </div>
      </div>

      <style>{`
        @media (max-width: 840px){ .chat-grid{ grid-template-columns: 1fr !important; } }
        @keyframes bubIn { from { opacity: 0; transform: translateY(7px); } to { opacity: 1; transform: none; } }
        .chat-bub { animation: bubIn .28s cubic-bezier(.2,.7,.2,1) both; }
        @keyframes blink { 0%,80%,100% { opacity: .3; transform: translateY(0); } 40% { opacity: 1; transform: translateY(-3px); } }
        @keyframes cardIn { from { opacity: 0; transform: translateY(10px) scale(.98); } to { opacity: 1; transform: none; } }
      `}</style>
    </section>
  );
}

// ── Lead → CRM card (o handoff de designação da própria Convive) ──
function LeadCard({ lead, crm }) {
  const rows = [
    ['Empresa', lead.empresa],
    ['Segmento', lead.segmento],
    ['Principal dor', lead.dor],
    ['Tamanho', lead.tamanho],
    ['Faturamento', lead.faturamento],
    ['Hoje usa', lead.ferramentas],
    ['Cidade', lead.cidade],
    ['E-mail', lead.email],
    ['WhatsApp', lead.contato],
  ];
  const sent = crm && crm.ok;
  const errored = crm && !crm.ok && !crm.demo;
  const headTitle = errored ? 'Lead salvo — sincronizando…' : 'Lead enviado pro CRM Convive';
  const headSub = sent ? 'qualificado, enviado e designado · agora'
    : errored ? 'qualificado e designado · retentaremos o envio'
    : 'qualificado e designado · agora';
  return (
    <div className="chat-bub" style={{ alignSelf: 'stretch', animation: 'cardIn .4s cubic-bezier(.2,.7,.2,1) both' }}>
      <div style={{ background: 'var(--white)', border: '1px solid var(--peach)', borderRadius: 16, overflow: 'hidden', boxShadow: 'var(--shadow-md)' }}>
        {/* header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px', background: 'var(--peach-soft)', borderBottom: '1px solid var(--peach)' }}>
          <span style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--terra)', color: 'var(--paper)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="check" size={17} stroke={2.6} /></span>
          <div style={{ lineHeight: 1.2 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--terra-deep)' }}>{headTitle}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-soft)' }}>{headSub}</div>
          </div>
          <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 600, color: 'var(--ink-faint)' }}>#CRM</span>
        </div>
        {/* lead name */}
        <div style={{ padding: '12px 16px 4px' }}>
          <div className="serif-display" style={{ fontSize: 20 }}>{lead.nome || 'Novo lead'}</div>
        </div>
        {/* fields */}
        <div style={{ padding: '4px 16px 10px', display: 'flex', flexDirection: 'column', gap: 7 }}>
          {rows.filter(([, v]) => v).map(([k, v]) => (
            <div key={k} style={{ display: 'flex', gap: 10, fontSize: 13 }}>
              <span style={{ width: 92, flexShrink: 0, color: 'var(--ink-faint)', fontWeight: 600 }}>{k}</span>
              <span style={{ color: 'var(--ink)', fontWeight: 500 }}>{v}</span>
            </div>
          ))}
        </div>
        {/* resumo de contexto */}
        {lead.resumo && (
          <div style={{ margin: '0 16px 12px', padding: '10px 12px', background: 'var(--cream)', border: '1px solid var(--line-soft)', borderRadius: 10 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--ink-faint)', marginBottom: 4 }}>Resumo pro time</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink)', lineHeight: 1.4 }}>{lead.resumo}</div>
          </div>
        )}
        {/* pipeline */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '10px 16px', borderTop: '1px solid var(--line-soft)', background: 'var(--cream)' }}>
          {['Novo lead', 'Qualificado', 'Designado → Adriana'].map((s, i) => (
            <React.Fragment key={s}>
              {i > 0 && <Icon name="arrow" size={13} color="var(--ink-faint)" />}
              <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.02em', color: i === 2 ? 'var(--terra-deep)' : 'var(--done)', background: i === 2 ? 'var(--peach-soft)' : 'transparent', borderRadius: 999, padding: i === 2 ? '3px 9px' : '3px 0' }}>{s}</span>
            </React.Fragment>
          ))}
        </div>
      </div>
    </div>
  );
}

function Bubble({ m }) {
  const me = m.from === 'me';
  return (
    <div className="chat-bub" style={{ alignSelf: me ? 'flex-end' : 'flex-start', maxWidth: '82%' }}>
      <div style={{
        background: me ? 'var(--terra)' : 'var(--white)',
        color: me ? 'var(--paper)' : 'var(--ink)',
        border: me ? '0' : '1px solid var(--line)',
        borderRadius: me ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
        padding: '11px 15px', fontSize: 14.5, lineHeight: 1.45,
        boxShadow: 'var(--shadow-sm)',
      }}>{m.text}</div>
    </div>
  );
}

function TypingBubble() {
  return (
    <div className="chat-bub" style={{ alignSelf: 'flex-start' }}>
      <div style={{ background: 'var(--white)', border: '1px solid var(--line)', borderRadius: '16px 16px 16px 4px', padding: '13px 16px', display: 'inline-flex', gap: 5 }}>
        {[0, 1, 2].map(i => (
          <span key={i} style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--ink-faint)', animation: `blink 1.2s ${i * 0.18}s infinite` }} />
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Atendimento });
