/* global React, Card, Button, Badge, Icon, ICONS, Field, sb, IBProspect */
// ════════════════════════════════════════════════════════════════════════════
// Prospecção — aba de Clientes (Lista · Pipeline · Funil)
// Fonte única: public.leads (migration 0800). Regras puras: src/core/prospecting.js
// ════════════════════════════════════════════════════════════════════════════
const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP, useRef: useRefP } = React;
const P = window.IBProspect;

const TIER_TONE = { A: '#36CFC9', B: '#597EF7', C: '#7A859A' };
const SITE_LABEL = { sem_site: { l: 'Sem site', t: 'success' }, proprio_fraco: { l: 'Site fraco', t: 'warning' }, proprio_ok: { l: 'Tem site', t: 'def' } };
const PAGE = 30;

const lblStyle = { fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--fg-muted)' };
const inputStyle = { width: '100%', background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)', borderRadius: 8, padding: '9px 11px', color: 'var(--fg-primary)', fontSize: 13, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' };
const selectStyle = { ...inputStyle, width: 'auto', padding: '8px 10px', cursor: 'pointer' };

function pct(v) { return v == null ? '—' : Math.round(v * 100) + '%'; }
function fmtBRL(n) { const v = Number(n) || 0; return v ? 'R$ ' + v.toLocaleString('pt-BR', { maximumFractionDigits: 0 }) : '—'; }
function fmtDate(d) { if (!d) return '—'; const x = new Date(d); return x.toLocaleDateString('pt-BR'); }
function fmtDateTime(d) { const x = new Date(d); return x.toLocaleDateString('pt-BR') + ' ' + x.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }); }
function localDateInput(d) { if (!d) return ''; const x = new Date(d); return x.getFullYear() + '-' + String(x.getMonth() + 1).padStart(2, '0') + '-' + String(x.getDate()).padStart(2, '0'); }
function dateAt9(daysFromToday) { const d = new Date(); d.setDate(d.getDate() + daysFromToday); d.setHours(9, 0, 0, 0); return d; }
function fromDateInput(v) { if (!v) return null; const [y, m, d] = v.split('-').map(Number); return new Date(y, m - 1, d, 9, 0, 0, 0); }

async function copyText(text) {
  try { await navigator.clipboard.writeText(text); window.__toast?.('Copiado', { tone: 'success' }); }
  catch { window.__toast?.('Não foi possível copiar', { tone: 'danger' }); }
}
function downloadFile(name, content, type) {
  const blob = new Blob([content], { type });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob); a.download = name;
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}

// ─── Peças visuais ──────────────────────────────────────────────────────────
function Pill({ children, tone, href, title }) {
  const tones = {
    good: { bg: 'rgba(34,197,94,.10)', fg: '#4ADE80', bd: 'rgba(34,197,94,.28)' },
    warn: { bg: 'rgba(250,173,20,.10)', fg: '#FAAD14', bd: 'rgba(250,173,20,.3)' },
    bad:  { bg: 'rgba(239,68,68,.10)', fg: '#FF7A7A', bd: 'rgba(239,68,68,.28)' },
    acc:  { bg: 'var(--primary-soft)', fg: 'var(--geek-blue-300)', bd: 'var(--geek-blue-a40)' },
    def:  { bg: 'var(--bg-elevated)', fg: 'var(--fg-secondary)', bd: 'var(--border-subtle)' },
  };
  const t = tones[tone] || tones.def;
  const st = { display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 9px', borderRadius: 999, fontSize: 11, fontWeight: 600, background: t.bg, color: t.fg, border: `1px solid ${t.bd}`, textDecoration: 'none', whiteSpace: 'nowrap' };
  return href ? <a href={href} target="_blank" rel="noopener noreferrer" style={st} title={title}>{children}</a> : <span style={st} title={title}>{children}</span>;
}

function Chip({ active, onClick, children, count, tone }) {
  return (
    <button onClick={onClick} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 999, border: `1px solid ${active ? (tone || 'var(--primary)') : 'var(--border-subtle)'}`, background: active ? (tone ? tone + '22' : 'var(--primary-soft)') : 'var(--bg-surface)', color: active ? (tone || 'var(--geek-blue-300)') : 'var(--fg-secondary)', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>
      {children}{count != null && <span style={{ opacity: 0.7, fontFamily: 'var(--font-mono)', fontSize: 11 }}>{count}</span>}
    </button>
  );
}

function Seg({ value, onChange, options }) {
  return (
    <div style={{ display: 'inline-flex', background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 10, padding: 3 }}>
      {options.map(o => (
        <button key={o.id} onClick={() => onChange(o.id)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 13px', borderRadius: 7, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, background: value === o.id ? 'var(--primary)' : 'transparent', color: value === o.id ? '#fff' : 'var(--fg-secondary)' }}>
          {o.icon && <Icon d={ICONS[o.icon]} size={13}/>}{o.l}
        </button>
      ))}
    </div>
  );
}

// Selo de faixa + pontuação. "block" (lista e ficha): faixa numa faixa colorida
// em cima, pontuação embaixo. "pill" (Kanban): [A] 85 pts numa linha só.
const TIER_INK = { A: '#04201F', B: '#FFFFFF', C: '#FFFFFF' };
function ScoreBadge({ lead, variant = 'block', size = 'md' }) {
  const tier = lead.tier && TIER_TONE[lead.tier] ? lead.tier : null;
  const tone = tier ? TIER_TONE[tier] : 'var(--fg-muted)';
  const ink = tier ? TIER_INK[tier] : 'var(--bg-surface)';
  const score = lead.score != null ? lead.score : null;
  const title = `${tier ? `Faixa ${tier}` : 'Sem faixa'} · ${score != null ? `${score} de 100 pontos` : 'sem pontuação'}`;
  if (variant === 'pill') {
    return (
      <span title={title} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, flexShrink: 0, padding: '2px 8px 2px 2px', borderRadius: 999, border: `1px solid ${tier ? tone + '66' : 'var(--border-subtle)'}`, background: tier ? tone + '14' : 'transparent', lineHeight: 1 }}>
        <span style={{ width: 20, height: 20, borderRadius: '50%', background: tone, color: ink, display: 'grid', placeItems: 'center', fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 800 }}>{tier || '–'}</span>
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 13, fontWeight: 800, color: 'var(--fg-primary)' }}>{score != null ? score : '—'}</span>
        {score != null && <span style={{ fontSize: 10, color: 'var(--fg-muted)', fontWeight: 600, marginLeft: -3 }}>pts</span>}
      </span>
    );
  }
  const lg = size === 'lg';
  const w = lg ? 64 : 58;
  return (
    <div title={title} style={{ width: w, minWidth: w, borderRadius: 12, overflow: 'hidden', border: `1px solid ${tier ? tone + '88' : 'var(--border-subtle)'}`, background: 'var(--bg-elevated)', display: 'flex', flexDirection: 'column', alignItems: 'stretch', lineHeight: 1, flexShrink: 0 }}>
      <div style={{ background: tone, color: ink, textAlign: 'center', padding: lg ? '5px 0 4px' : '4px 0 3px', fontFamily: 'var(--font-display)', fontSize: 10, fontWeight: 800, letterSpacing: '0.08em' }}>
        {tier ? `FAIXA ${tier}` : 'S/ FAIXA'}
      </div>
      <div style={{ textAlign: 'center', padding: lg ? '8px 0 7px' : '7px 0 6px' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: lg ? 22 : 19, fontWeight: 800, color: 'var(--fg-primary)', letterSpacing: '-0.01em' }}>{score != null ? score : '—'}</div>
        <div style={{ fontSize: 9, color: 'var(--fg-muted)', fontWeight: 700, letterSpacing: '0.06em', marginTop: 3 }}>PONTOS</div>
      </div>
    </div>
  );
}

function StatusSelect({ value, onChange, compact }) {
  const meta = P.statusMeta(value);
  return (
    <select value={P.normalizeStatus(value)} onChange={e => onChange(e.target.value)} onClick={e => e.stopPropagation()} aria-label="Status do contato"
      style={{ ...selectStyle, padding: compact ? '5px 8px' : '7px 10px', fontSize: 12, fontWeight: 700, color: meta.tone, borderColor: meta.tone + '66', background: meta.tone + '14' }}>
      {P.STATUSES.map(s => <option key={s.id} value={s.id} style={{ color: '#111' }}>{s.label}</option>)}
    </select>
  );
}

function Kpi({ label, value, sub, tone, onClick, children }) {
  return (
    <Card padding={16} onClick={onClick} hoverable={!!onClick}>
      <div style={lblStyle}>{label}</div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700, marginTop: 6, letterSpacing: '-0.02em', color: tone || 'var(--fg-primary)' }}>{value}</div>
      {children}
      {sub && <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>{sub}</div>}
    </Card>
  );
}

