/* Chat / Conversa de WhatsApp com co-piloto de IA */

const ChatListItem = ({ lead, active, onClick }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 11,
      padding: '11px 14px', cursor: 'pointer',
      background: active ? (isBloom ? t.surfaceHi : 'rgba(91,141,239,0.08)') : 'transparent',
      borderLeft: active && !isBloom ? `2px solid ${t.primary}` : '2px solid transparent',
      borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
      position: 'relative',
    }}>
      <Avatar name={lead.avatar} color={lead.color} size={42} ai={lead.aiActive}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontSize: 13.5, fontWeight: 600, color: t.text, letterSpacing: '-0.01em',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{lead.name}</span>
          <span style={{ fontSize: 10.5, color: t.textMuted, fontFamily: t.fontMono, flexShrink: 0 }}>
            {lead.lastMessageAt ? new Date(lead.lastMessageAt).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}) : ''}
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}>
          <span style={{ fontSize: 12, color: t.textMuted, lineHeight: 1.3,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, minWidth: 0 }}>
            {(lead.lastMessage || '').replace(/[""]/g, '')}
          </span>
          {lead.unread > 0 && (
            <span style={{
              padding: '1px 6px', borderRadius: 99, fontSize: 10, fontWeight: 700, fontFamily: t.fontMono,
              background: t.green, color: '#fff', flexShrink: 0,
              border: isBloom ? `1.5px solid ${t.border}` : 'none',
            }}>{lead.unread}</span>
          )}
        </div>
      </div>
    </div>
  );
};

const MessageBubble = ({ msg, idx }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  if (msg.from === 'system') {
    return (
      <div style={{ textAlign: 'center', margin: '12px 0' }}>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '5px 12px', borderRadius: 99,
          background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.04)',
          border: isBloom ? `1.5px solid ${t.border}` : '1px solid rgba(255,255,255,0.06)',
          fontSize: 11, color: t.textMuted, fontFamily: t.fontMono,
        }}>
          <Icons.Bot size={11}/> {msg.text} · {msg.time ? new Date(msg.time).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', timeZone: 'America/Sao_Paulo' }) : ''}
        </span>
      </div>
    );
  }
  const isMe = msg.from === 'me';
  const isAi = msg.who === 'ai';
  return (
    <div style={{ display: 'flex', justifyContent: isMe ? 'flex-end' : 'flex-start', marginBottom: 4 }}>
      <div style={{ maxWidth: '68%' }}>
        <div style={{
          padding: '8px 12px 6px',
          borderRadius: isMe ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
          background: isMe
            ? (isAi
                ? (isBloom ? '#D6FFE8' : 'rgba(16,185,129,0.13)')
                : (isBloom ? '#FFE5B7' : 'rgba(91,141,239,0.13)'))
            : (isBloom ? t.surface : t.surfaceAlt),
          border: isBloom ? `1.5px solid ${t.border}` : (isMe
            ? (isAi ? '1px solid rgba(16,185,129,0.25)' : '1px solid rgba(91,141,239,0.25)')
            : `1px solid ${t.border}`),
          color: t.text, fontSize: 13.5, lineHeight: 1.45,
          boxShadow: isBloom ? '2px 2px 0 0 #14131A' : 'none',
        }}>
          {isAi && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 4,
              fontSize: 10, fontWeight: 700, color: isBloom ? t.text : t.green,
              fontFamily: t.fontMono, letterSpacing: '0.06em' }}>
              <Icons.Sparkles size={10} stroke={isBloom ? t.text : t.green}/> ASSISTENTE IA
            </div>
          )}
          {msg.attachmentUrl && (
            <a href={msg.attachmentUrl} target="_blank" rel="noreferrer" style={{ 
              display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6, 
              padding: '6px 10px', background: 'rgba(0,0,0,0.1)', borderRadius: 6,
              textDecoration: 'none', color: 'inherit', fontSize: 12
            }}>
              <Icons.FileText size={16}/> <span>Ver anexo</span>
            </a>
          )}
          <div>{msg.text}</div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 5,
            marginTop: 3, fontSize: 10, color: t.textMuted, fontFamily: t.fontMono }}>
            {msg.time ? new Date(msg.time).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', timeZone: 'America/Sao_Paulo' }) : ''}
            {isMe && (msg.read ? <Icons.CheckDouble size={12} stroke={t.primary}/> : <Icons.Check size={12}/>)}
          </div>
        </div>
      </div>
    </div>
  );
};

