// ─── CRM Sucesso 8! — Componentes Compartilhados + Modal ─────────────────────
(function () {
const {
  FUNIL_ETAPAS, PRODUTOS, ORIGENS, RESPONSAVEIS, TODAY,
  getEtapa, isOverdue, isDueToday, fmtDate, genId
} = window.CRMData;

// ── EtapaTag ──────────────────────────────────────────────────────────────────
function EtapaTag({ etapaId, small }) {
  const e = getEtapa(etapaId);
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: small ? '2px 8px' : '3px 10px',
      borderRadius: 20, fontSize: small ? 11 : 12, fontWeight: 600,
      backgroundColor: e.bg, color: e.color, border: `1px solid ${e.color}28`,
      whiteSpace: 'nowrap',
    }}>{e.label}</span>
  );
}

// ── ProdutoBadge ──────────────────────────────────────────────────────────────
function ProdutoBadge({ ecossistema, small }) {
  const eco = PRODUTOS[ecossistema];
  if (!eco) return null;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: small ? '2px 7px' : '3px 9px',
      borderRadius: 6, fontSize: small ? 10 : 11, fontWeight: 700,
      backgroundColor: eco.bg, color: eco.color, border: `1px solid ${eco.border}`,
      whiteSpace: 'nowrap', letterSpacing: '0.02em',
    }}>{small ? eco.short : eco.label}</span>
  );
}

// ── OrigemTag ─────────────────────────────────────────────────────────────────
function OrigemTag({ origem }) {
  const o = ORIGENS.find(x => x.id === origem);
  if (!o) return null;
  const colors = {
    instagram: { color: '#C13584', bg: '#FDF0F7' },
    linkedin:  { color: '#0A66C2', bg: '#EBF5FB' },
    indicacao: { color: '#16A34A', bg: '#DCFCE7' },
    networking:{ color: '#7C3AED', bg: '#EDE9FE' },
    outro:     { color: '#64748B', bg: '#F1F5F9' },
  };
  const s = colors[origem] || colors.outro;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', padding: '2px 8px',
      borderRadius: 4, fontSize: 11, fontWeight: 600,
      backgroundColor: s.bg, color: s.color,
    }}>{o.label}</span>
  );
}

// ── FollowUpBadge ─────────────────────────────────────────────────────────────
function FollowUpBadge({ data, hora }) {
  if (!data) return null;
  const over = isOverdue(data);
  const today = isDueToday(data);
  if (!over && !today) return null;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 3,
      padding: '2px 7px', borderRadius: 4, fontSize: 11, fontWeight: 700,
      backgroundColor: over ? '#FEE2E2' : '#FEF9C3',
      color: over ? '#DC2626' : '#B45309',
    }}>
      {over ? '⚠ Atrasado' : '⏰ Hoje'}{hora ? ` ${hora}` : ''}
    </span>
  );
}

// ── Avatar ────────────────────────────────────────────────────────────────────
function Avatar({ nome, size }) {
  const initials = (nome || '?').split(' ').slice(0, 2).map(w => w[0]).join('').toUpperCase();
  const sz = size || 32;
  const palette = ['#D97706','#7C3AED','#0891B2','#16A34A','#DC2626','#C026D3','#0369A1','#B45309'];
  const bg = palette[(nome || '').charCodeAt(0) % palette.length];
  return (
    <div style={{
      width: sz, height: sz, borderRadius: '50%', backgroundColor: bg, color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: sz * 0.37, fontWeight: 700, flexShrink: 0, fontFamily: 'inherit',
      userSelect: 'none',
    }}>{initials}</div>
  );
}

// ── UpsellBadge ───────────────────────────────────────────────────────────────
function UpsellBadge() {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 2,
      padding: '2px 6px', borderRadius: 4, fontSize: 10, fontWeight: 800,
      backgroundColor: '#FFFBEB', color: '#B45309',
      border: '1px solid #FCD34D', letterSpacing: '0.04em', textTransform: 'uppercase',
    }}>↑ UPSELL</span>
  );
}