function Overlay({ children, onClose, width = 560 }) {
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(7,11,28,0.72)', backdropFilter: 'blur(6px)', display: 'grid', placeItems: 'center', zIndex: 9000, padding: 20 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: `min(${width}px, 100%)`, maxHeight: '90vh', overflow: 'auto', background: 'var(--bg-surface)', border: '1px solid var(--border-strong)', borderRadius: 16, padding: 24, boxShadow: '0 24px 64px rgba(0,0,0,.5)' }}>
        {children}
      </div>
    </div>
  );
}

// ─── Card de lead (Lista) ───────────────────────────────────────────────────
function LeadCard({ lead, onOpen, onStatus, onWa, waPrompt, onConfirmSent, onDismissPrompt }) {
  const s = P.normalizeStatus(lead.status);
  const dim = s === 'recusou' || s === 'descartado' || lead.archived_at;
  const wa = P.waLink(lead);
  const maps = P.mapsLink(lead);
  const ig = P.igLink(lead);
  const fu = P.followupState(lead);
  const since = P.daysSince(lead.last_contact_at);
  const site = SITE_LABEL[lead.site_status];
  return (
    <Card padding={16} style={{ opacity: dim ? 0.55 : 1 }}>
      <div style={{ display: 'flex', gap: 14 }}>
        <ScoreBadge lead={lead}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
            <button onClick={() => onOpen(lead)} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: 'inherit', color: 'var(--fg-primary)', fontSize: 15, fontWeight: 700, textAlign: 'left' }}>{lead.name}</button>
            <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{[lead.niche, lead.city].filter(Boolean).join(' · ')}</span>
            {lead.client_id && <Badge tone="success">Cliente</Badge>}
            {lead.archived_at && <Badge tone="neutral" dot={false}>Arquivado</Badge>}
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8 }}>
            {lead.rating != null && <Pill><span style={{ color: '#FADB14' }}>★</span> {String(lead.rating).replace('.', ',')}{lead.rating_count != null ? ` · ${lead.rating_count} avaliações` : ''}</Pill>}
            {site && <Pill tone={site.t === 'success' ? 'good' : 'warn'}>{site.l}</Pill>}
            {lead.instagram ? <Pill tone="acc" href={ig}>{'@' + P.igHandle(lead.instagram)}{lead.ig_followers != null ? ` · ${P.fmtCount(lead.ig_followers)} seg.` : ''}</Pill>
              : (lead.source === 'radar' && <Pill tone="bad">Sem Instagram</Pill>)}
            {(lead.facebook || P.fbLink(lead)) && <Pill href={P.fbLink(lead) || undefined}>Facebook</Pill>}
            {lead.phone_kind === 'fixo' && <Pill tone="warn" title="O número do Google é fixo">Fixo: confirmar WhatsApp</Pill>}
            {fu === 'atrasado' && <Pill tone="bad">Retorno atrasado · {fmtDate(lead.next_followup_at)}</Pill>}
            {fu === 'hoje' && <Pill tone="warn">Retornar hoje</Pill>}
            {fu === 'futuro' && <Pill>Retorno {fmtDate(lead.next_followup_at)}</Pill>}
            {since != null && P.isOpen(lead) && s !== 'novo' && <Pill tone={since >= 7 ? 'warn' : 'def'}>{since === 0 ? 'Contato hoje' : `${since} d sem contato`}</Pill>}
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', marginTop: 12 }}>
            {wa ? <a href={wa} target="_blank" rel="noopener noreferrer" onClick={() => onWa(lead)} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 13px', borderRadius: 8, background: '#25D366', color: '#062A12', fontSize: 12, fontWeight: 700, textDecoration: 'none' }}><Icon d={ICONS.msg} size={14}/>Abrir no WhatsApp</a>
              : <Pill tone="bad">Sem telefone</Pill>}
            {lead.phone && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-secondary)' }}>{lead.phone}</span>}
            <Button size="sm" variant="secondary" icon="page" onClick={() => onOpen(lead, 'dossie')}>{lead.dossier ? 'Dossiê e projeto' : 'Detalhes'}</Button>
            {maps && <a href={maps} target="_blank" rel="noopener noreferrer" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 6, border: '1px solid var(--border-strong)', color: 'var(--fg-primary)', fontSize: 12, fontWeight: 600, textDecoration: 'none' }}><Icon d={ICONS.link} size={13}/>Google Maps</a>}
            <div style={{ flex: 1 }}/>
            <StatusSelect value={s} onChange={v => onStatus(lead, v)}/>
          </div>
          {waPrompt && (
            <div style={{ marginTop: 10, padding: '9px 12px', borderRadius: 10, background: 'rgba(37,211,102,.08)', border: '1px solid rgba(37,211,102,.3)', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', fontSize: 12 }}>
              <span style={{ color: 'var(--fg-secondary)' }}>Enviou a mensagem?</span>
              <Button size="sm" onClick={() => onConfirmSent(lead)}>Marcar como enviada</Button>
              <Button size="sm" variant="ghost" onClick={onDismissPrompt}>Agora não</Button>
            </div>
          )}
        </div>
      </div>
    </Card>
  );
}

