/**
 * WhatsAppChat — mockup de conversa de WhatsApp auto-animado, reutilizável.
 * Usado pelo HeroChatMockup (compacto) e pela seção VejaConversa (completo).
 *
 * Props:
 *   messages   — array no formato de dialogos.jsx
 *   headerName — nome exibido no topo do chat (ex: "Escritório — atendimento")
 *   variant    — 'compact' (hero) | 'full' (VejaConversa) → muda só classes CSS
 *   loop       — reinicia a animação ao terminar (default true)
 *
 * Anima as bolhas em sequência: mensagem do lead aparece após um delay; resposta
 * da IA mostra "digitando…" antes de surgir. Faz auto-scroll pro fim.
 */
const WhatsAppChat = ({ messages = [], headerName = 'Escritório — atendimento', variant = 'compact', loop = true }) => {
  const [visible, setVisible] = React.useState(0);
  const [typing, setTyping] = React.useState(false);
  const bodyRef = React.useRef(null);

  React.useEffect(() => {
    if (visible >= messages.length) {
      if (!loop) return;
      const reset = setTimeout(() => { setVisible(0); }, 4200);
      return () => clearTimeout(reset);
    }
    const next = messages[visible];
    if (next.side === 'ai') {
      setTyping(true);
      const t1 = setTimeout(() => setTyping(false), 1000);
      const t2 = setTimeout(() => setVisible((v) => v + 1), 1600);
      return () => { clearTimeout(t1); clearTimeout(t2); };
    }
    const t = setTimeout(() => setVisible((v) => v + 1), 1150);
    return () => clearTimeout(t);
  }, [visible, messages, loop]);

  // Auto-scroll pro fim a cada nova bolha / typing.
  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [visible, typing]);

  const renderBubbleContent = (m) => {
    if (m.type === 'image') {
      return (
        <span className="wa-attach wa-attach-doc">
          <span className="wa-attach-icon" aria-hidden="true"><Icon.Doc size={18}/></span>
          <span className="wa-attach-label">{m.text}</span>
        </span>
      );
    }
    if (m.type === 'audio') {
      return (
        <span className="wa-attach wa-attach-audio">
          <span className="wa-attach-icon" aria-hidden="true"><Icon.Play size={14}/></span>
          <span className="wa-wave" aria-hidden="true">
            {Array.from({ length: 14 }, (_, i) => <i key={i} style={{ height: `${4 + ((i * 7) % 16)}px` }}></i>)}
          </span>
          <span className="wa-attach-label">{m.text}</span>
        </span>
      );
    }
    return m.text;
  };

  return (
    <div className={`wa-chat wa-${variant}`}>
      <div className="wa-screen">
        <div className="wa-header">
          <div className="wa-avatar" aria-hidden="true"><Icon.Whatsapp size={16}/></div>
          <div className="wa-header-meta">
            <span className="wa-header-name">{headerName}</span>
            <span className="wa-header-status">{typing ? 'digitando…' : 'online'}</span>
          </div>
        </div>

        <div className="wa-body" ref={bodyRef}>
          {messages.slice(0, visible).map((m, i) => {
            if (m.type === 'system') {
              return (
                <div key={i} className="wa-system">
                  <span className="wa-system-icon" aria-hidden="true"><Icon.Check size={12}/></span>
                  {m.text}
                </div>
              );
            }
            return (
              <div key={i} className={`wa-bubble wa-${m.side} ${m.type !== 'text' ? 'wa-bubble-attach' : ''}`}>
                {renderBubbleContent(m)}
                <span className="wa-time">{m.time}{m.side === 'user' ? ' ✓✓' : ''}</span>
              </div>
            );
          })}
          {typing && (
            <div className="wa-bubble wa-ai wa-typing">
              <span className="wa-dot"></span><span className="wa-dot"></span><span className="wa-dot"></span>
            </div>
          )}
        </div>

        <div className="wa-input">
          <span className="wa-input-field">Mensagem</span>
          <span className="wa-input-send" aria-hidden="true"><Icon.Send size={14}/></span>
        </div>
      </div>
    </div>
  );
};

window.WhatsAppChat = WhatsAppChat;
