// WhatsAppChat.jsx — widget simulado de WhatsApp com streaming
const WhatsAppChat = () => {
  const conversations = [
    {
      question: 'Leandro, nossa empresa fecha o mês em D+15. Isso é normal?',
      answer: 'Não é normal, mas é comum. D+15 geralmente indica processo manual, falta de automação e ausência de rituais de fechamento. O benchmark de mercado está em D+5. Já conduzi projetos que foram de D+12 para D+5 sem trocar o sistema — só reorganizando o processo e automatizando conciliações críticas.',
    },
    {
      question: 'Qual a diferença entre FP&A e Controladoria na prática?',
      answer: 'Controladoria cuida do passado: garante que os números estejam corretos, o fechamento fechado e os controles funcionando. FP&A cuida do futuro: forecast, orçamento, análise de variação e suporte à decisão. Em empresa de médio porte, frequentemente a mesma pessoa faz os dois — mas é importante saber qual chapéu está usando em cada momento.',
    },
    {
      question: 'Faz sentido implementar SAP em empresa de R$ 80M de faturamento?',
      answer: 'Depende do problema que você quer resolver. SAP resolve problema de escala e integração — não de gestão. Se o problema é falta de disciplina de processo ou ausência de FP&A, SAP não vai resolver. Já vi empresas de R$ 500M rodando bem no Sankhya e empresas de R$ 80M que precisavam do SAP por conta da complexidade fiscal e societária. A pergunta certa é: qual dor exige qual sistema?',
    },
    {
      question: 'Como estruturar capital de giro em empresa com margem apertada?',
      answer: 'Começa mapeando o ciclo financeiro real: PMR, PMP e PME. A maioria das empresas com margem apertada tem problema de prazo — recebe devagar e paga rápido. Com o diagnóstico na mão, você trabalha as alavancas: antecipação de recebíveis, extensão de prazo com fornecedores estratégicos e redução de estoque sem comprometer serviço. Cada ponto de melhora no ciclo libera caixa sem precisar de captação.',
    },
  ];

  const [convIdx, setConvIdx] = React.useState(0);
  const [phase, setPhase] = React.useState('question'); // question | typing | answer | pause
  const [displayedAnswer, setDisplayedAnswer] = React.useState('');
  const [charIdx, setCharIdx] = React.useState(0);
  const [dots, setDots] = React.useState(1);
  const messagesEndRef = React.useRef(null);

  const conv = conversations[convIdx];

  // Dot animation during typing phase
  React.useEffect(() => {
    if (phase !== 'typing') return;
    const t = setInterval(() => setDots(d => d < 3 ? d + 1 : 1), 400);
    return () => clearInterval(t);
  }, [phase]);

  // State machine
  React.useEffect(() => {
    if (phase === 'question') {
      // Show question, then start typing
      const t = setTimeout(() => { setDisplayedAnswer(''); setCharIdx(0); setPhase('typing'); }, 1000);
      return () => clearTimeout(t);
    }
    if (phase === 'typing') {
      // Fake typing delay, then stream answer
      const t = setTimeout(() => setPhase('streaming'), 800);
      return () => clearTimeout(t);
    }
    if (phase === 'streaming') {
      if (charIdx < conv.answer.length) {
        const delay = conv.answer[charIdx] === '.' || conv.answer[charIdx] === ',' ? 25 : 8;
        const t = setTimeout(() => {
          setDisplayedAnswer(prev => prev + conv.answer[charIdx]);
          setCharIdx(c => c + 1);
        }, delay);
        return () => clearTimeout(t);
      } else {
        const t = setTimeout(() => setPhase('pause'), 200);
        return () => clearTimeout(t);
      }
    }
    if (phase === 'pause') {
      const t = setTimeout(() => {
        setConvIdx(c => (c + 1) % conversations.length);
        setDisplayedAnswer('');
        setCharIdx(0);
        setPhase('question');
      }, 2200);
      return () => clearTimeout(t);
    }
  }, [phase, charIdx, conv]);

  // Auto-scroll messages
  React.useEffect(() => {
    if (messagesEndRef.current) {
      const parent = messagesEndRef.current.parentElement;
      if (parent) parent.scrollTop = parent.scrollHeight;
    }
  }, [displayedAnswer, phase]);

  const avatarStyle = {
    width: 32, height: 32, borderRadius: '50%',
    background: '#0B2447', display: 'flex', alignItems: 'center', justifyContent: 'center',
    flexShrink: 0,
  };

  return React.createElement('div', {
    style: {
      width: '100%', maxWidth: 360,
      borderRadius: 12, overflow: 'hidden',
      boxShadow: '0 8px 40px rgba(11,36,71,0.18)',
      fontFamily: "'Inter', sans-serif",
      display: 'flex', flexDirection: 'column',
    }
  },
    // WA Header
    React.createElement('div', {
      style: {
        background: '#0B2447',
        padding: '12px 16px',
        display: 'flex', alignItems: 'center', gap: 12,
      }
    },
      // Back arrow
      React.createElement('span', { style: { color: 'rgba(247,245,240,0.6)', fontSize: 16 } }, '←'),
      // Avatar
      React.createElement('div', { style: avatarStyle },
        React.createElement('img', { src: 'assets/logo.png', alt: 'LR', style: { height: 18, opacity: 0.8 } })
      ),
      React.createElement('div', { style: { flex: 1 } },
        React.createElement('div', { style: { fontSize: 14, fontWeight: 600, color: '#F7F5F0', lineHeight: 1.2 } }, 'Leandro Rafael'),
        React.createElement('div', {
          style: { fontSize: 11, color: '#C9A961', marginTop: 1 }
        }, phase === 'typing' || phase === 'streaming' ? 'digitando...' : 'online')
      ),
      // Icons
      React.createElement('div', { style: { display: 'flex', gap: 16, color: 'rgba(247,245,240,0.5)', fontSize: 16 } },
        React.createElement('span', null, '📹'),
        React.createElement('span', null, '📞'),
      )
    ),

    // Chat background
    React.createElement('div', {
      style: {
        background: '#E5DDD5',
        backgroundImage: "url(\"data:image/svg+xml,%3Csvg width='60' height='60' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0h60v60H0z' fill='%23E5DDD5'/%3E%3C/svg%3E\")",
        padding: '16px 12px',
        minHeight: 280,
        maxHeight: 320,
        overflowY: 'auto',
        display: 'flex', flexDirection: 'column', gap: 8,
      }
    },

      // Date chip
      React.createElement('div', {
        style: { textAlign: 'center', marginBottom: 4 }
      },
        React.createElement('span', {
          style: { background: 'rgba(255,255,255,0.7)', fontSize: 11, color: '#3A3A3A', padding: '3px 10px', borderRadius: 8 }
        }, 'Hoje')
      ),

      // Question bubble (received)
      React.createElement('div', {
        style: { display: 'flex', justifyContent: 'flex-start', alignItems: 'flex-end', gap: 6 }
      },
        React.createElement('div', {
          style: {
            background: '#fff',
            borderRadius: '8px 8px 8px 2px',
            padding: '8px 10px',
            maxWidth: '75%',
            boxShadow: '0 1px 2px rgba(0,0,0,0.12)',
          }
        },
          React.createElement('div', { style: { fontSize: 13, color: '#1a1a1a', lineHeight: 1.4 } }, conv.question),
          React.createElement('div', { style: { fontSize: 10, color: '#9A9A9A', textAlign: 'right', marginTop: 4 } }, '14:32')
        )
      ),

      // Typing indicator or answer bubble (sent)
      (phase === 'typing') && React.createElement('div', {
        style: { display: 'flex', justifyContent: 'flex-start' }
      },
        React.createElement('div', {
          style: {
            background: '#fff',
            borderRadius: '8px 8px 8px 2px',
            padding: '10px 14px',
            boxShadow: '0 1px 2px rgba(0,0,0,0.12)',
            display: 'flex', gap: 4, alignItems: 'center',
          }
        },
          ...[0,1,2].map(i =>
            React.createElement('span', {
              key: i,
              style: {
                width: 7, height: 7, borderRadius: '50%',
                background: dots > i ? '#0B2447' : 'rgba(11,36,71,0.25)',
                transition: 'background 200ms',
                display: 'inline-block',
              }
            })
          )
        )
      ),

      (phase === 'streaming' || phase === 'pause') && displayedAnswer && React.createElement('div', {
        style: { display: 'flex', justifyContent: 'flex-end' }
      },
        React.createElement('div', {
          style: {
            background: '#DCF8C6',
            borderRadius: '8px 8px 2px 8px',
            padding: '8px 10px',
            maxWidth: '78%',
            boxShadow: '0 1px 2px rgba(0,0,0,0.12)',
          }
        },
          React.createElement('div', { style: { fontSize: 13, color: '#1a1a1a', lineHeight: 1.5, textWrap: 'pretty' } },
            displayedAnswer,
            (phase === 'streaming') && React.createElement('span', {
              style: { display: 'inline-block', width: 2, height: 13, background: '#0B2447', marginLeft: 1, verticalAlign: 'middle', animation: 'blink 800ms step-end infinite' }
            })
          ),
          React.createElement('div', {
            style: { fontSize: 10, color: '#6B6B6B', textAlign: 'right', marginTop: 4, display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 4 }
          },
            '14:33',
            React.createElement('span', { style: { color: '#4FC3F7', fontSize: 12 } }, '✓✓')
          )
        )
      ),

      React.createElement('div', { ref: messagesEndRef })
    ),

    // WA bottom bar
    React.createElement('div', {
      style: {
        background: '#F0F0F0',
        padding: '8px 12px',
        display: 'flex', alignItems: 'center', gap: 8,
      }
    },
      React.createElement('div', {
        style: {
          flex: 1, background: '#fff', borderRadius: 20,
          padding: '8px 14px', fontSize: 13, color: '#9A9A9A',
          boxShadow: '0 1px 2px rgba(0,0,0,0.08)',
        }
      }, 'Mensagem'),
      React.createElement('div', {
        style: {
          width: 36, height: 36, borderRadius: '50%',
          background: '#0B2447', display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#C9A961', fontSize: 16, cursor: 'pointer',
        }
      }, '🎤')
    )
  );
};

Object.assign(window, { WhatsAppChat });