// ─── Pipeline (quadro) ──────────────────────────────────────────────────────
// Altura fixa: cada coluna rola por dentro e a barra horizontal fica sempre
// visível. O estado de "arrastando" muda no quadro seguinte (requestAnimationFrame):
// alterar o card dentro do dragstart faz o Chrome cancelar o arrasto.
function PipelineBoard({ leads, onOpen, onMove }) {
  const [over, setOver] = useStateP(null);
  const [dragging, setDragging] = useStateP(null);
  const boardRef = useRefP(null);
  const cols = P.PIPELINE_COLUMNS;
  // Arrastando perto da borda esquerda/direita, o quadro rola sozinho.
  function edgeScroll(e) {
    const el = boardRef.current; if (!el) return;
    const r = el.getBoundingClientRect(), zone = 80;
    if (e.clientX > r.right - zone) el.scrollLeft += Math.ceil((e.clientX - (r.right - zone)) / 4);
    else if (e.clientX < r.left + zone) el.scrollLeft -= Math.ceil(((r.left + zone) - e.clientX) / 4);
  }
  const colIndex = l => cols.findIndex(c => c.statuses.includes(P.normalizeStatus(l.status)));
  function moveTo(lead, col) { if (!col.statuses.includes(P.normalizeStatus(lead.status))) onMove(lead, col.dropStatus || col.id); }
  const arrowBtn = { width: 24, height: 22, borderRadius: 6, border: '1px solid var(--border-subtle)', background: 'transparent', color: 'var(--fg-muted)', cursor: 'pointer', display: 'grid', placeItems: 'center', padding: 0, fontSize: 13, lineHeight: 1, fontFamily: 'inherit' };
  return (
    <div ref={boardRef} onDragOver={edgeScroll} style={{ display: 'grid', gridTemplateColumns: `repeat(${cols.length}, minmax(240px, 1fr))`, gap: 12, overflowX: 'auto', overflowY: 'hidden', height: 'max(460px, calc(100vh - 300px))', paddingBottom: 6 }}>
      {cols.map((col, ci) => {
        const meta = col.label ? { label: col.label, tone: col.tone } : P.statusMeta(col.id);
        const items = leads.filter(l => col.statuses.includes(P.normalizeStatus(l.status)));
        const value = items.reduce((a, l) => a + (Number(l.value) || 0), 0);
        const isOver = over === col.id;
        return (
          <div key={col.id}
            onDragOver={e => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; if (over !== col.id) setOver(col.id); }}
            onDragLeave={e => { if (!e.currentTarget.contains(e.relatedTarget)) setOver(null); }}
            onDrop={e => { e.preventDefault(); setOver(null); setDragging(null); const id = e.dataTransfer.getData('text/plain'); const lead = leads.find(l => String(l.id) === id); if (lead) moveTo(lead, col); }}
            style={{ background: isOver ? meta.tone + '14' : 'var(--bg-surface)', border: `1px solid ${isOver ? meta.tone : 'var(--border-subtle)'}`, boxShadow: isOver ? `inset 0 0 0 1px ${meta.tone}` : 'none', borderRadius: 14, display: 'flex', flexDirection: 'column', minHeight: 0, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '12px 14px 10px', borderBottom: '1px solid var(--border-subtle)', flexShrink: 0 }}>
              <span style={{ width: 9, height: 9, borderRadius: '50%', background: meta.tone }}/>
              <span style={{ fontSize: 12, fontWeight: 700 }}>{meta.label}</span>
              <span style={{ fontSize: 11, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)' }}>{items.length}</span>
              <div style={{ flex: 1 }}/>
              {value > 0 && <span style={{ fontSize: 11, color: meta.tone, fontFamily: 'var(--font-mono)', fontWeight: 700 }}>{fmtBRL(value)}</span>}
            </div>
            <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {items.length === 0 && <div style={{ fontSize: 12, color: 'var(--fg-muted)', padding: '18px 6px', textAlign: 'center', border: '1px dashed var(--border-subtle)', borderRadius: 10 }}>Arraste um lead para cá</div>}
              {items.map(l => {
                const idx = colIndex(l);
                return (
                  <div key={l.id} draggable="true"
                    onDragStart={e => { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', String(l.id)); requestAnimationFrame(() => setDragging(l.id)); }}
                    onDragEnd={() => { setDragging(null); setOver(null); }}
                    onClick={() => onOpen(l)}
                    style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)', borderRadius: 10, padding: '10px 11px', cursor: 'grab', opacity: dragging === l.id ? 0.4 : 1, display: 'flex', gap: 10, alignItems: 'flex-start', flexShrink: 0, userSelect: 'none', WebkitUserSelect: 'none' }}>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, lineHeight: 1.3, overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>{[l.niche, l.city].filter(Boolean).join(' · ')}</div>
                      <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap', alignItems: 'center' }}>
                        <ScoreBadge lead={l} variant="pill"/>
                        {col.id === 'perdido' && <span style={{ fontSize: 10, color: P.statusMeta(l.status).tone, fontWeight: 700 }}>{P.statusMeta(l.status).label}</span>}
                        {P.followupState(l) === 'atrasado' && <span style={{ fontSize: 10, color: '#FF7A7A', fontWeight: 700 }}>Retorno atrasado</span>}
                        {P.followupState(l) === 'hoje' && <span style={{ fontSize: 10, color: '#FAAD14', fontWeight: 700 }}>Retornar hoje</span>}
                        {l.client_id && <span style={{ fontSize: 10, color: '#22C55E', fontWeight: 700 }}>Cliente</span>}
                        {Number(l.value) > 0 && <span style={{ fontSize: 10, color: 'var(--fg-secondary)', fontFamily: 'var(--font-mono)' }}>{fmtBRL(l.value)}</span>}
                        <div style={{ flex: 1 }}/>
                        {idx > 0 && <button type="button" title={`Mover para ${cols[idx - 1].label || P.statusMeta(cols[idx - 1].id).label}`} aria-label="Mover para a coluna anterior" onClick={e => { e.stopPropagation(); moveTo(l, cols[idx - 1]); }} style={arrowBtn}>‹</button>}
                        {idx >= 0 && idx < cols.length - 1 && <button type="button" title={`Mover para ${cols[idx + 1].label || P.statusMeta(cols[idx + 1].id).label}`} aria-label="Mover para a próxima coluna" onClick={e => { e.stopPropagation(); moveTo(l, cols[idx + 1]); }} style={arrowBtn}>›</button>}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Funil (análise) ────────────────────────────────────────────────────────
function FunnelView({ leads }) {
  const m = P.metrics(leads);
  const order = ['novo', 'enviado', 'respondeu', 'proposta', 'fechado', 'recusou', 'descartado'];
  const max = Math.max(1, ...order.map(id => m.byStatus[id]));
  function Table({ title, dim }) {
    const rows = P.funnelBy(leads, dim);
    return (
      <Card padding={0} style={{ overflow: 'hidden' }}>
        <div style={{ padding: '14px 16px', fontWeight: 700, fontSize: 14, borderBottom: '1px solid var(--border-subtle)' }}>{title}</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(140px,1.6fr) 64px 96px 116px 100px', columnGap: 8, padding: '9px 16px', ...lblStyle, fontSize: 10, borderBottom: '1px solid var(--border-subtle)' }}>
          <span/><span>Leads</span><span>Contatados</span><span>Responderam</span><span>Fechados</span>
        </div>
        {rows.length === 0 && <div style={{ padding: 16, fontSize: 13, color: 'var(--fg-muted)' }}>Sem dados.</div>}
        {rows.map(r => (
          <div key={r.key} style={{ display: 'grid', gridTemplateColumns: 'minmax(140px,1.6fr) 64px 96px 116px 100px', columnGap: 8, padding: '10px 16px', fontSize: 13, borderBottom: '1px solid var(--border-subtle)', alignItems: 'center' }}>
            <span style={{ fontWeight: 600 }}>{dim === 'tier' && r.key !== 'Sem faixa' ? 'Faixa ' + r.key : r.key}</span>
            <span style={{ fontFamily: 'var(--font-mono)' }}>{r.total}</span>
            <span style={{ fontFamily: 'var(--font-mono)' }}>{r.contacted}</span>
            <span style={{ fontFamily: 'var(--font-mono)' }}>{r.responded} <em style={{ fontStyle: 'normal', color: 'var(--fg-muted)', fontSize: 11 }}>{r.contacted ? pct(r.responded / r.contacted) : ''}</em></span>
            <span style={{ fontFamily: 'var(--font-mono)', color: r.won ? '#22C55E' : undefined }}>{r.won} <em style={{ fontStyle: 'normal', color: 'var(--fg-muted)', fontSize: 11 }}>{r.contacted ? pct(r.won / r.contacted) : ''}</em></span>
          </div>
        ))}
      </Card>
    );
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card padding={18}>
        <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 14 }}>Onde estão os leads</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {order.map(id => {
            const meta = P.statusMeta(id); const n = m.byStatus[id];
            return (
              <div key={id} style={{ display: 'grid', gridTemplateColumns: '140px 1fr 48px', gap: 12, alignItems: 'center', fontSize: 13 }}>
                <span style={{ color: 'var(--fg-secondary)' }}>{meta.label}</span>
                <div style={{ height: 10, borderRadius: 999, background: 'var(--bg-elevated)', overflow: 'hidden' }}><div style={{ width: `${(n / max) * 100}%`, height: '100%', background: meta.tone, borderRadius: 999 }}/></div>
                <span style={{ fontFamily: 'var(--font-mono)', textAlign: 'right' }}>{n}</span>
              </div>
            );
          })}
        </div>
        <div style={{ display: 'flex', gap: 22, marginTop: 16, fontSize: 12, color: 'var(--fg-muted)', flexWrap: 'wrap' }}>
          <span>Taxa de resposta <b style={{ color: 'var(--fg-primary)' }}>{pct(m.responseRate)}</b></span>
          <span>Taxa de fechamento <b style={{ color: 'var(--fg-primary)' }}>{pct(m.winRate)}</b></span>
          <span>Valor em negociação <b style={{ color: 'var(--fg-primary)' }}>{fmtBRL(m.pipelineValue)}</b></span>
        </div>
      </Card>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(420px, 1fr))', gap: 16 }}>
        <Table title="Por região" dim="city"/>
        <Table title="Por faixa" dim="tier"/>
      </div>
      <Table title="Por nicho" dim="niche"/>
    </div>
  );
}

// ─── Painel lateral do lead ─────────────────────────────────────────────────
function DossierSection({ label, value }) {
  if (value == null || value === '' || (Array.isArray(value) && !value.length)) return null;
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ ...lblStyle, marginBottom: 6 }}>{label}</div>
      {Array.isArray(value)
        ? <ul style={{ margin: 0, paddingLeft: 18, display: 'flex', flexDirection: 'column', gap: 4, fontSize: 13, lineHeight: 1.5, color: 'var(--fg-secondary)' }}>{value.map((x, i) => <li key={i}>{typeof x === 'string' ? x : JSON.stringify(x)}</li>)}</ul>
        : <p style={{ margin: 0, fontSize: 13, lineHeight: 1.6, color: 'var(--fg-secondary)' }}>{String(value)}</p>}
    </div>
  );
}

function ScoreBars({ parts }) {
  if (!parts) return null;
  const rows = [['Reputação', parts.rep, 35], ['Presença digital', parts.dig, 30], ['Oportunidade', parts.opp, 20], ['Ticket do nicho', parts.tic, 15]].filter(r => r[1] != null);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      {rows.map(([l, v, mx]) => (
        <div key={l} style={{ display: 'grid', gridTemplateColumns: '120px 1fr 48px', gap: 10, alignItems: 'center', fontSize: 12 }}>
          <span style={{ color: 'var(--fg-secondary)' }}>{l}</span>
          <div style={{ height: 7, borderRadius: 999, background: 'var(--bg-elevated)', overflow: 'hidden' }}><div style={{ width: `${Math.min(100, (v / mx) * 100)}%`, height: '100%', background: 'var(--primary)' }}/></div>
          <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--fg-muted)' }}>{Math.round(v)}/{mx}</span>
        </div>
      ))}
      {parts.pen && <div style={{ fontSize: 11, color: 'var(--fg-muted)' }}>Ajuste de contato: {parts.pen}</div>}
    </div>
  );
}

const EVENT_LABEL = { created: 'Lead criado', status: 'Status', note: 'Anotação', followup: 'Retorno', contact: 'Contato registrado', converted: 'Virou cliente' };

function LeadDrawer({ lead, initialTab, onClose, onPatch, onConvert, onOpenClient, onArchive, onDelete, onEdit }) {
  const [tab, setTab] = useStateP(initialTab || 'resumo');
  const [events, setEvents] = useStateP(null);
  const [notes, setNotes] = useStateP(lead.notes || '');
  const [msg, setMsg] = useStateP(lead.first_message || '');
  const [value, setValue] = useStateP(lead.value || '');
  const [contactNote, setContactNote] = useStateP('');
  const [confirmDel, setConfirmDel] = useStateP(false);
  const notesTimer = useRefP(null);

  useEffectP(() => { setNotes(lead.notes || ''); setMsg(lead.first_message || ''); setValue(lead.value || ''); }, [lead.id]);
  useEffectP(() => {
    let alive = true;
    sb.from('lead_events').select('*').eq('lead_id', lead.id).order('created_at', { ascending: false }).limit(50)
      .then(({ data }) => { if (alive) setEvents(data || []); });
    return () => { alive = false; };
  }, [lead.id, lead.status, lead.next_followup_at, lead.client_id]);

  function onNotes(v) {
    setNotes(v);
    clearTimeout(notesTimer.current);
    notesTimer.current = setTimeout(() => onPatch(lead, { notes: v }, { silent: true }), 900);
  }
  async function logContact() {
    const note = contactNote.trim() || 'Contato registrado';
    const { error } = await sb.from('lead_events').insert({ lead_id: lead.id, user_id: lead.user_id, type: 'contact', note });
    if (error) { window.__toast?.(error.message, { tone: 'danger' }); return; }
    await onPatch(lead, { last_contact_at: new Date().toISOString() }, { silent: true });
    setContactNote('');
    window.__toast?.('Contato registrado', { tone: 'success' });
  }

  const d = lead.dossier || {};
  const wa = P.waLink(lead, msg);
  const maps = P.mapsLink(lead), ig = P.igLink(lead), site = P.siteLink(lead), fb = P.fbLink(lead);
  const fu = P.followupState(lead);
  const tabs = [{ id: 'resumo', l: 'Resumo' }, { id: 'dossie', l: 'Dossiê' }, { id: 'mensagem', l: 'Mensagem' }, { id: 'acompanhamento', l: 'Acompanhamento' }];
  const quickBtn = { display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 12px', borderRadius: 8, border: '1px solid var(--border-strong)', color: 'var(--fg-primary)', fontSize: 12, fontWeight: 600, textDecoration: 'none', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit' };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(7,11,28,0.72)', backdropFilter: 'blur(6px)', zIndex: 8000, display: 'grid', placeItems: 'center', padding: 24 }}>
      <div role="dialog" aria-modal="true" aria-label={lead.name} onClick={e => e.stopPropagation()} style={{ width: 'min(760px, 100%)', height: 'min(88vh, 920px)', background: 'var(--bg-surface)', border: '1px solid var(--border-strong)', borderRadius: 16, overflow: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: '0 24px 64px rgba(0,0,0,.5)' }}>
        <div style={{ padding: '20px 22px 14px', borderBottom: '1px solid var(--border-subtle)' }}>
          <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
            <ScoreBadge lead={lead} size="lg"/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 19, fontWeight: 800, lineHeight: 1.25 }}>{lead.name}</div>
              <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 3 }}>{[lead.niche, lead.city, lead.source === 'radar' ? 'Radar' : lead.source === 'import' ? 'Importado' : 'Manual'].filter(Boolean).join(' · ')}</div>
            </div>
            <button onClick={onClose} aria-label="Fechar" style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)', borderRadius: 8, width: 32, height: 32, display: 'grid', placeItems: 'center', cursor: 'pointer', color: 'var(--fg-muted)' }}><Icon d={ICONS.x} size={15}/></button>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 14, alignItems: 'center' }}>
            <StatusSelect value={lead.status} onChange={v => onPatch(lead, { status: v })}/>
            {wa && <a href={wa} target="_blank" rel="noopener noreferrer" style={{ ...quickBtn, background: '#25D366', color: '#062A12', border: '1px solid #25D366' }}><Icon d={ICONS.msg} size={13}/>WhatsApp</a>}
            {maps && <a href={maps} target="_blank" rel="noopener noreferrer" style={quickBtn}><Icon d={ICONS.link} size={13}/>Maps</a>}
            {ig && <a href={ig} target="_blank" rel="noopener noreferrer" style={quickBtn}>Instagram</a>}
            {fb && <a href={fb} target="_blank" rel="noopener noreferrer" style={quickBtn}>Facebook</a>}
            {site && <a href={site} target="_blank" rel="noopener noreferrer" style={quickBtn}>Site</a>}
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 10 }}>
            {lead.client_id
              ? <Button size="sm" variant="secondary" icon="users" onClick={() => onOpenClient(lead.client_id)}>Ver cliente</Button>
              : <Button size="sm" icon="users" onClick={() => onConvert(lead)}>Converter em cliente</Button>}
            <Button size="sm" variant="secondary" icon="briefcase" onClick={() => window.__openBudgetWith?.(P.budgetPrefill(lead))}>Gerar proposta</Button>
            <Button size="sm" variant="secondary" icon="edit" onClick={() => onEdit(lead)}>Editar ficha</Button>
            {lead.dossier && <Button size="sm" variant="ghost" icon="copy" onClick={() => copyText(P.briefText(lead))}>Copiar briefing</Button>}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 4, padding: '10px 22px 0', borderBottom: '1px solid var(--border-subtle)' }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{ padding: '9px 12px', border: 'none', borderBottom: `2px solid ${tab === t.id ? 'var(--primary)' : 'transparent'}`, background: 'transparent', color: tab === t.id ? 'var(--fg-primary)' : 'var(--fg-muted)', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>{t.l}</button>
          ))}
        </div>

        <div style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '18px 22px 28px' }}>
          {tab === 'resumo' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                {[
                  ['Nota no Google', lead.rating != null ? `${String(lead.rating).replace('.', ',')} ★ · ${lead.rating_count || 0} avaliações` : '—'],
                  ['Instagram', lead.instagram ? `@${P.igHandle(lead.instagram)}${lead.ig_followers != null ? ` · ${P.fmtCount(lead.ig_followers)} seg.` : ''}${lead.ig_posts != null ? ` · ${P.fmtCount(lead.ig_posts)} posts` : ''}` : '—'],
                  ['Site', (SITE_LABEL[lead.site_status] || {}).l || lead.site_url || '—'],
                  ['Telefone', lead.phone ? lead.phone + (lead.phone_kind === 'fixo' ? ' (fixo)' : '') : '—'],
                  ['Último contato', lead.last_contact_at ? fmtDate(lead.last_contact_at) : 'Ainda não'],
                  ['Próximo retorno', lead.next_followup_at ? fmtDate(lead.next_followup_at) + (fu === 'atrasado' ? ' · atrasado' : fu === 'hoje' ? ' · hoje' : '') : '—'],
                ].map(([k, v]) => (
                  <div key={k} style={{ padding: 12, borderRadius: 10, background: 'var(--bg-elevated)' }}>
                    <div style={{ ...lblStyle, fontSize: 10 }}>{k}</div>
                    <div style={{ fontSize: 13, marginTop: 4 }}>{v}</div>
                  </div>
                ))}
              </div>
              {d.contato && (d.contato.endereco || d.contato.horarios) && (
                <div style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>
                  {d.contato.endereco && <div>📍 {d.contato.endereco}</div>}
                  {d.contato.horarios && <div>🕒 {d.contato.horarios}</div>}
                </div>
              )}
              {lead.insights && <div style={{ padding: 12, borderRadius: 10, border: '1px solid var(--border-subtle)', fontSize: 13, lineHeight: 1.6, color: 'var(--fg-secondary)' }}><b style={{ color: 'var(--fg-primary)' }}>Leitura: </b>{lead.insights}</div>}
              {lead.score_parts && <div><div style={{ ...lblStyle, marginBottom: 10 }}>Por que essa pontuação</div><ScoreBars parts={lead.score_parts}/></div>}
              {d.resumo && <DossierSection label="Resumo do negócio" value={d.resumo}/>}
              {lead.extra && lead.extra.sources && lead.extra.sources.length > 0 && (
                <div style={{ fontSize: 11, color: 'var(--fg-muted)' }}>Fontes: {lead.extra.sources.map((u, i) => <a key={i} href={u} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--geek-blue-300)', marginRight: 8 }}>{String(u).replace(/^https?:\/\/(www\.)?/, '').slice(0, 40)}</a>)}</div>
              )}
            </div>
          )}

          {tab === 'dossie' && (
            lead.dossier ? (
              <div>
                {P.DOSSIER_SECTIONS.map(s => <DossierSection key={s.key} label={s.label} value={d[s.key]}/>)}
                <Button size="sm" variant="secondary" icon="copy" onClick={() => copyText(P.briefText(lead))}>Copiar como briefing</Button>
              </div>
            ) : (
              <div style={{ textAlign: 'center', padding: '36px 12px', border: '1px dashed var(--border-subtle)', borderRadius: 12 }}>
                <div style={{ fontSize: 15, fontWeight: 700 }}>Dossiê ainda vazio</div>
                <p style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6, margin: '6px auto 14px', maxWidth: 420 }}>Registre o que você levantou: resumo do negócio, serviços, o que os clientes elogiam, provas, pacote sugerido e o que falta descobrir.</p>
                <Button size="sm" icon="edit" onClick={() => onEdit(lead)}>Preencher dossiê</Button>
              </div>
            )
          )}

          {tab === 'mensagem' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={lblStyle}>Primeira mensagem</div>
              <textarea value={msg} onChange={e => setMsg(e.target.value)} rows={12} placeholder="Escreva a mensagem de abordagem…" style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.6 }}/>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {wa && <a href={wa} target="_blank" rel="noopener noreferrer" style={{ ...quickBtn, background: '#25D366', color: '#062A12', border: '1px solid #25D366' }}>Abrir no WhatsApp com esta mensagem</a>}
                <Button size="sm" variant="secondary" icon="copy" onClick={() => copyText(msg)}>Copiar</Button>
                {msg !== (lead.first_message || '') && <Button size="sm" onClick={() => onPatch(lead, { first_message: msg })}>Salvar mensagem</Button>}
              </div>
            </div>
          )}

          {tab === 'acompanhamento' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div>
                <div style={{ ...lblStyle, marginBottom: 8 }}>Próximo retorno</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
                  {[['Amanhã', 1], ['Em 3 dias', 3], ['Próx. semana', 7]].map(([l, n]) => <Chip key={l} onClick={() => onPatch(lead, { next_followup_at: dateAt9(n).toISOString() })}>{l}</Chip>)}
                  <input type="date" value={localDateInput(lead.next_followup_at)} onChange={e => onPatch(lead, { next_followup_at: e.target.value ? fromDateInput(e.target.value).toISOString() : null })} style={{ ...selectStyle, colorScheme: 'dark' }}/>
                  {lead.next_followup_at && <Button size="sm" variant="ghost" onClick={() => onPatch(lead, { next_followup_at: null })}>Limpar</Button>}
                </div>
              </div>
              <div>
                <div style={{ ...lblStyle, marginBottom: 8 }}>Registrar contato</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <input value={contactNote} onChange={e => setContactNote(e.target.value)} placeholder="Ex.: liguei, pediu para retornar segunda" style={inputStyle} onKeyDown={e => { if (e.key === 'Enter') logContact(); }}/>
                  <Button size="sm" onClick={logContact}>Registrar</Button>
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 12 }}>
                <label><div style={{ ...lblStyle, marginBottom: 6 }}>Valor estimado (R$)</div>
                  <input type="number" min="0" value={value} onChange={e => setValue(e.target.value)} onBlur={() => { const v = Number(value) || 0; if (v !== (Number(lead.value) || 0)) onPatch(lead, { value: v }, { silent: true }); }} style={inputStyle}/></label>
                <label><div style={{ ...lblStyle, marginBottom: 6 }}>Anotações <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 500 }}>(salva sozinho)</span></div>
                  <textarea value={notes} onChange={e => onNotes(e.target.value)} rows={3} style={{ ...inputStyle, resize: 'vertical' }}/></label>
              </div>
              <div>
                <div style={{ ...lblStyle, marginBottom: 10 }}>Histórico</div>
                {events === null && <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>Carregando…</div>}
                {events && events.length === 0 && <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>Sem eventos ainda.</div>}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                  {(events || []).map(ev => (
                    <div key={ev.id} style={{ display: 'grid', gridTemplateColumns: '110px 1fr', gap: 12, padding: '8px 0', borderBottom: '1px solid var(--border-subtle)', fontSize: 12 }}>
                      <span style={{ color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>{fmtDateTime(ev.created_at)}</span>
                      <span>
                        <b>{EVENT_LABEL[ev.type] || ev.type}</b>
                        {ev.type === 'status' && <span style={{ color: 'var(--fg-secondary)' }}>: {P.statusMeta(ev.from_status).label} → <span style={{ color: P.statusMeta(ev.to_status).tone }}>{P.statusMeta(ev.to_status).label}</span></span>}
                        {ev.note && <span style={{ color: 'var(--fg-secondary)' }}> — {ev.note}</span>}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', paddingTop: 6 }}>
                <Button size="sm" variant="secondary" onClick={() => onArchive(lead)}>{lead.archived_at ? 'Desarquivar' : 'Arquivar lead'}</Button>
                {!confirmDel ? <Button size="sm" variant="ghost" onClick={() => setConfirmDel(true)} style={{ color: '#FF7A7A' }}>Excluir…</Button>
                  : <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center', fontSize: 12 }}>Excluir de vez, com histórico? <Button size="sm" variant="danger" onClick={() => onDelete(lead)}>Excluir</Button><Button size="sm" variant="ghost" onClick={() => setConfirmDel(false)}>Cancelar</Button></span>}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Importar ───────────────────────────────────────────────────────────────
function ImportModal({ userId, existing, onClose, onDone }) {
  const [parsed, setParsed] = useStateP(null);
  const [error, setError] = useStateP('');
  const [fileName, setFileName] = useStateP('');
  const [busy, setBusy] = useStateP(false);
  const [progress, setProgress] = useStateP(0);

  async function onFile(file) {
    setError(''); setParsed(null); setFileName(file ? file.name : '');
    if (!file) return;
    try {
      const text = await file.text();
      const res = P.parseImport(file.name, text, userId);
      if (!res.rows.length) throw new Error('Nenhum lead encontrado no arquivo.');
      const plan = P.planImport(res.rows, existing);
      const m = P.metrics(res.rows.map(r => ({ ...r, status: 'novo' })));
      setParsed({ ...res, plan, m });
    } catch (e) { setError(e.message || 'Arquivo inválido'); }
  }

  async function run() {
    if (!parsed) return;
    setBusy(true); setProgress(0);
    const { toCreate, toUpdate } = parsed.plan;
    const total = toCreate.length + toUpdate.length;
    let done = 0;
    try {
      for (let i = 0; i < toCreate.length; i += 20) {
        const chunk = toCreate.slice(i, i + 20).map(r => P.rowForDb(r, true));
        const { error } = await sb.from('leads').insert(chunk);
        if (error) throw error;
        done += chunk.length; setProgress(done / total);
      }
      for (let i = 0; i < toUpdate.length; i += 20) {
        const chunk = toUpdate.slice(i, i + 20).map(r => P.rowForDb(r, false));
        const { error } = await sb.from('leads').upsert(chunk, { onConflict: 'user_id,source,external_id' });
        if (error) throw error;
        done += chunk.length; setProgress(done / total);
      }
      window.__toast?.(`${toCreate.length} novos · ${toUpdate.length} atualizados`, { tone: 'success' });
      onDone();
    } catch (e) {
      setError((e && e.message) || 'Falha ao importar');
      setBusy(false);
      onDone(true);
    }
  }

  return (
    <Overlay onClose={busy ? undefined : onClose} width={600}>
      <div style={{ fontSize: 18, fontWeight: 800 }}>Importar leads</div>
      <p style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.6, margin: '6px 0 16px' }}>
        Aceita o <b>arquivo HTML do Radar de Prospecção</b>, um JSON ou uma planilha <b>CSV</b> (colunas como Nome, Telefone, WhatsApp, Cidade, Nicho, Faixa, Instagram, Site, Status, Observações).
        Reimportar o mesmo lote <b>atualiza os dados captados sem mexer</b> no status, nas anotações e nos retornos.
      </p>
      <label style={{ display: 'block', border: '1.5px dashed var(--border-strong)', borderRadius: 12, padding: 20, textAlign: 'center', cursor: busy ? 'default' : 'pointer', background: 'var(--bg-elevated)' }}>
        <input type="file" accept=".html,.htm,.json,.csv,text/html,application/json,text/csv" style={{ display: 'none' }} disabled={busy} onChange={e => onFile(e.target.files && e.target.files[0])}/>
        <Icon d={ICONS.upload} size={22} style={{ color: 'var(--fg-muted)' }}/>
        <div style={{ fontSize: 13, fontWeight: 600, marginTop: 8 }}>{fileName || 'Escolher arquivo'}</div>
      </label>
      {error && <div style={{ marginTop: 12, padding: 12, borderRadius: 10, background: 'rgba(239,68,68,.1)', border: '1px solid rgba(239,68,68,.3)', color: '#FF7A7A', fontSize: 13 }}>{error}</div>}
      {parsed && (
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
            {[['Novos', parsed.plan.toCreate.length], ['Atualizados', parsed.plan.toUpdate.length], ['Repetidos no arquivo', parsed.plan.dupInFile]].map(([l, n]) => (
              <div key={l} style={{ padding: 12, borderRadius: 10, background: 'var(--bg-elevated)' }}><div style={{ ...lblStyle, fontSize: 10 }}>{l}</div><div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, marginTop: 4 }}>{n}</div></div>
            ))}
          </div>
          <div style={{ fontSize: 12, color: 'var(--fg-muted)', lineHeight: 1.7 }}>
            Formato: <b style={{ color: 'var(--fg-secondary)' }}>{parsed.format === 'radar' ? 'Radar de Prospecção' : parsed.format.toUpperCase()}</b> ·
            Faixas: A {parsed.m.byTier.A} · B {parsed.m.byTier.B} · C {parsed.m.byTier.C}{parsed.m.byTier.none ? ` · sem faixa ${parsed.m.byTier.none}` : ''}<br/>
            Regiões: {parsed.m.byCity.slice(0, 6).map(c => `${c.key} (${c.n})`).join(' · ')}
          </div>
          {busy && <div style={{ height: 8, borderRadius: 999, background: 'var(--bg-elevated)', overflow: 'hidden' }}><div style={{ width: `${Math.round(progress * 100)}%`, height: '100%', background: 'var(--primary)', transition: 'width 200ms' }}/></div>}
        </div>
      )}
      <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 20 }}>
        <Button variant="secondary" onClick={busy ? undefined : onClose}>Cancelar</Button>
        <Button icon="upload" onClick={busy || !parsed ? undefined : run} style={{ opacity: busy || !parsed ? 0.5 : 1 }}>{busy ? 'Importando…' : 'Importar'}</Button>
      </div>
    </Overlay>
  );
}

