/* CRM Detail — visão 360 do cliente */

class CrmErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { hasError: false, errorMsg: '' }; }
  static getDerivedStateFromError(error) { return { hasError: true, errorMsg: error.message }; }
  render() {
    if (this.state.hasError) return <div style={{ padding: 40, color: 'red' }}>Erro Fatal no Perfil: {this.state.errorMsg}</div>;
    return this.props.children;
  }
}

const TimelineEvent = ({ icon, color, title, sub, time, last }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const I = Icons[icon];
  return (
    <div style={{ display: 'flex', gap: 14, position: 'relative', paddingBottom: last ? 0 : 20 }}>
      {!last && <div style={{
        position: 'absolute', left: 15, top: 32, bottom: 0, width: 2,
        background: isBloom ? t.border : 'rgba(255,255,255,0.08)',
      }}/>}
      <div style={{
        width: 32, height: 32, borderRadius: isBloom ? 8 : '50%', flexShrink: 0,
        background: color + (isBloom ? '' : '22'),
        border: isBloom ? `1.5px solid ${t.border}` : 'none',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: isBloom ? '2px 2px 0 0 #14131A' : 'none',
      }}>
        <I size={15} stroke={isBloom ? t.text : color}/>
      </div>
      <div style={{ flex: 1, paddingTop: 4 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
          <span style={{ fontSize: 13.5, fontWeight: 600, color: t.text, letterSpacing: '-0.01em' }}>{title}</span>
          <span style={{ fontSize: 10.5, color: t.textMuted, fontFamily: t.fontMono, flexShrink: 0 }}>{time}</span>
        </div>
        {sub && <div style={{ fontSize: 12, color: t.textMuted, marginTop: 3, lineHeight: 1.4 }}>{sub}</div>}
      </div>
    </div>
  );
};

const CrmDetailBase = ({ leadId = 1, onBack, onChat }) => {
  const t = useTheme();
  const { showToast } = useToast();
  const { prompt, confirm } = useDialog();
  const isBloom = t.name === 'BLOOM';
  
  const { data: apiLead, loading: loadingLead } = useLead(leadId);
  const { data: apiStages, loading: loadingStages } = usePipelineStages();
  const { data: apiTimeline } = useLeadTimeline(leadId);
  const { data: apiNotes } = useNotes(leadId);
  const { data: aiConfig } = useAiConfig();
  const addNote = useAddNote();

  const [isAddingNote, setIsAddingNote] = React.useState(false);
  const [newNoteBody, setNewNoteBody] = React.useState('');
  
  const handleSaveNote = async () => {
    if (!newNoteBody.trim()) return;
    await addNote(leadId, newNoteBody.trim());
    setNewNoteBody('');
    setIsAddingNote(false);
  };

  const lead = apiLead || (window.mockLeads && window.mockLeads.find(l => l.id === leadId)) || (window.mockLeads && window.mockLeads[0]) || null;
  const stagesPipeline = apiStages || window.stagesPipeline || [];
  const notes = apiNotes || [];

  if (loadingLead || loadingStages || !lead) {
    if (!loadingLead && !lead) {
      return (
        <div style={{ 
          padding: '60px 40px', 
          color: t.text, 
          textAlign: 'center', 
          display: 'flex', 
          flexDirection: 'column', 
          alignItems: 'center', 
          justifyContent: 'center', 
          minHeight: 400,
          background: isBloom ? '#FFFBF4' : 'rgba(255,255,255,0.01)',
          border: isBloom ? `2px solid ${t.border}` : `1px dashed ${t.border}`,
          borderRadius: t.radiusMd,
          margin: '24px auto',
          maxWidth: 600,
          boxShadow: isBloom ? '6px 6px 0 0 #14131A' : 'none'
        }}>
          <Icons.Fire size={48} stroke={t.orange} style={{ marginBottom: 20 }} />
          <h3 style={{ margin: '0 0 10px 0', fontFamily: t.fontDisplay, fontSize: 22, fontWeight: 700 }}>Lead não encontrado</h3>
          <p style={{ color: t.textMuted, fontSize: 13.5, margin: '0 0 24px 0', maxWidth: 400, lineHeight: 1.6 }}>
            O cliente com o ID #{leadId} não foi encontrado no banco de dados. Ele pode ter sido excluído ou a sincronização falhou.
          </p>
          <Btn variant="primary" onClick={onBack} icon={<Icons.ArrowLeft size={13}/>}>
            Voltar ao Pipeline
          </Btn>
        </div>
      );
    }
    return <div style={{ padding: 40, color: t.text, textAlign: 'center' }}>Carregando perfil...</div>;
  }

  return (
    <div style={{ padding: '24px 28px 40px', maxWidth: 1480, margin: '0 auto' }}>
      {/* Breadcrumb */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, fontSize: 12, color: t.textMuted, fontFamily: t.fontMono, letterSpacing: '0.04em' }}>
        <button onClick={onBack} style={{ background: 'none', border: 'none', color: t.textMuted, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'inherit', fontSize: 'inherit' }}>
          <Icons.ArrowLeft size={12}/> PIPELINE
        </button>
        <span>/</span>
        <span style={{ color: t.text }}>CLIENTE #{lead.id.toString().padStart(4, '0')}</span>
      </div>

      {/* Header card */}
      <Card style={{ padding: 26, marginBottom: 18, position: 'relative', overflow: 'hidden' }}>
        {/* decorative bg */}
        <div style={{
          position: 'absolute', top: -40, right: -40, width: 240, height: 240,
          background: `radial-gradient(circle, ${lead.color}22 0%, transparent 70%)`,
          pointerEvents: 'none',
        }}/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 20, position: 'relative' }}>
          <Avatar name={lead.avatar} color={lead.color} size={84} ai={lead.aiActive}/>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
              <h1 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em', color: t.text }}>
                {lead.name}
              </h1>
              <Pill soft={t.orangeSoft} color={isBloom ? t.text : t.orange}>
                <Icons.Fire size={11} stroke={isBloom ? t.text : t.orange}/> {lead.temp}
              </Pill>
            </div>
            <div style={{ display: 'flex', gap: 18, fontSize: 13, color: t.textMuted, fontFamily: t.fontMono, alignItems: 'center' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icons.Whatsapp size={13} stroke={t.green} fill={t.green}/> {lead.phone}
              </span>
              <span>·</span>
              <span>{lead.city}</span>
              <span>·</span>
              <span>via <strong style={{color: t.text}}>{lead.source}</strong></span>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end' }}>
            <ScoreRing value={lead.score} size={64}/>
            <span style={{ fontSize: 10, color: t.textMuted, fontFamily: t.fontMono, letterSpacing: '0.08em' }}>SCORE IA</span>
          </div>
        </div>

        {/* Action bar */}
        <div style={{ display: 'flex', gap: 8, marginTop: 22, paddingTop: 22,
          borderTop: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
        }}>
          <Btn variant="green" icon={<Icons.Whatsapp size={14} stroke="#fff" fill="#fff"/>} onClick={onChat}>
            Abrir conversa
          </Btn>
          <a href={`tel:${lead.phone}`} style={{ textDecoration: 'none' }}>
            <Btn variant="secondary" icon={<Icons.Phone size={14}/>}>Ligar</Btn>
          </a>
          <a href={`mailto:${lead.email || 'contato@exemplo.com'}?subject=Contato`} style={{ textDecoration: 'none' }}>
            <Btn variant="secondary" icon={<Icons.Mail size={14}/>}>E-mail</Btn>
          </a>
          <Btn variant="secondary" icon={<Icons.Calendar size={14}/>} onClick={async () => {
            const title = await prompt('Digite o título do compromisso (ex: Call de Apresentação):');
            if (!title) return;
            const dateStr = await prompt('Digite a data do compromisso (formato AAAA-MM-DD, ex: 2026-05-27):');
            if (!dateStr) return;
            const timeStr = await prompt('Digite o horário do compromisso (formato HH:MM, ex: 14:30):');
            if (!timeStr) return;
            
            const dateTime = new Date(`${dateStr}T${timeStr}:00`);
            if (isNaN(dateTime.getTime())) {
              showToast('Data ou hora inválida. Use os formatos especificados.', 'error');
              return;
            }
            
            try {
              const createAppointment = window.useCreateAppointment();
              await createAppointment({
                leadId: lead.id,
                title,
                date: dateTime.toISOString(),
                description: `Agendamento criado via perfil do cliente.`
              });
              showToast('Compromisso agendado com sucesso!', 'success');
              setTimeout(() => window.location.reload(), 1000);
            } catch (err) {
              showToast('Erro ao agendar compromisso.', 'error');
            }
          }}>Agendar</Btn>
          <Btn variant="secondary" icon={<Icons.Note size={14}/>} onClick={() => setIsAddingNote(true)}>Adicionar nota</Btn>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <Btn variant="secondary" icon={<Icons.Tag size={14}/>} onClick={async () => {
              const newTag = await prompt('Digite o nome da nova etiqueta:');
              if (newTag) {
                await window.FluxoEndpoints.leads.addTag(lead.id, newTag);
                window.location.reload();
              }
            }}>Etiquetar</Btn>
            <Btn variant="secondary" size="md" style={{ padding: 10 }} onClick={() => showToast('Mais opções em breve...')}>
              <Icons.More size={16}/>
            </Btn>
          </div>
        </div>
      </Card>

      {/* Stage progress */}
      <Card style={{ padding: 22, marginBottom: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
          <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
            Jornada do cliente
          </h3>
          <span style={{ fontSize: 12, color: t.textMuted, fontFamily: t.fontMono }}>etapa atual: <strong style={{ color: t.text }}>{stagesPipeline.find(s => s.id === lead.stage)?.label?.toUpperCase() || lead.stage}</strong></span>
        </div>
        <div style={{ display: 'flex', gap: 4 }}>
          {stagesPipeline.slice(0, 5).map((stage, i) => {
            const currentIdx = stagesPipeline.findIndex(s => s.id === lead.stage);
            const reached = i <= currentIdx;
            const isCurrent = i === currentIdx;
            return (
              <div 
                key={stage.id} 
                style={{ flex: 1, cursor: 'pointer' }}
                onClick={async () => {
                  try {
                    await window.FluxoEndpoints.leads.moveStage(lead.id, stage.id);
                    window.location.reload();
                  } catch (e) {
                    showToast('Erro ao mover lead.');
                  }
                }}
              >
                <div style={{
                  height: 8, borderRadius: 99,
                  background: reached ? stage.color : (isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.05)'),
                  border: isBloom ? `1.5px solid ${t.border}` : 'none',
                  position: 'relative',
                  transition: 'all 0.2s'
                }}>
                  {isCurrent && (
                    <span style={{
                      position: 'absolute', right: -6, top: -4, width: 16, height: 16, borderRadius: '50%',
                      background: stage.color, border: isBloom ? `1.5px solid ${t.border}` : `3px solid ${t.surface}`,
                      animation: 'pulse 2s ease-in-out infinite',
                    }}/>
                  )}
                </div>
                <div style={{ marginTop: 10, fontSize: 12, fontWeight: reached ? 600 : 500,
                  color: reached ? t.text : t.textMuted, letterSpacing: '-0.01em' }}>{stage.label}</div>
                <div style={{ fontSize: 10.5, color: t.textMuted, fontFamily: t.fontMono, marginTop: 2 }}>
                  {i === currentIdx ? 'em andamento' : i < currentIdx ? 'concluído' : '—'}
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      {/* Main grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
        {/* Left col */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* AI insights */}
          <Card style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
            <div style={{
              position: 'absolute', inset: 0,
              background: isBloom
                ? 'linear-gradient(135deg, #C9D5FF22 0%, transparent 50%)'
                : 'linear-gradient(135deg, rgba(91,141,239,0.05) 0%, transparent 50%)',
              pointerEvents: 'none',
            }}/>
            <div style={{ position: 'relative' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
                <div style={{
                  width: 30, height: 30, borderRadius: isBloom ? 8 : '50%',
                  background: `linear-gradient(135deg, ${t.green}, ${t.primary})`,
                  border: isBloom ? `1.5px solid ${t.border}` : 'none',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icons.Sparkles size={15} stroke="#fff"/>
                </div>
                <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                  Insights {aiConfig?.name ? `de ${aiConfig.name}` : 'da IA'}
                </h3>
                <Btn variant="primary" size="sm" style={{ marginLeft: 'auto' }} onClick={async (e) => {
                  const btn = e.currentTarget;
                  btn.textContent = "Analisando...";
                  btn.disabled = true;
                  try {
                    await window.FluxoEndpoints.leads.analyze(lead.id);
                    showToast('Insights gerados com sucesso!');
                    window.location.reload();
                  } catch(e) {
                    showToast('Erro ao analisar conversa.');
                  }
                }}>
                  Gerar Insights
                </Btn>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 14 }}>
                {[
                  { label: 'PROB. CONVERSÃO', value: (lead.conversionProb || 0) + '%', color: t.green, icon: 'TrendUp' },
                  { label: 'URGÊNCIA DETECTADA', value: lead.urgency || 'BAIXA', color: t.orange, icon: 'Fire' },
                  { label: 'CICLO ESPERADO', value: lead.expectedCycle || '~24h', color: t.primary, icon: 'Clock' },
                  { label: 'TICKET ESPERADO', value: lead.expectedTicket ? 'R$ ' + (lead.expectedTicket / 100).toFixed(2) : 'R$ 0,00', color: t.purple, icon: 'Money' },
                ].map((m, i) => {
                  const I = Icons[m.icon];
                  return (
                    <div key={i} style={{
                      padding: 14, borderRadius: t.radiusMd,
                      background: isBloom ? t.bg : 'rgba(255,255,255,0.03)',
                      border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 8,
                        fontSize: 9, fontWeight: 700, color: t.textMuted, letterSpacing: '0.1em', fontFamily: t.fontMono }}>
                        <I size={11} stroke={m.color}/> {m.label}
                      </div>
                      <div style={{ fontFamily: t.fontDisplay, fontSize: 24, fontWeight: 700, color: t.text, letterSpacing: '-0.02em', lineHeight: 1 }}>
                        {m.value}
                      </div>
                    </div>
                  );
                })}
              </div>
              <div style={{
                padding: 14, 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',
              }}>
                <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 }}>PRINCIPAIS OBJEÇÕES DO CLIENTE</span>
                </div>
                <div style={{ fontSize: 14, color: t.text, lineHeight: 1.5, fontWeight: 500 }}>
                  {(() => {
                    let objList = [];
                    try { objList = typeof lead.objections === 'string' ? JSON.parse(lead.objections) : (lead.objections || []); } catch(e) {}
                    return objList.length > 0 ? (
                      <ul style={{ margin: 0, paddingLeft: 20 }}>
                        {objList.map((o, i) => {
                          const text = typeof o === 'object' && o !== null ? o.obj : o;
                          return <li key={i}>{text}</li>;
                        })}
                      </ul>
                    ) : 'Nenhuma objeção detectada.';
                  })()}
                </div>
              </div>
            </div>
          </Card>

          {/* Conversation summary */}
          <Card style={{ padding: 22 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
              <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                Resumo da conversa
              </h3>
              <div style={{ display: 'flex', gap: 8 }}>
                <Btn variant="ghost" size="sm" onClick={async (e) => {
                  const btn = e.currentTarget;
                  btn.textContent = "Analisando...";
                  btn.disabled = true;
                  try {
                    await window.FluxoEndpoints.leads.analyze(lead.id);
                    showToast('Resumo gerado com sucesso!');
                    window.location.reload();
                  } catch(e) {
                    showToast('Erro ao analisar conversa.');
                    btn.textContent = "Regerar";
                    btn.disabled = false;
                  }
                }}>Regerar</Btn>
                <Btn variant="ghost" size="sm" icon={<Icons.Send size={11}/>} onClick={() => {
                  let text = `CLIENTE: ${lead.name}\nTELEFONE: ${lead.phone}\nETAPA: ${lead.stage}\n\n`;
                  text += `--- RESUMO ---\n${lead.summary || 'Nenhum resumo'}\n\n`;
                  text += `--- OBJEÇÕES ---\n`;
                  try {
                    const objs = typeof lead.objections === 'string' ? JSON.parse(lead.objections) : (lead.objections || []);
                    if (objs.length === 0) text += 'Nenhuma objeção\n';
                    objs.forEach(o => { text += `- ${typeof o === 'object' ? o.obj : o}\n`; });
                  } catch (e) {
                    text += lead.objections + '\n';
                  }
                  const blob = new Blob([text], { type: 'text/plain' });
                  const url = URL.createObjectURL(blob);
                  const a = document.createElement('a');
                  a.href = url;
                  a.download = `resumo_${lead.name.replace(/\s+/g, '_')}.txt`;
                  a.click();
                  URL.revokeObjectURL(url);
                }}>Exportar</Btn>
              </div>
            </div>
            <div style={{ fontSize: 14, color: t.text, lineHeight: 1.65, marginBottom: 16 }}>
              {lead.summary}
            </div>
            <div style={{ display: 'flex', gap: 16, paddingTop: 14,
              borderTop: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
              fontSize: 12, color: t.textMuted, fontFamily: t.fontMono,
            }}>
              <span>12 mensagens trocadas</span>
              <span>·</span>
              <span>4 áudios</span>
              <span>·</span>
              <span>2 imagens</span>
              <span>·</span>
              <span style={{ marginLeft: 'auto' }}>tempo médio resp: <strong style={{color: t.text}}>6s</strong></span>
            </div>
          </Card>

          {/* Notes */}
          <Card style={{ padding: 22 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
              <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                Notas internas
              </h3>
              {!isAddingNote && (
                <Btn variant="ghost" size="sm" icon={<Icons.Plus size={12}/>} onClick={() => setIsAddingNote(true)}>Nova nota</Btn>
              )}
            </div>
            
            {isAddingNote && (
              <div style={{ marginBottom: 14 }}>
                <textarea 
                  autoFocus
                  value={newNoteBody}
                  onChange={e => setNewNoteBody(e.target.value)}
                  placeholder="Escreva sua nota aqui..."
                  style={{
                    width: '100%', padding: '10px 12px',
                    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',
                    resize: 'vertical', minHeight: 60, fontFamily: 'inherit', marginBottom: 8
                  }}
                />
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                  <Btn variant="ghost" size="sm" onClick={() => setIsAddingNote(false)}>Cancelar</Btn>
                  <Btn variant="primary" size="sm" onClick={handleSaveNote}>Salvar Nota</Btn>
                </div>
              </div>
            )}

            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {notes.length === 0 && !isAddingNote ? (
                <div style={{ fontSize: 13, color: t.textMuted, fontStyle: 'italic' }}>Nenhuma nota adicionada ainda.</div>
              ) : (
                notes.map(note => (
                  <div key={note.id} style={{
                    padding: 14, borderRadius: t.radiusMd,
                    background: isBloom ? '#FFE6B8' : 'rgba(245,158,11,0.08)',
                    border: isBloom ? `1.5px solid ${t.border}` : `1px solid rgba(245,158,11,0.2)`,
                    boxShadow: isBloom ? '2px 2px 0 0 #14131A' : 'none',
                    fontSize: 13.5, color: t.text, lineHeight: 1.5,
                  }}>
                    {note.body}
                    <div style={{ marginTop: 10, fontSize: 11, color: t.textMuted, fontFamily: t.fontMono }}>
                      {note.author?.name || 'Admin'} · {new Date(note.createdAt).toLocaleString('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}
                    </div>
                  </div>
                ))
              )}
            </div>
          </Card>
        </div>

        {/* Right col */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* Timeline */}
          <Card style={{ padding: 22 }}>
            <h3 style={{ margin: '0 0 18px', fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Linha do tempo
            </h3>
            {(!apiTimeline || apiTimeline.length === 0) ? (
              <div style={{ fontSize: 13, color: t.textMuted, fontStyle: 'italic' }}>Nenhuma atividade registrada ainda.</div>
            ) : (
              apiTimeline.map((ev, i) => (
                <TimelineEvent 
                  key={ev.id || i}
                  icon={ev.icon} 
                  color={ev.color} 
                  title={ev.title} 
                  sub={ev.sub} 
                  time={ev.time} 
                  last={i === apiTimeline.length - 1}
                />
              ))
            )}
          </Card>

          {/* Deals/Files */}
          <Card style={{ padding: 22 }}>
            <h3 style={{ margin: '0 0 14px', fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Negociações
            </h3>
            <div style={{
              padding: 14, borderRadius: t.radiusMd,
              background: isBloom ? t.bg : 'rgba(255,255,255,0.03)',
              border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text }}>{lead.tags && lead.tags.length > 0 ? (Array.isArray(lead.tags) ? lead.tags[0] : (typeof lead.tags === 'string' ? JSON.parse(lead.tags)[0] : 'Produto em interesse')) : 'Oportunidade em andamento'}</div>
                  <div style={{ fontSize: 11, color: t.textMuted, fontFamily: t.fontMono, marginTop: 2 }}>NEGÓCIO #{lead.id.toString().padStart(4, '0')}</div>
                </div>
                <Pill soft={t.orangeSoft} color={isBloom ? t.text : t.orange}>{lead.temp || 'morno'}</Pill>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8 }}>
                <span style={{ fontSize: 11, color: t.textMuted, fontFamily: t.fontMono }}>VALOR</span>
                <span style={{ fontFamily: t.fontDisplay, fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                  R$ {((lead.value_cents || 0)/100).toLocaleString('pt-BR')}
                </span>
              </div>
            </div>
          </Card>

          {/* Tags */}
          <Card style={{ padding: 22 }}>
            <h3 style={{ margin: '0 0 14px', fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Etiquetas
            </h3>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {(() => {
                let tagsArray = [];
                try {
                  tagsArray = Array.isArray(lead.tags) ? lead.tags : (lead.tags ? JSON.parse(lead.tags) : []);
                } catch (e) {
                  tagsArray = [lead.tags]; // fallback to single string if invalid JSON
                }
                if (!Array.isArray(tagsArray)) tagsArray = [];
                
                return tagsArray.map((tag, idx) => {
                  return (
                    <div key={idx} style={{ position: 'relative' }}>
                      <Pill soft={t.primarySoft} color={t.text} style={{ cursor: 'pointer', paddingRight: 24 }}>{tag}</Pill>
                      <Icons.X size={10} style={{ position: 'absolute', right: 8, top: 'calc(50% - 5px)', cursor: 'pointer', color: t.textMuted }}
                        onClick={async () => {
                          if (await confirm(`Remover etiqueta "${tag}"?`)) {
                            await window.FluxoEndpoints.leads.removeTag(lead.id, tag);
                            window.location.reload();
                          }
                        }}
                      />
                    </div>
                  );
                });
              })()}
              <button onClick={async () => {
                const newTag = await prompt('Digite o nome da nova etiqueta:');
                if (newTag) {
                  await window.FluxoEndpoints.leads.addTag(lead.id, newTag);
                  window.location.reload();
                }
              }} style={{
                padding: '4px 10px', borderRadius: 99, fontSize: 12,
                background: 'transparent',
                border: isBloom ? `1.5px dashed ${t.border}` : `1px dashed ${t.border}`,
                color: t.textMuted, cursor: 'pointer',
              }}>+ adicionar</button>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

window.CrmDetail = (props) => <CrmErrorBoundary><CrmDetailBase {...props} /></CrmErrorBoundary>;