const Chat = ({ activeLeadId = 1, onOpenCrm }) => {
  const t = useTheme();
  const { showToast } = useToast();
  const isBloom = t.name === 'BLOOM';
  
  const [selected, setSelected] = React.useState(activeLeadId);
  const [draft, setDraft] = React.useState('');
  const [aiMode, setAiMode] = React.useState(true);
  const [searchQuery, setSearchQuery] = React.useState('');
  const [chatFilter, setChatFilter] = React.useState('all');
  
  // Refs e Estados adicionais para anexo ativo e áudio funcional (Fase BETA - Estabilidade)
  const composerFileInputRef = React.useRef(null);
  const [composerUploading, setComposerUploading] = React.useState(false);
  const [recording, setRecording] = React.useState(false);
  const [recorderInstance, setRecorderInstance] = React.useState(null);
  const chunksRef = React.useRef([]);
  
  const { data: apiLeads, loading: loadingLeads, refetch: refetchLeads } = useLeads();
  const leads = (apiLeads && apiLeads.data) ? apiLeads.data : (Array.isArray(apiLeads) ? apiLeads : []);
  const safeLeadId = selected && leads.some(l => l.id === selected) ? selected : (leads.length > 0 ? leads[0].id : null);
  
  React.useEffect(() => {
    if (safeLeadId) {
      const current = leads.find(l => l.id === safeLeadId);
      if (current && current.unread > 0) {
        window.FluxoApi.post(`/conversations/${safeLeadId}/read`).then(() => {
          if (refetchLeads) refetchLeads();
        }).catch(console.error);
      }
    }
  }, [safeLeadId, apiLeads]);
  
  const filteredLeads = leads.filter(l => {
    if (chatFilter === 'ai' && !l.aiActive) return false;
    if (chatFilter === 'hot' && l.temp !== 'quente') return false;
    if (searchQuery && !l.name.toLowerCase().includes(searchQuery.toLowerCase())) return false;
    return true;
  });
  
  const { data: apiMessages } = useConversation(safeLeadId);
  const { ask: askAi, suggestion: aiSuggestion, loading: aiLoading } = useAiSuggest();
  const { data: quickRepliesData } = useQuickReplies();
  const uploadQuickReply = useUploadQuickReply();
  const sendMessage = useSendMessage();

  const fileInputRef = React.useRef(null);
  const [uploadingQrId, setUploadingQrId] = React.useState(null);

  const lead = leads.find(l => l.id === safeLeadId) || leads[0];
  const messages = apiMessages || [];
  const quickReplies = quickRepliesData || [];

  const handleSend = (textOverride = null, attachmentUrl = null) => {
    const textToSend = typeof textOverride === 'string' ? textOverride : draft;
    if (!textToSend.trim() && !attachmentUrl) return;
    sendMessage(lead.id, textToSend, { via: aiMode ? 'ai' : 'human', attachmentUrl });
    if (typeof textOverride !== 'string') setDraft('');
  };

  const handleGenerateSummary = async () => {
    if (!lead) return;
    try {
      const res = await window.FluxoApi.post(`/leads/${lead.id}/analyze`);
      if (res && res.lead) {
        if (refetchLeads) refetchLeads();
      }
    } catch (e) {
      console.error(e);
      alert('Erro ao gerar resumo da IA.');
    }
  };

  const handleMarkDone = async () => {
    if (!lead) return;
    try {
      await window.FluxoApi.patch(`/leads/${lead.id}`, { nextAction: "" });
      if (refetchLeads) refetchLeads();
    } catch (e) {
      console.error(e);
    }
  };

  let parsedObjections = [];
  try {
    if (lead?.objections) {
      parsedObjections = JSON.parse(lead.objections);
    }
  } catch (e) {}

  const handleToggleTemp = async () => {
    if (!lead) return;
    const order = ['frio', 'morno', 'quente', 'fechado'];
    const current = lead.temp || 'morno';
    const nextTemp = order[(order.indexOf(current) + 1) % order.length];
    try {
      await window.FluxoApi.patch(`/leads/${lead.id}`, { temp: nextTemp });
      if (refetchLeads) refetchLeads();
    } catch (e) {
      console.error(e);
    }
  };

  const handleFileChange = async (e) => {
    if (!e.target.files || !e.target.files[0] || !uploadingQrId) return;
    try {
      await uploadQuickReply(uploadingQrId, e.target.files[0]);
    } catch (err) {
      console.error("Erro no upload", err);
    }
    setUploadingQrId(null);
    e.target.value = null; // reset
  };

  const handleComposerFileChange = async (e) => {
    if (!e.target.files || !e.target.files[0]) return;
    setComposerUploading(true);
    showToast('Enviando anexo comercial...', 'info');
    
    const file = e.target.files[0];
    const formData = new FormData();
    formData.append('file', file);
    
    try {
      const res = await fetch('/api/conversations/upload-media', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('fluxo_token')}`
        },
        body: formData
      });
      if (res.ok) {
        const data = await res.json();
        // Envia o anexo na hora!
        handleSend("📎 Anexo: " + file.name, data.attachmentUrl);
        showToast('Anexo enviado com sucesso!', 'success');
      } else {
        showToast('Erro ao enviar anexo.', 'error');
      }
    } catch (err) {
      showToast('Erro ao conectar ao servidor de uploads.', 'error');
    } finally {
      setComposerUploading(false);
      e.target.value = null; // reset
    }
  };

  const handleToggleVoiceRecord = async () => {
    if (!recording) {
      // Inicia a gravação
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        showToast('Gravação de áudio não suportada neste navegador.', 'error');
        return;
      }
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        const recorder = new MediaRecorder(stream);
        chunksRef.current = [];
        
        recorder.ondataavailable = (e) => {
          if (e.data && e.data.size > 0) chunksRef.current.push(e.data);
        };
        
        recorder.onstop = async () => {
          // Salva e envia o áudio
          const audioBlob = new Blob(chunksRef.current, { type: 'audio/webm' });
          const file = new File([audioBlob], `gravacao_${Date.now()}.webm`, { type: 'audio/webm' });
          
          const formData = new FormData();
          formData.append('file', file);
          
          showToast('Processando e enviando áudio...', 'info');
          try {
            const res = await fetch('/api/conversations/upload-media', {
              method: 'POST',
              headers: {
                'Authorization': `Bearer ${localStorage.getItem('fluxo_token')}`
              },
              body: formData
            });
            if (res.ok) {
              const data = await res.json();
              // Envia a mensagem de áudio na hora
              handleSend("🎤 Mensagem de voz", data.attachmentUrl);
              showToast('Áudio enviado com sucesso!', 'success');
            } else {
              showToast('Erro ao enviar áudio gravado.', 'error');
            }
          } catch(err) {
            showToast('Falha na conexão ao subir áudio.', 'error');
          }
          
          // Desativa os microfones para não ficar ícone de gravação no navegador
          stream.getTracks().forEach(track => track.stop());
        };
        
        recorder.start();
        setRecorderInstance(recorder);
        setRecording(true);
        showToast('🎤 Gravando áudio comercial... Clique de novo para enviar!', 'info');
      } catch (err) {
        console.error(err);
        showToast('Permissão de microfone recusada ou erro ao acessar hardware.', 'error');
      }
    } else {
      // Para e envia
      if (recorderInstance) {
        recorderInstance.stop();
        setRecording(false);
      }
    }
  };

  if (loadingLeads) return <div style={{padding:20, color: t.text}}>Carregando chat...</div>;
  if (!lead) return (
    <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.textMuted, flexDirection: 'column', gap: 10 }}>
      <Icons.Chat size={40} opacity={0.3} />
      <span style={{ fontSize: 16 }}>Nenhuma conversa encontrada.</span>
      <span style={{ fontSize: 13, maxWidth: 400, textAlign: 'center', marginTop: 5 }}>Envie uma mensagem para o número de WhatsApp do sistema para iniciar o primeiro atendimento.</span>
    </div>
  );

  return (
    <div style={{ height: '100%', display: 'flex', overflow: 'hidden' }}>
      <input type="file" ref={fileInputRef} style={{ display: 'none' }} onChange={handleFileChange} />
      <input type="file" ref={composerFileInputRef} style={{ display: 'none' }} onChange={handleComposerFileChange} accept=".png,.jpg,.jpeg,.gif,.pdf,.doc,.docx,.xls,.xlsx,.mp3,.ogg,.wav,.mp4,.webm" />
      {/* Left: conversation list */}
      <aside style={{
        width: 320, flexShrink: 0,
        background: isBloom ? t.surface : '#0B0F1C',
        borderRight: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        <div style={{ padding: '18px 16px',
          borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 20, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Conversas
            </h2>
            <div style={{ display: 'flex', gap: 6 }}>
              <Btn variant="ghost" size="sm" style={{ padding: 6 }} onClick={() => showToast('Mais opções de filtro chegando na próxima build.')}><Icons.Filter size={14}/></Btn>
              <Btn variant="ghost" size="sm" style={{ padding: 6 }} onClick={() => showToast('Nova conversa externa em breve.')}><Icons.Plus size={14}/></Btn>
            </div>
          </div>
          <div style={{ position: 'relative' }}>
            <Icons.Search size={14} stroke={t.textMuted} style={{ position: 'absolute', left: 11, top: 9 }}/>
            <input 
              placeholder="Buscar contato..." 
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              style={{
                width: '100%', padding: '8px 12px 8px 32px',
                background: isBloom ? t.bg : 'rgba(255,255,255,0.04)',
                border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
                borderRadius: t.radiusMd, color: t.text, fontSize: 13, outline: 'none',
              }}
            />
          </div>
          <div style={{ display: 'flex', gap: 5, marginTop: 12 }}>
            <Tab active={chatFilter === 'all'} onClick={() => setChatFilter('all')} count={leads.length}>Todos</Tab>
            <Tab active={chatFilter === 'ai'} onClick={() => setChatFilter('ai')} count={leads.filter(l=>l.aiActive).length} color={t.green}>IA</Tab>
            <Tab active={chatFilter === 'hot'} onClick={() => setChatFilter('hot')} count={leads.filter(l=>l.temp==='quente').length} color={t.orange}>Quentes</Tab>
          </div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {leads.filter(l => {
            if (chatFilter === 'ai' && !l.aiActive) return false;
            if (chatFilter === 'hot' && l.temp !== 'quente') return false;
            if (searchQuery && !l.name.toLowerCase().includes(searchQuery.toLowerCase())) return false;
            return true;
          }).map(l => (
            <ChatListItem key={l.id} lead={l} active={l.id === selected} onClick={() => setSelected(l.id)}/>
          ))}
        </div>
      </aside>

      {/* Center: chat */}
      <main style={{
        flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0,
        background: isBloom
          ? `${t.bg} ${t.bgGrid}`
          : `radial-gradient(circle at 1px 1px, rgba(255,255,255,0.025) 1px, transparent 0) #0A0E1A`,
        backgroundSize: '20px 20px',
      }}>
        {/* Chat header */}
        <div style={{ padding: '14px 22px', display: 'flex', alignItems: 'center', gap: 12,
          background: t.surface,
          borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
        }}>
          <Avatar name={lead.avatar} color={lead.color} size={40} ai={lead.aiActive}/>
          <div style={{ flex: 1, cursor: 'pointer' }} onClick={() => onOpenCrm && onOpenCrm(lead.id)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 15, fontWeight: 700, color: t.text, letterSpacing: '-0.01em' }}>{lead.name}</span>
              <Pill soft={t.greenSoft} color={isBloom ? t.text : t.green} style={{ padding: '2px 7px', fontSize: 10 }}>
                <span style={{width:6,height:6,borderRadius:'50%',background:t.green}}/> online
              </Pill>
            </div>
            <div style={{ fontSize: 11.5, color: t.textMuted, fontFamily: t.fontMono, marginTop: 2 }}>
              {(() => {
                let p = lead.phone || '';
                // Se começar com algo como 55 ou tiver mais dígitos, tenta formatar um pouco.
                // Se for um número que parece WhatsApp do brasil (ex: 554199999999)
                if (p.length >= 12 && p.startsWith('55')) {
                   const ddd = p.substring(2, 4);
                   const num = p.substring(4);
                   if (num.length === 9) {
                     p = `+55 (${ddd}) ${num.substring(0,5)}-${num.substring(5)}`;
                   } else if (num.length === 8) {
                     p = `+55 (${ddd}) ${num.substring(0,4)}-${num.substring(4)}`;
                   }
                } else if (p.length === 11 || p.length === 10) {
                   const ddd = p.substring(0, 2);
                   const num = p.substring(2);
                   p = `(${ddd}) ${num.length === 9 ? num.substring(0,5)+'-'+num.substring(5) : num.substring(0,4)+'-'+num.substring(4)}`;
                }
                return p;
              })()} · {lead.city || 'Desconhecido'} · score {lead.score}
            </div>
          </div>
          <Btn variant="ghost" size="sm" style={{ padding: 8 }} onClick={() => showToast('Ligação VOIP em breve.')}><Icons.Phone size={16}/></Btn>
          <Btn variant="ghost" size="sm" style={{ padding: 8 }} onClick={() => showToast('Videochamada indisponível.')}><Icons.Video size={16}/></Btn>
          <Btn variant="ghost" size="sm" style={{ padding: 8 }} onClick={() => showToast('Menu de opções adicionais.')}><Icons.More size={16}/></Btn>
        </div>

        {/* Messages */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '20px 22px' }}>
          {/* Date separator */}
          <div style={{ textAlign: 'center', marginBottom: 14 }}>
            <span style={{
              padding: '4px 10px', borderRadius: 99, fontSize: 11, fontFamily: t.fontMono,
              background: isBloom ? t.surface : 'rgba(0,0,0,0.4)',
              border: isBloom ? `1.5px solid ${t.border}` : '1px solid rgba(255,255,255,0.06)',
              color: t.textMuted,
            }}>HOJE</span>
          </div>
          {messages.map((msg, i) => <MessageBubble key={msg.id || i} msg={msg} idx={i}/>)}
        </div>

        {/* AI suggestion bar */}
        {aiMode && (
          <div style={{
            margin: '0 22px 10px', padding: '12px 14px',
            background: isBloom ? t.primarySoft : 'rgba(91,141,239,0.1)',
            border: isBloom ? `1.5px solid ${t.border}` : `1px solid rgba(91,141,239,0.25)`,
            borderRadius: t.radiusMd,
            boxShadow: isBloom ? '3px 3px 0 0 #14131A' : 'none',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 7 }}>
              <Icons.Sparkles size={13} stroke={isBloom ? t.text : t.primary}/>
              <span style={{ fontSize: 10.5, fontWeight: 700, color: isBloom ? t.text : t.primary,
                letterSpacing: '0.08em', fontFamily: t.fontMono }}>IA SUGERE ENVIAR</span>
              <span style={{ marginLeft: 'auto', fontSize: 10, color: t.textMuted, fontFamily: t.fontMono }}>conf. 94%</span>
            </div>
            <div style={{ fontSize: 13, color: t.text, lineHeight: 1.45, marginBottom: 10 }}>
              {aiLoading ? "Gerando sugestão da IA..." : (aiSuggestion ? aiSuggestion.text : "Nenhuma sugestão ainda.")}
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              {aiSuggestion && (
                <>
                  <Btn variant="green" size="sm" icon={<Icons.Send size={12}/>} onClick={() => { setDraft(''); handleSend(aiSuggestion.text); }}>
                    Aceitar e enviar
                  </Btn>
                  <Btn variant="secondary" size="sm" onClick={() => setDraft(aiSuggestion.text)}>Editar primeiro</Btn>
                </>
              )}
              <Btn variant={!aiSuggestion ? "primary" : "ghost"} size="sm" onClick={() => askAi(lead.id, 'nova')} loading={aiLoading}>
                {aiSuggestion ? "Outra sugestão" : "Gerar sugestão da IA"}
              </Btn>
              <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: t.textMuted, fontFamily: t.fontMono }}>
                <span>Tom:</span>
                <span style={{ padding: '2px 8px', borderRadius: 99,
                  background: isBloom ? t.surface : 'rgba(255,255,255,0.06)',
                  border: isBloom ? `1.5px solid ${t.border}` : 'none', color: t.text, fontWeight: 600 }}>amigável</span>
              </div>
            </div>
          </div>
        )}

        {/* Composer */}
        <div style={{ padding: 16, background: t.surface,
          borderTop: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
        }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10 }}>
            <Btn variant="ghost" size="sm" style={{ padding: 9 }} onClick={() => composerFileInputRef.current && composerFileInputRef.current.click()} loading={composerUploading}><Icons.Plus size={18}/></Btn>
            <div style={{ flex: 1,
              background: isBloom ? t.bg : 'rgba(255,255,255,0.04)',
              border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
              borderRadius: t.radiusMd, padding: '6px 12px',
            }}>
              <textarea value={draft} onChange={e => setDraft(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }}
                placeholder="Mensagem para o cliente... (digite / para comandos da IA)"
                rows={1} style={{
                  width: '100%', border: 'none', outline: 'none', resize: 'none',
                  background: 'transparent', color: t.text, fontSize: 14, lineHeight: 1.4,
                  padding: '6px 0', maxHeight: 120,
                }}/>
            </div>
            <Btn variant={draft ? 'green' : 'secondary'} size="md" style={{ padding: 10 }} onClick={handleSend}>
              <Icons.Send size={16} stroke={draft ? (isBloom ? '#0a2a1f' : '#fff') : t.textMuted}/>
            </Btn>
          </div>
          {/* Mode toggle */}
          <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 12, fontSize: 11, color: t.textMuted, fontFamily: t.fontMono }}>
            <span>MODO:</span>
            <button onClick={() => { setAiMode(true); showToast('Modo Co-piloto ativado.'); }} style={{
              padding: '4px 9px', borderRadius: 6,
              background: aiMode ? t.greenSoft : 'transparent',
              color: aiMode ? (isBloom ? t.text : t.green) : t.textMuted,
              border: isBloom ? `1.5px solid ${aiMode ? t.border : 'transparent'}` : 'none',
              fontWeight: 700, letterSpacing: '0.04em', display: 'flex', alignItems: 'center', gap: 5,
            }}>
              <Icons.Sparkles size={11}/> IA CO-PILOTO
            </button>
            <button onClick={() => { setAiMode(false); showToast('Modo Só Humano ativado. A IA irá parar de enviar mensagens para este lead automaticamente.', 'info'); }} style={{
              padding: '4px 9px', borderRadius: 6,
              background: !aiMode ? t.primarySoft : 'transparent',
              color: !aiMode ? (isBloom ? t.text : t.primary) : t.textMuted,
              border: isBloom ? `1.5px solid ${!aiMode ? t.border : 'transparent'}` : 'none',
              fontWeight: 700, letterSpacing: '0.04em', display: 'flex', alignItems: 'center', gap: 5,
            }}>
              <Icons.Users size={11}/> SÓ HUMANO
            </button>
          </div>
        </div>
      </main>

      {/* Right: AI co-pilot panel */}
      <aside style={{
        width: 320, flexShrink: 0,
        background: isBloom ? t.surface : '#0B0F1C',
        borderLeft: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        <div style={{ padding: '16px 18px',
          borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
          display: 'flex', alignItems: 'center', gap: 9,
        }}>
          <Icons.Sparkles size={16} stroke={isBloom ? t.text : t.primary}/>
          <span style={{ fontSize: 14, fontWeight: 700, color: t.text, letterSpacing: '-0.01em', flex: 1 }}>Co-piloto IA</span>
          <ScoreRing value={lead.score} size={30}/>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 18 }}>
          {/* Customer snapshot */}
          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, letterSpacing: '0.12em', fontFamily: t.fontMono, marginBottom: 8 }}>
              SOBRE {lead.name ? lead.name.split(' ')[0].toUpperCase() : 'CLIENTE'}
            </div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 12 }}>
              {(lead.tags || []).map(tag => (
                <Pill key={tag} soft={t.purpleSoft} color={isBloom ? t.text : t.purple}>{tag}</Pill>
              ))}
              <div onClick={handleToggleTemp} style={{ cursor: 'pointer', transition: 'all 0.2s ease', opacity: 0.9 }}>
                <Pill soft={lead.temp === 'frio' ? t.blueSoft : lead.temp === 'quente' ? t.orangeSoft : lead.temp === 'fechado' ? t.greenSoft : t.primarySoft} 
                      color={isBloom ? t.text : (lead.temp === 'frio' ? t.blue : lead.temp === 'quente' ? t.orange : lead.temp === 'fechado' ? t.green : t.primary)}>
                  <Icons.Fire size={11} stroke={isBloom ? t.text : (lead.temp === 'frio' ? t.blue : lead.temp === 'quente' ? t.orange : lead.temp === 'fechado' ? t.green : t.primary)}/> 
                  lead {lead.temp || 'morno'}
                </Pill>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 4 }}>
              <div>
                <div style={{ fontSize: 10, color: t.textMuted, fontFamily: t.fontMono }}>ORIGEM</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: t.text, marginTop: 2 }}>{lead.source}</div>
              </div>
              <div>
                <div style={{ fontSize: 10, color: t.textMuted, fontFamily: t.fontMono }}>VALOR EST.</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: t.text, marginTop: 2, fontFamily: t.fontMono }}>
                  R$ {((lead.value_cents || 0) / 100).toLocaleString('pt-BR', { minimumFractionDigits: 2 })}
                </div>
              </div>
            </div>
          </div>

          {/* AI Summary */}
          <div style={{ marginBottom: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
              <div style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, letterSpacing: '0.12em', fontFamily: t.fontMono }}>
                RESUMO DA CONVERSA
              </div>
              <button onClick={handleGenerateSummary} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', background: 'transparent', border: 'none', padding: 0 }}>
                <span style={{ fontSize: 9, padding: '1px 5px', borderRadius: 3,
                  background: t.greenSoft, color: isBloom ? t.text : t.green, fontFamily: t.fontMono, fontWeight: 700,
                  border: isBloom ? `1px solid ${t.border}` : 'none' }}>GERAR RESUMO</span>
              </button>
            </div>
            <div style={{ fontSize: 12.5, color: t.text, lineHeight: 1.55 }}>{lead.summary || "Nenhum resumo gerado ainda."}</div>
          </div>

          {/* Objections detected */}
          {parsedObjections.length > 0 && (
            <div style={{ marginBottom: 18 }}>
              <div style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, letterSpacing: '0.12em', fontFamily: t.fontMono, marginBottom: 8 }}>
                OBJEÇÕES DETECTADAS
              </div>
              {parsedObjections.map((o, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  padding: '7px 10px', marginBottom: 6,
                  background: isBloom ? t.bg : 'rgba(255,255,255,0.03)',
                  border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
                  borderRadius: t.radiusSm, fontSize: 12, color: t.text,
                }}>
                  <span>{o.obj}</span>
                  <span style={{ fontFamily: t.fontMono, fontSize: 10, color: t.textMuted }}>{o.conf}%</span>
                </div>
              ))}
            </div>
          )}

          {/* Next action */}
          <div style={{
            padding: 12, borderRadius: t.radiusMd,
            background: isBloom ? t.greenSoft : 'rgba(16,185,129,0.08)',
            border: isBloom ? `1.5px solid ${t.border}` : `1px solid rgba(16,185,129,0.2)`,
            boxShadow: isBloom ? '3px 3px 0 0 #14131A' : 'none',
            marginBottom: 18,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
              <Icons.Lightning size={12} stroke={isBloom ? t.text : t.green}/>
              <span style={{ fontSize: 10, fontWeight: 700, color: isBloom ? t.text : t.green,
                letterSpacing: '0.08em', fontFamily: t.fontMono }}>PRÓXIMA AÇÃO</span>
            </div>
            <div style={{ fontSize: 13, color: t.text, lineHeight: 1.45, fontWeight: 500 }}>{lead.nextAction}</div>
            <Btn variant="green" size="sm" style={{ marginTop: 10, width: '100%' }} icon={<Icons.Check size={12}/>} onClick={handleMarkDone}>
              Marcar como feito
            </Btn>
          </div>

          {/* Quick replies */}
          <div>
            <div style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, letterSpacing: '0.12em', fontFamily: t.fontMono, marginBottom: 8 }}>
              RESPOSTAS RÁPIDAS
            </div>
            {quickReplies.map((qr) => (
              <button key={qr.id} onClick={() => {
                if (qr.attachmentUrl) {
                  // Se já tem anexo, envia imediatamente o anexo + texto!
                  handleSend(qr.text, qr.attachmentUrl);
                } else {
                  // Se não tem anexo, abre pra subir!
                  setUploadingQrId(qr.id);
                  if (fileInputRef.current) fileInputRef.current.click();
                }
              }} style={{
                display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                padding: '8px 10px', marginBottom: 5,
                background: isBloom ? t.bg : 'rgba(255,255,255,0.025)',
                border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
                borderRadius: t.radiusSm,
                fontSize: 12, color: t.text, textAlign: 'left', cursor: 'pointer'
              }}>
                <Icons.Lightning size={11} stroke={t.textMuted}/>
                <span style={{ flex: 1 }}>{qr.title}</span>
                {qr.attachmentUrl ? (
                   <span title="Anexo pronto!" style={{ color: t.green, display: 'flex' }}><Icons.Check size={14}/></span>
                ) : (
                   <span title="Anexar documento" style={{ color: t.textMuted, display: 'flex' }}><Icons.Paperclip size={14}/></span>
                )}
              </button>
            ))}
          </div>
        </div>
      </aside>
    </div>
  );
};

window.Chat = Chat;