// ─── Novo lead (manual) ─────────────────────────────────────────────────────
// Ficha do lead: a mesma tela cria um lead manual e edita qualquer lead
// (inclusive os do Radar, sem perder o que o formulário não mostra).
function LeadFormModal({ lead, userId, cities, niches, onClose, onSaved }) {
  const isEdit = !!lead;
  const [f, setF] = useStateP(() => P.leadToForm(lead || { status: 'novo' }));
  const [tab, setTab] = useStateP('dados');
  const [saving, setSaving] = useStateP(false);
  const [err, setErr] = useStateP('');
  const set = k => e => { const v = e.target.value; setF(x => ({ ...x, [k]: v })); if (k === 'name') setErr(''); };
  const setD = k => e => { const v = e.target.value; setF(x => ({ ...x, dossier: { ...x.dossier, [k]: v } })); };
  const filledDossier = P.DOSSIER_SECTIONS.filter(s => String(f.dossier[s.key] || '').trim()).length;

  async function save() {
    let row;
    try { row = P.formToRow(f, lead); } catch (e) { setErr(e.message); setTab('dados'); return; }
    setSaving(true);
    let res;
    if (isEdit) res = await sb.from('leads').update(row).eq('id', lead.id).select().single();
    else res = await sb.from('leads').insert({ ...row, user_id: userId, source: 'manual', status: f.status || 'novo' }).select().single();
    setSaving(false);
    if (res.error) { window.__toast?.(res.error.message, { tone: 'danger' }); return; }
    onSaved(res.data, isEdit);
  }

  // Campos chamados como função (não como componente) para o input não perder o foco.
  const field = (k, l, o = {}) => (
    <label key={k} style={{ display: 'flex', flexDirection: 'column', gap: 6, gridColumn: o.full ? '1 / -1' : undefined }}>
      <span style={lblStyle}>{l}</span>
      <input type={o.type || 'text'} inputMode={o.inputMode} value={f[k]} onChange={set(k)} placeholder={o.ph} list={o.list} autoFocus={o.autoFocus}
        style={{ ...inputStyle, borderColor: k === 'name' && err ? '#FF7A7A' : undefined }}/>
      {o.hint && <span style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{o.hint}</span>}
    </label>
  );
  const area = (k, l, o = {}) => (
    <label key={k} style={{ display: 'flex', flexDirection: 'column', gap: 6, gridColumn: '1 / -1' }}>
      <span style={lblStyle}>{l}</span>
      <textarea value={o.dossier ? f.dossier[k] : f[k]} onChange={o.dossier ? setD(k) : set(k)} rows={o.rows || 3} placeholder={o.ph}
        style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.55 }}/>
    </label>
  );
  const select = (k, l, opts) => (
    <label key={k} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={lblStyle}>{l}</span>
      <select value={f[k]} onChange={set(k)} style={{ ...selectStyle, width: '100%' }}>{opts.map(([v, t]) => <option key={v} value={v}>{t}</option>)}</select>
    </label>
  );
  const section = (title, children, sub) => (
    <div style={{ marginBottom: 22 }}>
      <div style={{ fontSize: 13, fontWeight: 800, marginBottom: sub ? 2 : 12 }}>{title}</div>
      {sub && <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 12 }}>{sub}</div>}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>{children}</div>
    </div>
  );
  const tabs = [
    { id: 'dados', l: 'Dados' },
    { id: 'contato', l: 'Contato e presença' },
    { id: 'dossie', l: `Dossiê${filledDossier ? ` · ${filledDossier}` : ''}` },
    { id: 'abordagem', l: 'Abordagem' },
  ];
  const linkTest = (href) => href ? <a href={href} target="_blank" rel="noopener noreferrer" style={{ fontSize: 11, color: 'var(--geek-blue-300)' }}>Testar link ↗</a> : null;
  const previewLead = { ...f, extra: { facebook_url: f.facebook_url } };

  return (
    <div onClick={saving ? undefined : onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(7,11,28,0.72)', backdropFilter: 'blur(6px)', zIndex: 9000, display: 'grid', placeItems: 'center', padding: 24 }}>
      <div role="dialog" aria-modal="true" aria-label={isEdit ? 'Editar ficha do lead' : 'Novo lead'} onClick={e => e.stopPropagation()}
        style={{ width: 'min(860px, 100%)', height: 'min(88vh, 920px)', background: 'var(--bg-surface)', border: '1px solid var(--border-strong)', borderRadius: 16, overflow: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: '0 24px 64px rgba(0,0,0,.5)' }}>
        <div style={{ padding: '20px 22px 0', display: 'flex', alignItems: 'flex-start', gap: 14 }}>
          <ScoreBadge lead={{ tier: f.tier || null, score: f.score === '' ? null : f.score }} size="lg"/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 19, fontWeight: 800 }}>{isEdit ? 'Editar ficha' : 'Novo lead'}</div>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 3 }}>{f.name.trim() || 'Preencha o que já levantou — dá para completar depois.'}</div>
          </div>
          <button onClick={onClose} aria-label="Fechar" style={{ background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)', borderRadius: 8, width: 32, height: 32, display: 'grid', placeItems: 'center', cursor: 'pointer', color: 'var(--fg-muted)' }}><Icon d={ICONS.x} size={15}/></button>
        </div>
        <div style={{ display: 'flex', gap: 4, padding: '12px 22px 0', borderBottom: '1px solid var(--border-subtle)', overflowX: 'auto' }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{ padding: '9px 12px', border: 'none', borderBottom: `2px solid ${tab === t.id ? 'var(--primary)' : 'transparent'}`, background: 'transparent', color: tab === t.id ? 'var(--fg-primary)' : 'var(--fg-muted)', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>{t.l}</button>
          ))}
        </div>
        <datalist id="pl-cities">{cities.map(c => <option key={c} value={c}/>)}</datalist>
        <datalist id="pl-niches">{niches.map(c => <option key={c} value={c}/>)}</datalist>

        <div style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '20px 22px 8px' }}>
          {tab === 'dados' && <>
            {section('Identificação', [
              field('name', 'Nome do negócio *', { ph: 'Ex.: Studio Bloom', full: true, autoFocus: !isEdit, hint: err || undefined }),
              field('niche', 'Nicho', { list: 'pl-niches', ph: 'Ex.: Salão de beleza' }),
              field('city', 'Cidade / região', { list: 'pl-cities', ph: 'Ex.: Barueri' }),
              field('address', 'Endereço', { full: true, ph: 'Rua, número, bairro' }),
              field('hours', 'Horário de funcionamento', { full: true, ph: 'Ex.: seg a sáb, 9h às 19h' }),
            ])}
            {section('Qualificação', [
              <div key="tier" style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <span style={lblStyle}>Faixa</span>
                <div style={{ display: 'flex', gap: 6 }}>
                  {['A', 'B', 'C', ''].map(t => {
                    const on = (f.tier || '') === t, tone = TIER_TONE[t] || 'var(--fg-muted)';
                    return <button key={t || 'none'} type="button" onClick={() => setF(x => ({ ...x, tier: t }))}
                      style={{ flex: 1, padding: '8px 0', borderRadius: 8, border: `1px solid ${on ? tone : 'var(--border-subtle)'}`, background: on ? (t ? tone : 'var(--bg-elevated)') : 'transparent', color: on ? (t ? TIER_INK[t] : 'var(--fg-primary)') : 'var(--fg-secondary)', fontWeight: 800, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>{t || 'Sem'}</button>;
                  })}
                </div>
              </div>,
              field('score', 'Pontuação (0–100)', { type: 'number', inputMode: 'numeric', ph: 'Ex.: 85' }),
              field('rating', 'Nota no Google', { inputMode: 'decimal', ph: 'Ex.: 4,8' }),
              field('rating_count', 'Nº de avaliações', { type: 'number', inputMode: 'numeric', ph: 'Ex.: 320' }),
            ], 'A: prioridade alta · B: bom potencial · C: baixa prioridade.')}
          </>}

          {tab === 'contato' && <>
            {section('Contato', [
              field('whatsapp', 'WhatsApp', { inputMode: 'tel', ph: '(11) 9 9999-9999', hint: 'Só números; o 55 é colocado sozinho.' }),
              field('phone', 'Telefone', { inputMode: 'tel', ph: '(11) 4000-0000' }),
              field('email', 'E-mail', { type: 'email', ph: 'contato@negocio.com.br' }),
            ])}
            {section('Presença online', [
              <div key="ig" style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>{field('instagram', 'Instagram', { ph: '@perfil ou link' })}{linkTest(P.igLink(f))}</div>,
              <div key="fb" style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>{field('facebook_url', 'Facebook', { ph: 'Link da página ou @' })}{linkTest(P.fbLink(previewLead))}</div>,
              <div key="site" style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>{field('site_url', 'Site', { ph: 'negocio.com.br' })}{linkTest(P.siteLink(f))}</div>,
              select('site_status', 'Situação do site', [['', 'Não avaliado'], ['sem_site', 'Sem site'], ['proprio_fraco', 'Site fraco'], ['proprio_ok', 'Tem site bom']]),
              <div key="maps" style={{ display: 'flex', flexDirection: 'column', gap: 4, gridColumn: '1 / -1' }}>{field('maps_url', 'Link do Google Maps', { ph: 'Cole o link de compartilhar do Maps', full: true, hint: 'Sem link, o botão do Maps busca pelo nome e cidade.' })}{linkTest(f.maps_url ? (/^https?:/i.test(f.maps_url) ? f.maps_url : 'https://' + f.maps_url) : null)}</div>,
            ])}
          </>}

          {tab === 'dossie' && <>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 16, lineHeight: 1.6 }}>
              Tudo o que você levantou sobre o negócio. Nas listas, <b style={{ color: 'var(--fg-secondary)' }}>um item por linha</b>. Campos vazios não aparecem na ficha.
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 14 }}>
              {P.DOSSIER_SECTIONS.map(s => {
                const isList = P.DOSSIER_LIST_KEYS.includes(s.key);
                return area(s.key, s.label + (isList ? ' · lista' : ''), { dossier: true, rows: s.key === 'resumo' ? 4 : isList ? 4 : 3, ph: isList ? 'Um item por linha' : '' });
              })}
            </div>
          </>}

          {tab === 'abordagem' && <>
            {section('Negociação', [
              ...(isEdit ? [] : [select('status', 'Status inicial', P.STATUSES.map(st => [st.id, st.label]))]),
              field('value', 'Valor estimado (R$)', { inputMode: 'decimal', ph: 'Ex.: 3.500' }),
            ])}
            <div style={{ display: 'grid', gap: 14 }}>
              {area('first_message', 'Primeira mensagem (WhatsApp)', { rows: 7, ph: 'Olá, tudo bem? Vi o trabalho de vocês…' })}
              {area('insights', 'Leitura / oportunidade', { rows: 3, ph: 'Por que vale abordar esse negócio' })}
              {area('notes', 'Anotações', { rows: 4 })}
            </div>
          </>}
        </div>

        <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 12, color: err ? '#FF7A7A' : 'var(--fg-muted)' }}>{err || (isEdit ? 'As alterações valem quando você salvar.' : 'Só o nome é obrigatório.')}</span>
          <div style={{ flex: 1 }}/>
          <Button variant="secondary" onClick={saving ? undefined : onClose}>Cancelar</Button>
          <Button icon={isEdit ? 'check' : 'plus'} onClick={saving ? undefined : save}>{saving ? 'Salvando…' : isEdit ? 'Salvar ficha' : 'Adicionar lead'}</Button>
        </div>
      </div>
    </div>
  );
}