// ── ConfirmDialog ─────────────────────────────────────────────────────────────
function ConfirmDialog({ message, onConfirm, onCancel }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      backgroundColor: 'rgba(0,0,0,0.5)',
    }}>
      <div style={{
        background: '#fff', borderRadius: 14, padding: 28, maxWidth: 380, width: '90%',
        boxShadow: '0 20px 60px rgba(0,0,0,0.22)',
      }}>
        <p style={{ margin: '0 0 22px', fontSize: 15, color: '#1C1A12', lineHeight: 1.6 }}>{message}</p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <button onClick={onCancel} style={{
            padding: '8px 18px', borderRadius: 8, border: '1px solid #EAE4D2',
            background: '#fff', cursor: 'pointer', fontSize: 14, color: '#5C5440', fontFamily: 'inherit',
          }}>Cancelar</button>
          <button onClick={onConfirm} style={{
            padding: '8px 18px', borderRadius: 8, border: 'none',
            background: '#DC2626', color: '#fff', cursor: 'pointer', fontSize: 14,
            fontWeight: 700, fontFamily: 'inherit',
          }}>Confirmar</button>
        </div>
      </div>
    </div>
  );
}

// ─── Lead Modal ───────────────────────────────────────────────────────────────
const TIPO_HISTORICO = {
  criacao:  { color: '#16A34A', bg: '#DCFCE7', icon: '✦' },
  etapa:    { color: '#2563EB', bg: '#DBEAFE', icon: '→' },
  nota:     { color: '#D97706', bg: '#FEF3C7', icon: '✍' },
  followup: { color: '#7C3AED', bg: '#EDE9FE', icon: '⏰' },
};

function LeadModal({ lead, isNew, onSave, onClose, onDelete, onCreateUpsell }) {
  const defaults = {
    id: genId(), nome: '', email: '', whatsapp: '', instagram: '', linkedin: '',
    cpf: '', site: '', empresa: '', origem: '', origemDetalhe: '',
    ecossistema: '', produto: '', etapa: 'lead', valor: 0,
    responsavel: RESPONSAVEIS[0], followUpData: '', followUpHora: '',
    isUpsell: false, originalLeadId: null, criadoEm: TODAY, notas: '', historico: [], opcoes: [],
  };
  const [form, setForm] = React.useState(() => ({ ...defaults, ...(lead || {}) }));
  const [tab, setTab] = React.useState('info');
  const [confirmDel, setConfirmDel] = React.useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // Opções de proposta (vários valores)
  const addOpcao = () => set('opcoes', [...(form.opcoes || []), { nome: '', valor: 0 }]);
  const updateOpcao = (i, k, v) => set('opcoes', (form.opcoes || []).map((o, idx) => idx === i ? { ...o, [k]: v } : o));
  const removeOpcao = (i) => set('opcoes', (form.opcoes || []).filter((_, idx) => idx !== i));
  const useOpcaoValor = (v) => set('valor', Number(v) || 0);

  // Apagar um item do histórico/nota
  const handleDeleteHist = (id) => set('historico', (form.historico || []).filter(h => h.id !== id));

  // Marcar follow-up como feito (registra no histórico e limpa o agendamento)
  const markFollowupDone = () => {
    setForm(f => ({
      ...f, followUpData: '', followUpHora: '',
      historico: [...(f.historico || []), { id: genId(), data: TODAY, tipo: 'followup', descricao: `Follow-up concluído (estava previsto para ${fmtDate(f.followUpData)})` }],
    }));
  };

  const produtos = form.ecossistema ? (PRODUTOS[form.ecossistema]?.itens || []) : [];

  const canUpsell = !isNew && !form.isUpsell &&
    ['contrato_assinado','servico_andamento','servico_finalizado'].includes(form.etapa);

  const handleSave = () => {
    if (!form.nome.trim()) { alert('O nome é obrigatório.'); return; }
    let updated = { ...form };
    if (!isNew && lead && form.etapa !== lead.etapa) {
      updated.historico = [...(updated.historico || []), {
        id: genId(), data: TODAY, tipo: 'etapa',
        descricao: `Etapa alterada para: ${getEtapa(form.etapa).label}`,
      }];
    }
    onSave(updated);
  };

  const handleAddNota = () => {
    const nota = prompt('Adicionar nota:');
    if (nota?.trim()) {
      set('historico', [...(form.historico || []), {
        id: genId(), data: TODAY, tipo: 'nota', descricao: nota.trim(),
      }]);
    }
  };

  const inp = {
    width: '100%', padding: '8px 12px', borderRadius: 8, boxSizing: 'border-box',
    border: '1px solid #E8E3D5', fontSize: 14, color: '#1C1A12', background: '#FAFAF6',
    outline: 'none', fontFamily: 'inherit', transition: 'border-color 0.15s',
  };
  const lbl = { display: 'block', fontSize: 12, fontWeight: 600, color: '#5C5440', marginBottom: 4 };
  const fld = { marginBottom: 14 };
  const sec = { fontSize: 11, fontWeight: 700, color: '#8C8470', letterSpacing: '0.08em',
    textTransform: 'uppercase', margin: '6px 0 12px' };

  return (
    <div
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000, display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        backgroundColor: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(3px)',
      }}
    >
      <div style={{
        background: '#fff', borderRadius: 16, width: '92vw', maxWidth: 960,
        maxHeight: '94vh', overflow: 'hidden', display: 'flex', flexDirection: 'column',
        boxShadow: '0 24px 80px rgba(0,0,0,0.22)',
      }}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: '16px 22px',
          borderBottom: '1px solid #EAE4D2', background: '#FFFDF8', flexShrink: 0,
        }}>
          <Avatar nome={form.nome || '?'} size={42} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 18, fontWeight: 800, color: '#1C1A12', marginBottom: 4, fontFamily: "'Bricolage Grotesque', sans-serif" }}>
              {form.nome || (isNew ? 'Novo Lead' : '—')}
            </div>
            <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
              <EtapaTag etapaId={form.etapa} small />
              {form.ecossistema && <ProdutoBadge ecossistema={form.ecossistema} small />}
              {form.isUpsell && <UpsellBadge />}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
            {canUpsell && (
              <button onClick={() => onCreateUpsell(form)} style={{
                padding: '7px 14px', borderRadius: 8, border: '1px solid #F0CC60',
                background: '#FFFBEB', color: '#92600A', cursor: 'pointer',
                fontSize: 13, fontWeight: 700, fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
              }}>↑ Criar Upsell</button>
            )}
            {!isNew && (
              <button onClick={() => setConfirmDel(true)} style={{
                padding: '7px 12px', borderRadius: 8, border: '1px solid #FECACA',
                background: '#FFF5F5', color: '#DC2626', cursor: 'pointer', fontSize: 13, fontFamily: 'inherit',
              }}>Excluir</button>
            )}
            <button onClick={onClose} style={{
              width: 36, height: 36, borderRadius: 8, border: '1px solid #EAE4D2',
              background: '#fff', cursor: 'pointer', fontSize: 20, color: '#8C8470', lineHeight: 1,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>×</button>
          </div>
        </div>

        {/* Body */}
        <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>

          {/* Left: form */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '18px 22px', borderRight: '1px solid #EAE4D2' }}>
            <div style={{ display: 'flex', gap: 0, marginBottom: 18, borderBottom: '1px solid #EAE4D2' }}>
              {[{id:'info',label:'Informações'},{id:'historico',label:'Histórico'}].map(t => (
                <button key={t.id} onClick={() => setTab(t.id)} style={{
                  padding: '9px 18px', border: 'none', background: 'transparent', cursor: 'pointer',
                  fontSize: 14, fontWeight: tab===t.id ? 700 : 500, fontFamily: 'inherit',
                  color: tab===t.id ? '#B8860B' : '#8C8470',
                  borderBottom: tab===t.id ? '2px solid #B8860B' : '2px solid transparent',
                  marginBottom: -1,
                }}>{t.label}</button>
              ))}
            </div>

            {tab === 'info' && (
              <>
                <p style={sec}>Dados Pessoais</p>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div style={{ gridColumn: '1/-1', ...fld }}>
                    <label style={lbl}>Nome Completo *</label>
                    <input style={inp} value={form.nome} onChange={e => set('nome', e.target.value)} placeholder="Nome completo" />
                  </div>
                  <div style={fld}>
                    <label style={lbl}>E-mail</label>
                    <input style={inp} type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="email@exemplo.com" />
                  </div>
                  <div style={fld}>
                    <label style={lbl}>WhatsApp</label>
                    <input style={inp} value={form.whatsapp} onChange={e => set('whatsapp', e.target.value)} placeholder="11999999999" />
                  </div>
                  <div style={fld}>
                    <label style={lbl}>CPF</label>
                    <input style={inp} value={form.cpf} onChange={e => set('cpf', e.target.value)} placeholder="000.000.000-00" />
                  </div>
                  <div style={fld}>
                    <label style={lbl}>Empresa</label>
                    <input style={inp} value={form.empresa} onChange={e => set('empresa', e.target.value)} placeholder="Nome da empresa" />
                  </div>
                </div>

                <p style={{ ...sec, marginTop: 4 }}>Redes & Presença Digital</p>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div style={fld}>
                    <label style={lbl}>Instagram</label>
                    <input style={inp} value={form.instagram} onChange={e => set('instagram', e.target.value)} placeholder="@perfil" />
                  </div>
                  <div style={fld}>
                    <label style={lbl}>LinkedIn</label>
                    <input style={inp} value={form.linkedin} onChange={e => set('linkedin', e.target.value)} placeholder="linkedin.com/in/..." />
                  </div>
                  <div style={{ gridColumn: '1/-1', ...fld }}>
                    <label style={lbl}>Site</label>
                    <input style={inp} value={form.site} onChange={e => set('site', e.target.value)} placeholder="www.exemplo.com.br" />
                  </div>
                </div>

                <p style={{ ...sec, marginTop: 4 }}>Origem do Lead</p>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div style={fld}>
                    <label style={lbl}>Canal de Entrada</label>
                    <select style={{ ...inp, cursor: 'pointer' }} value={form.origem} onChange={e => { set('origem', e.target.value); set('origemDetalhe',''); }}>
                      <option value="">Selecione...</option>
                      {ORIGENS.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
                    </select>
                  </div>
                  {form.origem && ORIGENS.find(o => o.id === form.origem)?.hasDetail && (
                    <div style={fld}>
                      <label style={lbl}>
                        {form.origem === 'indicacao' ? 'Indicado por' : form.origem === 'networking' ? 'Onde aconteceu?' : 'Detalhe'}
                      </label>
                      <input style={inp} value={form.origemDetalhe} onChange={e => set('origemDetalhe', e.target.value)}
                        placeholder={ORIGENS.find(o => o.id === form.origem)?.placeholder} />
                    </div>
                  )}
                </div>

                <p style={{ ...sec, marginTop: 4 }}>Produto & Oportunidade</p>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div style={fld}>
                    <label style={lbl}>Ecossistema</label>
                    <select style={{ ...inp, cursor: 'pointer' }} value={form.ecossistema} onChange={e => { set('ecossistema', e.target.value); set('produto',''); }}>
                      <option value="">Selecione...</option>
                      <option value="voz">Método V.O.Z.</option>
                      <option value="automatiza">Automatiza Isso</option>
                    </select>
                  </div>
                  <div style={fld}>
                    <label style={lbl}>Produto</label>
                    <select style={{ ...inp, cursor: 'pointer' }} value={form.produto} onChange={e => set('produto', e.target.value)} disabled={!form.ecossistema}>
                      <option value="">Selecione...</option>
                      {produtos.map(p => <option key={p} value={p}>{p}</option>)}
                    </select>
                  </div>
                  <div style={fld}>
                    <label style={lbl}>Valor principal (R$)</label>
                    <input style={inp} type="number" min="0" value={form.valor || ''} onChange={e => set('valor', parseFloat(e.target.value) || 0)} placeholder="0" />
                  </div>
                </div>

                <p style={{ ...sec, marginTop: 4 }}>Opções de proposta <span style={{ textTransform: 'none', fontWeight: 500, color: '#B0A890' }}>(quando há mais de um valor)</span></p>
                {(form.opcoes || []).map((op, i) => (
                  <div key={i} style={{ display: 'flex', gap: 8, marginBottom: 8, alignItems: 'center' }}>
                    <input style={{ ...inp, flex: 2 }} value={op.nome} onChange={e => updateOpcao(i, 'nome', e.target.value)} placeholder="Descrição (ex: Plano Essencial)" />
                    <input style={{ ...inp, flex: 1 }} type="number" min="0" value={op.valor || ''} onChange={e => updateOpcao(i, 'valor', parseFloat(e.target.value) || 0)} placeholder="Valor" />
                    <button type="button" onClick={() => useOpcaoValor(op.valor)} title="Usar como valor principal" style={{ flexShrink: 0, padding: '8px 10px', borderRadius: 8, border: '1px solid #DCFCE7', background: '#F0FDF4', color: '#16A34A', cursor: 'pointer', fontSize: 13, fontWeight: 700 }}>✓</button>
                    <button type="button" onClick={() => removeOpcao(i)} title="Remover opção" style={{ flexShrink: 0, padding: '8px 10px', borderRadius: 8, border: '1px solid #FECACA', background: '#FFF5F5', color: '#DC2626', cursor: 'pointer', fontSize: 14 }}>×</button>
                  </div>
                ))}
                <div style={fld}>
                  <button type="button" onClick={addOpcao} style={{ padding: '7px 14px', borderRadius: 8, border: '1px dashed #D4C89A', background: 'transparent', color: '#92600A', cursor: 'pointer', fontSize: 13, fontWeight: 600, fontFamily: 'inherit' }}>+ Adicionar opção</button>
                  {(form.opcoes || []).length > 0 && (
                    <span style={{ marginLeft: 12, fontSize: 12, color: '#8C8470' }}>O ✓ define aquela opção como o "Valor principal".</span>
                  )}
                </div>

                <p style={{ ...sec, marginTop: 4 }}>Gestão & Follow-up</p>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                  <div style={fld}>
                    <label style={lbl}>Responsável</label>
                    <select style={{ ...inp, cursor: 'pointer' }} value={form.responsavel} onChange={e => set('responsavel', e.target.value)}>
                      {RESPONSAVEIS.map(r => <option key={r} value={r}>{r}</option>)}
                    </select>
                  </div>
                  <div style={fld}>
                    <label style={lbl}>Data do Follow-up</label>
                    <input style={inp} type="date" value={form.followUpData} onChange={e => set('followUpData', e.target.value)} />
                  </div>
                  <div style={fld}>
                    <label style={lbl}>Horário</label>
                    <input style={inp} type="time" value={form.followUpHora} onChange={e => set('followUpHora', e.target.value)} />
                  </div>
                </div>

                <p style={{ ...sec, marginTop: 4 }}>Notas</p>
                <div style={fld}>
                  <textarea style={{ ...inp, height: 90, resize: 'vertical', lineHeight: 1.6 }}
                    value={form.notas} onChange={e => set('notas', e.target.value)}
                    placeholder="Observações sobre este lead..." />
                </div>
              </>
            )}

            {tab === 'historico' && (
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                  <span style={{ fontSize: 13, color: '#5C5440', fontWeight: 600 }}>
                    {(form.historico || []).length} registro(s)
                  </span>
                  <button onClick={handleAddNota} style={{
                    padding: '6px 14px', borderRadius: 8, border: '1px solid #F0CC60',
                    background: '#FFFBEB', color: '#92600A', cursor: 'pointer',
                    fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
                  }}>+ Adicionar Nota</button>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  {(form.historico || []).slice().reverse().map((h, i, arr) => {
                    const t = TIPO_HISTORICO[h.tipo] || TIPO_HISTORICO.nota;
                    return (
                      <div key={h.id || i} style={{ display: 'flex', gap: 12, paddingBottom: 16, position: 'relative' }}>
                        {i < arr.length - 1 && (
                          <div style={{ position: 'absolute', left: 14, top: 30, bottom: 0, width: 2, background: '#EAE4D2' }} />
                        )}
                        <div style={{
                          width: 30, height: 30, borderRadius: '50%', flexShrink: 0, zIndex: 1,
                          background: t.bg, color: t.color, display: 'flex',
                          alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700,
                        }}>{t.icon}</div>
                        <div style={{ flex: 1, paddingTop: 4 }}>
                          <div style={{ fontSize: 13, color: '#1C1A12', lineHeight: 1.5 }}>{h.descricao}</div>
                          <div style={{ fontSize: 11, color: '#8C8470', marginTop: 3 }}>{fmtDate(h.data)}</div>
                        </div>
                        <button onClick={() => handleDeleteHist(h.id)} title="Apagar" style={{ flexShrink: 0, alignSelf: 'flex-start', border: 'none', background: 'transparent', color: '#C4BAA8', cursor: 'pointer', fontSize: 16, lineHeight: 1, padding: '2px 4px' }}>×</button>
                      </div>
                    );
                  })}
                  {!(form.historico?.length) && (
                    <p style={{ color: '#8C8470', fontSize: 13, textAlign: 'center', padding: '32px 0' }}>
                      Nenhum registro ainda.
                    </p>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Right: stage + quick info */}
          <div style={{ width: 240, flexShrink: 0, overflowY: 'auto', padding: '18px 16px', background: '#FAFAF6' }}>
            <p style={{ fontSize: 11, fontWeight: 700, color: '#8C8470', letterSpacing: '0.08em',
              textTransform: 'uppercase', marginBottom: 10 }}>Etapa do Funil</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 3, marginBottom: 22 }}>
              {FUNIL_ETAPAS.map(e => (
                <button key={e.id} onClick={() => set('etapa', e.id)} style={{
                  padding: '8px 11px', borderRadius: 8, cursor: 'pointer',
                  border: `1px solid ${form.etapa===e.id ? e.color : '#EAE4D2'}`,
                  background: form.etapa===e.id ? e.bg : '#fff',
                  color: form.etapa===e.id ? e.color : '#5C5440',
                  fontSize: 12, fontWeight: form.etapa===e.id ? 700 : 500,
                  textAlign: 'left', fontFamily: 'inherit', transition: 'all 0.1s',
                }}>{e.label}</button>
              ))}
            </div>

            {form.followUpData && (
              <>
                <p style={{ fontSize: 11, fontWeight: 700, color: '#8C8470', letterSpacing: '0.08em',
                  textTransform: 'uppercase', marginBottom: 8 }}>Follow-up</p>
                <div style={{
                  padding: '11px 12px', borderRadius: 10, marginBottom: 20,
                  background: isOverdue(form.followUpData) ? '#FEE2E2' : isDueToday(form.followUpData) ? '#FEF9C3' : '#F0F9FF',
                  border: `1px solid ${isOverdue(form.followUpData) ? '#FECACA' : isDueToday(form.followUpData) ? '#FDE68A' : '#BAE6FD'}`,
                }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: isOverdue(form.followUpData) ? '#DC2626' : isDueToday(form.followUpData) ? '#B45309' : '#0369A1' }}>
                    {isOverdue(form.followUpData) ? '⚠ Atrasado!' : isDueToday(form.followUpData) ? '⏰ Hoje' : '📅 Agendado'}
                  </div>
                  <div style={{ fontSize: 12, color: '#5C5440', marginTop: 2 }}>
                    {fmtDate(form.followUpData)}{form.followUpHora ? ` às ${form.followUpHora}` : ''}
                  </div>
                </div>
                <button onClick={markFollowupDone} style={{ width: '100%', marginBottom: 20, padding: '8px', borderRadius: 8, border: '1px solid #DCFCE7', background: '#F0FDF4', color: '#16A34A', cursor: 'pointer', fontSize: 12, fontWeight: 700, fontFamily: 'inherit' }}>✓ Follow-up feito</button>
              </>
            )}

            {form.valor > 0 && (
              <>
                <p style={{ fontSize: 11, fontWeight: 700, color: '#8C8470', letterSpacing: '0.08em',
                  textTransform: 'uppercase', marginBottom: 8 }}>Valor</p>
                <div style={{ fontSize: 22, fontWeight: 800, color: '#B8860B', marginBottom: 20,
                  fontVariantNumeric: 'tabular-nums' }}>
                  R$ {Number(form.valor).toLocaleString('pt-BR')}
                </div>
              </>
            )}

            {form.responsavel && (
              <>
                <p style={{ fontSize: 11, fontWeight: 700, color: '#8C8470', letterSpacing: '0.08em',
                  textTransform: 'uppercase', marginBottom: 8 }}>Responsável</p>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 20 }}>
                  <Avatar nome={form.responsavel} size={26} />
                  <span style={{ fontSize: 13, fontWeight: 600, color: '#1C1A12' }}>{form.responsavel}</span>
                </div>
              </>
            )}

            {form.origem && (
              <>
                <p style={{ fontSize: 11, fontWeight: 700, color: '#8C8470', letterSpacing: '0.08em',
                  textTransform: 'uppercase', marginBottom: 8 }}>Origem</p>
                <div style={{ marginBottom: 20 }}>
                  <OrigemTag origem={form.origem} />
                  {form.origemDetalhe && (
                    <div style={{ fontSize: 11, color: '#8C8470', marginTop: 5, lineHeight: 1.4 }}>
                      {form.origemDetalhe}
                    </div>
                  )}
                </div>
              </>
            )}
          </div>
        </div>

        {/* Footer */}
        <div style={{
          display: 'flex', justifyContent: 'flex-end', gap: 10,
          padding: '13px 22px', borderTop: '1px solid #EAE4D2', background: '#FFFDF8', flexShrink: 0,
        }}>
          <button onClick={onClose} style={{
            padding: '9px 20px', borderRadius: 10, border: '1px solid #EAE4D2',
            background: '#fff', cursor: 'pointer', fontSize: 14, color: '#5C5440', fontFamily: 'inherit',
          }}>Cancelar</button>
          <button onClick={handleSave} style={{
            padding: '9px 24px', borderRadius: 10, border: 'none',
            background: '#B8860B', color: '#fff', cursor: 'pointer',
            fontSize: 14, fontWeight: 700, fontFamily: 'inherit',
          }}>{isNew ? '+ Criar Lead' : 'Salvar'}</button>
        </div>
      </div>

      {confirmDel && (
        <ConfirmDialog
          message={`Excluir o lead "${form.nome}"? Esta ação não pode ser desfeita.`}
          onConfirm={() => { onDelete(form.id); setConfirmDel(false); }}
          onCancel={() => setConfirmDel(false)}
        />
      )}
    </div>
  );
}

Object.assign(window, {
  EtapaTag, ProdutoBadge, OrigemTag, FollowUpBadge, Avatar,
  UpsellBadge, ConfirmDialog, LeadModal,
});
})();