// ─── Confirmação de conversão ───────────────────────────────────────────────
function ConvertModal({ lead, onClose, onConfirm, busy }) {
  return (
    <Overlay onClose={busy ? undefined : onClose} width={480}>
      <div style={{ fontSize: 18, fontWeight: 800 }}>Converter em cliente?</div>
      <p style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.6, margin: '8px 0 14px' }}>
        <b>{lead.name}</b> vai para <b>Clientes</b> como <b>ativo</b>, com origem “Prospecção” e tudo o que foi captado: telefone/WhatsApp, cidade, nicho, Instagram, site, nota no Google, resumo do dossiê e suas anotações. O lead fica marcado como <b>Fechado</b> e ligado ao cliente.
      </p>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
        <Button variant="secondary" onClick={busy ? undefined : onClose}>Agora não</Button>
        <Button icon="users" onClick={busy ? undefined : onConfirm}>{busy ? 'Convertendo…' : 'Converter'}</Button>
      </div>
    </Overlay>
  );
}

// ─── Tela principal ─────────────────────────────────────────────────────────
function Prospecting({ initialView, focusLeadId, onFocusDone, onOpenClient, onCountChange }) {
  const [leads, setLeads] = useStateP([]);
  const [loading, setLoading] = useStateP(true);
  const [loadError, setLoadError] = useStateP('');
  const [userId, setUserId] = useStateP(null);
  const [view, setView] = useStateP(initialView || 'list');
  const [f, setF] = useStateP({ city: 'all', tier: 'all', niche: 'all', status: 'all', followup: 'all', q: '', sort: 'score', showArchived: false });
  const [limit, setLimit] = useStateP(PAGE);
  const [drawer, setDrawer] = useStateP(null);         // { id, tab }
  const [importing, setImporting] = useStateP(false);
  const [creating, setCreating] = useStateP(false);
  const [editing, setEditing] = useStateP(null);      // lead em edição
  const [converting, setConverting] = useStateP(null);  // lead
  const [convBusy, setConvBusy] = useStateP(false);
  const [waPrompt, setWaPrompt] = useStateP(null);

  useEffectP(() => { if (initialView) setView(initialView); }, [initialView]);

  async function load() {
    const { data: auth } = await sb.auth.getUser();
    setUserId(auth?.user?.id || null);
    const { data, error } = await sb.from('leads').select('*').order('created_at', { ascending: false });
    if (error) {
      setLoadError(/column|status|does not exist/i.test(error.message) ? 'A Prospecção precisa da atualização do banco (migration 0800).' : error.message);
    } else setLoadError('');
    setLeads(data || []);
    setLoading(false);
  }
  useEffectP(() => { load(); }, []);
  useEffectP(() => {
    if (!focusLeadId || loading) return;
    if (leads.some(l => l.id === focusLeadId)) setDrawer({ id: focusLeadId, tab: 'dossie' });
    onFocusDone?.();
  }, [focusLeadId, loading]);
  useEffectP(() => { onCountChange?.(leads.filter(l => !l.archived_at).length); }, [leads]);

  const setFilter = (k, v) => { setF(x => ({ ...x, [k]: v })); setLimit(PAGE); };
  const m = useMemoP(() => P.metrics(leads), [leads]);
  const cities = useMemoP(() => m.byCity.filter(c => c.key !== '—'), [m]);
  const niches = useMemoP(() => m.byNiche.map(n => n.key).filter(k => k !== '—'), [m]);
  const filtered = useMemoP(() => P.sortLeads(P.filterLeads(leads, f), f.sort), [leads, f]);
  const anyFilter = f.city !== 'all' || f.tier !== 'all' || f.niche !== 'all' || f.status !== 'all' || f.followup !== 'all' || f.q;
  const drawerLead = drawer && leads.find(l => l.id === drawer.id);

  async function patchLead(lead, patch, opts = {}) {
    const before = leads;
    setLeads(ls => ls.map(l => l.id === lead.id ? { ...l, ...patch } : l));
    const { data, error } = await sb.from('leads').update(patch).eq('id', lead.id).select().single();
    if (error) { setLeads(before); window.__toast?.(error.message, { tone: 'danger' }); return null; }
    setLeads(ls => ls.map(l => l.id === lead.id ? data : l));
    if (!opts.silent && patch.status) window.__toast?.(P.statusMeta(patch.status).label, { tone: 'success' });
    if (patch.status === 'fechado' && !data.client_id) setConverting(data);
    return data;
  }

  async function confirmConvert() {
    const lead = converting;
    setConvBusy(true);
    const { data: cid, error } = await sb.rpc('convert_lead_to_client', { p_lead: lead.id });
    setConvBusy(false);
    if (error) { window.__toast?.(error.message, { tone: 'danger' }); return; }
    const { data: fresh } = await sb.from('leads').select('*').eq('id', lead.id).single();
    if (fresh) setLeads(ls => ls.map(l => l.id === lead.id ? fresh : l));
    setConverting(null);
    window.__toast?.(`${lead.name} agora está em Clientes`, { tone: 'success' });
    window.dispatchEvent(new CustomEvent('clients-changed', { detail: { id: cid } }));
  }

  async function archiveLead(lead) {
    await patchLead(lead, { archived_at: lead.archived_at ? null : new Date().toISOString() }, { silent: true });
    window.__toast?.(lead.archived_at ? 'Lead desarquivado' : 'Lead arquivado', { tone: 'success' });
    if (!lead.archived_at) setDrawer(null);
  }
  async function deleteLead(lead) {
    const { error } = await sb.from('leads').delete().eq('id', lead.id);
    if (error) { window.__toast?.(error.message, { tone: 'danger' }); return; }
    setLeads(ls => ls.filter(l => l.id !== lead.id));
    setDrawer(null);
    window.__toast?.('Lead excluído', { tone: 'success' });
  }

  function exportCsv() {
    const d = new Date();
    downloadFile(`leads-${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}.csv`, P.toCsv(filtered), 'text/csv;charset=utf-8');
  }

  if (loading) return <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 14 }}>Carregando prospecção…</div>;
  if (loadError) return <Card padding={24}><div style={{ fontWeight: 700, marginBottom: 6 }}>Prospecção indisponível</div><div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{loadError}</div></Card>;

  const tierTotal = Math.max(1, m.byTier.A + m.byTier.B + m.byTier.C + m.byTier.none);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {leads.length > 0 && (
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <Seg value={view} onChange={setView} options={[{ id: 'list', l: 'Lista', icon: 'list' }, { id: 'pipeline', l: 'Pipeline', icon: 'pipeline' }, { id: 'funnel', l: 'Funil', icon: 'chart' }]}/>
          <div style={{ flex: 1 }}/>
          <Button variant="secondary" size="sm" icon="upload" onClick={() => setImporting(true)}>Importar</Button>
          <Button variant="secondary" size="sm" icon="download" onClick={exportCsv}>Exportar</Button>
          <Button size="sm" icon="plus" onClick={() => setCreating(true)}>Novo lead</Button>
        </div>
      )}
      {leads.length === 0 ? (
        <Card padding={32} style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 17, fontWeight: 800 }}>Nenhum lead ainda</div>
          <p style={{ fontSize: 13, color: 'var(--fg-muted)', margin: '8px auto 18px', maxWidth: 460, lineHeight: 1.6 }}>Importe a lista do Radar de Prospecção (o próprio arquivo HTML), uma planilha CSV, ou adicione um lead à mão.</p>
          <div style={{ display: 'inline-flex', gap: 10 }}>
            <Button icon="upload" onClick={() => setImporting(true)}>Importar leads</Button>
            <Button variant="secondary" icon="plus" onClick={() => setCreating(true)}>Novo lead</Button>
          </div>
        </Card>
      ) : (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 12 }}>
            <Kpi label="Leads captados" value={m.total} sub={`${m.notContacted} ainda sem contato`}/>
            <Kpi label="Por faixa" value={<span>A {m.byTier.A}<span style={{ fontSize: 15, color: 'var(--fg-muted)', fontWeight: 600 }}> · B {m.byTier.B} · C {m.byTier.C}</span></span>}>
              <div style={{ display: 'flex', height: 6, borderRadius: 999, overflow: 'hidden', marginTop: 10, background: 'var(--bg-elevated)' }}>
                {['A', 'B', 'C'].map(t => <div key={t} style={{ width: `${(m.byTier[t] / tierTotal) * 100}%`, background: TIER_TONE[t] }}/>)}
              </div>
            </Kpi>
            <Kpi label="Em andamento" value={m.inProgress} tone="var(--geek-blue-300)" sub={`${m.byStatus.enviado} enviadas · ${m.byStatus.respondeu} responderam · ${m.byStatus.proposta} propostas`} onClick={() => setFilter('status', f.status === 'andamento' ? 'all' : 'andamento')}/>
            <Kpi label="Retornos" value={m.followupsToday + m.followupsOverdue} tone={m.followupsOverdue ? '#FF7A7A' : undefined} sub={`${m.followupsToday} hoje · ${m.followupsOverdue} atrasados`} onClick={() => setFilter('followup', f.followup === 'pendentes' ? 'all' : 'pendentes')}/>
            <Kpi label="Taxa de resposta" value={pct(m.responseRate)} sub={`de ${m.contacted} contatados`}/>
            <Kpi label="Fechados" value={m.won} tone="#22C55E" sub={`conversão ${pct(m.winRate)}`} onClick={() => setFilter('status', f.status === 'fechado' ? 'all' : 'fechado')}/>
          </div>

          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            <span style={{ ...lblStyle, marginRight: 4 }}>Região</span>
            <Chip active={f.city === 'all'} onClick={() => setFilter('city', 'all')} count={m.total}>Todas</Chip>
            {cities.slice(0, 8).map(c => <Chip key={c.key} active={f.city === c.key} onClick={() => setFilter('city', f.city === c.key ? 'all' : c.key)} count={c.n}>{c.key}</Chip>)}
            <span style={{ width: 12 }}/>
            <span style={{ ...lblStyle, marginRight: 4 }}>Faixa</span>
            {['A', 'B', 'C'].map(t => <Chip key={t} tone={TIER_TONE[t]} active={f.tier === t} onClick={() => setFilter('tier', f.tier === t ? 'all' : t)} count={m.byTier[t]}>{t}</Chip>)}
          </div>
        </>
      )}

      {leads.length > 0 && <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ flex: '1 1 240px', maxWidth: 340 }}><Field icon="search" placeholder="Buscar nome, @, cidade, nicho…" value={f.q} onChange={e => setFilter('q', e.target.value)}/></div>
        <select value={f.status} onChange={e => setFilter('status', e.target.value)} style={selectStyle} aria-label="Status">
          <option value="all">Qualquer status</option>
          <option value="aberto">Ainda não contatados</option>
          <option value="andamento">Em andamento</option>
          {P.STATUSES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
          <option value="perdido">Perdidos (recusou + descartado)</option>
        </select>
        <select value={f.niche} onChange={e => setFilter('niche', e.target.value)} style={selectStyle} aria-label="Nicho">
          <option value="all">Todos os nichos</option>
          {niches.map(n => <option key={n} value={n}>{n}</option>)}
        </select>
        {view === 'list' && <select value={f.sort} onChange={e => setFilter('sort', e.target.value)} style={selectStyle} aria-label="Ordenar">
          {Object.keys(P.SORTS).map(k => <option key={k} value={k}>{P.SORTS[k].label}</option>)}
        </select>}
        {f.followup === 'pendentes' && <Chip active tone="#FAAD14" onClick={() => setFilter('followup', 'all')}>Retornos pendentes ✕</Chip>}
        {anyFilter && <Button size="sm" variant="ghost" onClick={() => { setF(x => ({ ...x, city: 'all', tier: 'all', niche: 'all', status: 'all', followup: 'all', q: '' })); setLimit(PAGE); }}>Limpar filtros</Button>}
      </div>}

      {leads.length > 0 && view !== 'funnel' && (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12, color: 'var(--fg-muted)' }}>
          <span>{filtered.length} de {m.total} leads</span>
          <label style={{ display: 'inline-flex', gap: 6, alignItems: 'center', cursor: 'pointer' }}><input type="checkbox" checked={f.showArchived} onChange={e => setFilter('showArchived', e.target.checked)}/>Mostrar arquivados</label>
        </div>
      )}

      {view === 'list' && leads.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {filtered.length === 0 && <Card padding={24} style={{ textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>Nenhum lead com esses filtros.</Card>}
          {filtered.slice(0, limit).map(l => (
            <LeadCard key={l.id} lead={l}
              onOpen={(lead, tab) => setDrawer({ id: lead.id, tab })}
              onStatus={(lead, v) => patchLead(lead, { status: v })}
              onWa={lead => { if (P.normalizeStatus(lead.status) === 'novo') setWaPrompt(lead.id); }}
              waPrompt={waPrompt === l.id}
              onConfirmSent={lead => { setWaPrompt(null); patchLead(lead, { status: 'enviado' }); }}
              onDismissPrompt={() => setWaPrompt(null)}/>
          ))}
          {filtered.length > limit && <div style={{ textAlign: 'center' }}><Button variant="secondary" onClick={() => setLimit(x => x + PAGE)}>Mostrar mais ({filtered.length - limit})</Button></div>}
        </div>
      )}

      {view === 'pipeline' && leads.length > 0 && <PipelineBoard leads={filtered} onOpen={l => setDrawer({ id: l.id })} onMove={(l, st) => patchLead(l, { status: st })}/>}
      {view === 'funnel' && leads.length > 0 && <FunnelView leads={leads}/>}

      {drawerLead && (
        <LeadDrawer lead={drawerLead} initialTab={drawer.tab} onClose={() => setDrawer(null)}
          onPatch={patchLead} onConvert={l => setConverting(l)} onOpenClient={cid => { setDrawer(null); onOpenClient?.(cid); }}
          onArchive={archiveLead} onDelete={deleteLead} onEdit={l => setEditing(l)}/>
      )}
      {importing && <ImportModal userId={userId} existing={leads} onClose={() => setImporting(false)} onDone={(failed) => { load(); if (!failed) setImporting(false); }}/>}
      {(creating || editing) && <LeadFormModal lead={editing} userId={userId} cities={cities.map(c => c.key)} niches={niches}
        onClose={() => { setCreating(false); setEditing(null); }}
        onSaved={(l, isEdit) => {
          setLeads(ls => isEdit ? ls.map(x => x.id === l.id ? l : x) : [l, ...ls]);
          setCreating(false); setEditing(null);
          window.__toast?.(isEdit ? 'Ficha atualizada' : 'Lead adicionado', { tone: 'success' });
          if (!isEdit) setDrawer({ id: l.id, tab: 'resumo' });
        }}/>}
      {converting && <ConvertModal lead={converting} busy={convBusy} onClose={() => setConverting(null)} onConfirm={confirmConvert}/>}
    </div>
  );
}

window.Prospecting = Prospecting;
