/* COMERCIAL · PROSPECÇÃO v2 — 571 leads reais (PAULA PARTNERS ES)
 * 4 vistas: Leads · Empresas · Mapa · Análise
 * Filtros laterais multi-dim · drawer 5-tab · score recalculável */

// ================ HELPERS ================
const PROSPEC_MARCAS = {
  'Sensek':   { color: '#ec4899', bg: 'color-mix(in oklch, #ec4899 12%, transparent)' },
  'Mimaki':   { color: '#ef4444', bg: 'color-mix(in oklch, #ef4444 12%, transparent)' },
  'BIOND':    { color: '#10b981', bg: 'color-mix(in oklch, #10b981 12%, transparent)' },
  'Decal':    { color: '#3b82f6', bg: 'color-mix(in oklch, #3b82f6 12%, transparent)' },
};

const PROSPEC_ABORDAGEM = {
  'direct':   { icon: '🔥', label: 'Ligar esta semana',        short: 'Direct',   color: '#ef4444' },
  'email':    { icon: '⚡', label: 'Email + follow-up 3d',      short: 'Email',    color: '#f59e0b' },
  'campaign': { icon: '📧', label: 'Campanha email mensal',     short: 'Campaign', color: '#6b7280' },
};

const PROSPEC_EMAIL_STATUS = {
  'Verified':     { color: 'var(--success)', icon: '✓', label: 'Verificado' },
  'Extrapolated': { color: 'var(--warning)', icon: '≈', label: 'Extrapolado' },
  'Unavailable':  { color: 'var(--text-dim)', icon: '—', label: 'Indisponível' },
};

const PROSPEC_SENIORIDADE_ORDER = ['C_Suite', 'Founder', 'Owner', 'Partner', 'Vp', 'Head', 'Director', 'Manager', 'Senior', 'Entry'];

// regiões prioritárias identificadas no Resumo do Fábio
const PROSPEC_REGIOES_PRIO = {
  'Madrid': ['Madrid', 'Pinto', 'Torrejón de Ardoz', 'Getafe', 'Alcorcón', 'Móstoles'],
  'Castilla-La Mancha': ['Albacete', 'Chinchilla de Montearagon', 'Toledo', 'Guadalajara', 'Ciudad Real', 'Cuenca'],
  'Andalucía': ['Sevilla', 'Málaga', 'Granada', 'Córdoba', 'Cádiz', 'Jaén', 'Huelva', 'Almería'],
  'Asturias': ['Oviedo', 'Gijón', 'Avilés'],
  'Aragón': ['Zaragoza', 'Huesca', 'Teruel'],
  'La Rioja': ['Logroño'],
  'Extremadura': ['Cáceres', 'Badajoz', 'Mérida'],
  'Cantabria': ['Santander'],
};

const prospecRegiaoOf = (cidade) => {
  if (!cidade) return 'Outras';
  for (const [reg, cities] of Object.entries(PROSPEC_REGIOES_PRIO)) {
    if (cities.some(c => cidade.toLowerCase().includes(c.toLowerCase()))) return reg;
  }
  return 'Outras';
};

const prospecScoreColor = (s) => {
  if (s >= 9) return '#ef4444';
  if (s >= 8) return '#f97316';
  if (s >= 7) return '#eab308';
  if (s >= 6) return '#84cc16';
  if (s >= 5) return '#6b7280';
  return '#9ca3af';
};

const prospecFormatFact = (n) => {
  if (!n || isNaN(n)) return '—';
  if (n >= 1e6) return `€${(n / 1e6).toFixed(1)}M`;
  if (n >= 1e3) return `€${Math.round(n / 1e3)}k`;
  return `€${n}`;
};

// ================ DRAWER (lead detail) ================
const ProspecDrawerTab = ({ active, label, onClick, count }) => (
  <button onClick={onClick} style={{
    padding: '10px 14px', fontSize: 11.5, fontWeight: 600, letterSpacing: '0.02em',
    border: 'none', background: 'transparent', cursor: 'pointer',
    color: active ? 'var(--text)' : 'var(--text-muted)',
    borderBottom: `2px solid ${active ? 'var(--ai-500)' : 'transparent'}`,
    fontFamily: 'inherit', transition: 'color 0.1s',
  }}>
    {label}{count != null && <span style={{ marginLeft: 5, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-dim)' }}>{count}</span>}
  </button>
);

const ProspecField = ({ label, value, mono, multiline }) => (
  <div style={{ display: 'flex', gap: 12, padding: '8px 0', borderBottom: '1px solid var(--border-subtle)' }}>
    <div style={{ fontSize: 10.5, color: 'var(--text-muted)', width: 110, flexShrink: 0, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.04em', paddingTop: 2 }}>{label}</div>
    <div style={{
      fontSize: 12, color: 'var(--text)', flex: 1, minWidth: 0,
      fontFamily: mono ? 'var(--font-mono)' : 'inherit',
      whiteSpace: multiline ? 'pre-wrap' : 'normal',
      wordBreak: 'break-word',
    }}>{value || <span style={{ color: 'var(--text-dim)' }}>—</span>}</div>
  </div>
);

const ProspecExtLink = ({ href, label, icon }) => {
  if (!href) return null;
  return (
    <a href={href} target="_blank" rel="noopener" style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '6px 10px', borderRadius: 6,
      fontSize: 11, fontWeight: 500,
      background: 'var(--bg-sunken)', border: '1px solid var(--border)',
      color: 'var(--text)', textDecoration: 'none',
      transition: 'all 0.1s',
    }}
      onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)'; e.currentTarget.style.borderColor = 'var(--ai-500)'; }}
      onMouseLeave={e => { e.currentTarget.style.background = 'var(--bg-sunken)'; e.currentTarget.style.borderColor = 'var(--border)'; }}
    >
      {icon && <span>{icon}</span>}
      {label}
      <Icon name="arrow-up-right" size={10} style={{ opacity: 0.6 }} />
    </a>
  );
};

const ProspecDrawer = ({ lead, onClose }) => {
  const [tab, setTab] = React.useState('contacto');
  if (!lead) return null;

  const marca = PROSPEC_MARCAS[lead.marca];
  const abord = PROSPEC_ABORDAGEM[lead.abordagem];
  const emailMeta = PROSPEC_EMAIL_STATUS[lead.emailStatus];

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)',
        zIndex: 90, animation: 'prospec-fade 0.15s ease-out',
      }} />
      <aside style={{
        position: 'fixed', right: 0, top: 0, bottom: 0, width: 560, zIndex: 91,
        background: 'var(--bg-elev)', borderLeft: '1px solid var(--border)',
        display: 'flex', flexDirection: 'column',
        animation: 'prospec-slide 0.2s ease-out',
        boxShadow: '-8px 0 32px rgba(0,0,0,0.25)',
      }}>
        {/* Header */}
        <div style={{ padding: '18px 20px 14px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 12 }}>
            <div style={{
              width: 52, height: 52, borderRadius: 10, flexShrink: 0,
              background: `linear-gradient(135deg, ${prospecScoreColor(lead.score)}, color-mix(in oklch, ${prospecScoreColor(lead.score)} 70%, #000))`,
              display: 'grid', placeItems: 'center',
              fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: '#fff',
              boxShadow: `0 4px 12px color-mix(in oklch, ${prospecScoreColor(lead.score)} 40%, transparent)`,
            }}>{lead.score}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="font-display" style={{ fontSize: 18, fontWeight: 700, lineHeight: 1.15, letterSpacing: '-0.01em', marginBottom: 2 }}>
                {lead.fullName}
              </div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 4 }}>
                {lead.cargo} · {lead.empresa}
              </div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {marca && (
                  <span style={{ padding: '2px 8px', borderRadius: 999, fontSize: 10, fontWeight: 700, background: marca.bg, color: marca.color, letterSpacing: '0.04em' }}>
                    {lead.marca}
                  </span>
                )}
                {abord && (
                  <span style={{ padding: '2px 8px', borderRadius: 999, fontSize: 10, fontWeight: 600, background: `color-mix(in oklch, ${abord.color} 14%, transparent)`, color: abord.color }}>
                    {abord.icon} {abord.short}
                  </span>
                )}
                {lead.senioridade && (
                  <span style={{ padding: '2px 8px', borderRadius: 999, fontSize: 10, fontWeight: 500, background: 'var(--bg-sunken)', color: 'var(--text-muted)', border: '1px solid var(--border)' }}>
                    {lead.senioridade}
                  </span>
                )}
              </div>
            </div>
            <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', padding: 4 }}>
              <Icon name="close" size={16} />
            </button>
          </div>

          {/* Quick actions */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {lead.email && (
              <a href={`mailto:${lead.email}`} style={{
                flex: 1, minWidth: 110, padding: '8px 12px', borderRadius: 7,
                background: 'var(--ai-500)', color: '#fff', textDecoration: 'none',
                fontSize: 11.5, fontWeight: 600, textAlign: 'center',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              }}>
                <Icon name="mail" size={12} /> Enviar email
              </a>
            )}
            {lead.telMovel && (
              <a href={`tel:${lead.telMovel}`} style={{
                flex: 1, minWidth: 110, padding: '8px 12px', borderRadius: 7,
                background: 'var(--bg-sunken)', border: '1px solid var(--border)',
                color: 'var(--text)', textDecoration: 'none',
                fontSize: 11.5, fontWeight: 600, textAlign: 'center',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              }}>
                <Icon name="phone" size={12} /> Ligar
              </a>
            )}
            {lead.linkedin && (
              <a href={lead.linkedin} target="_blank" rel="noopener" style={{
                padding: '8px 12px', borderRadius: 7,
                background: 'var(--bg-sunken)', border: '1px solid var(--border)',
                color: 'var(--text)', textDecoration: 'none',
                fontSize: 11.5, fontWeight: 600,
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                <Icon name="linkedin" size={12} /> LinkedIn
              </a>
            )}
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', borderBottom: '1px solid var(--border)', overflowX: 'auto', background: 'var(--bg)' }}>
          <ProspecDrawerTab active={tab === 'contacto'} label="Contacto" onClick={() => setTab('contacto')} />
          <ProspecDrawerTab active={tab === 'empresa'} label="Empresa" onClick={() => setTab('empresa')} />
          <ProspecDrawerTab active={tab === 'gmb'} label="Google My Business" onClick={() => setTab('gmb')} />
          <ProspecDrawerTab active={tab === 'financ'} label="Financeiro" onClick={() => setTab('financ')} />
          <ProspecDrawerTab active={tab === 'sinais'} label="Sinais" onClick={() => setTab('sinais')} />
        </div>

        {/* Body */}
        <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '18px 20px' }}>
          {tab === 'contacto' && <ProspecDrawerContacto lead={lead} />}
          {tab === 'empresa' && <ProspecDrawerEmpresa lead={lead} />}
          {tab === 'gmb' && <ProspecDrawerGMB lead={lead} />}
          {tab === 'financ' && <ProspecDrawerFinanc lead={lead} />}
          {tab === 'sinais' && <ProspecDrawerSinais lead={lead} />}
        </div>
      </aside>
      <style>{`
        @keyframes prospec-slide { from { transform: translateX(100%); } to { transform: translateX(0); } }
        @keyframes prospec-fade { from { opacity: 0; } to { opacity: 1; } }
      `}</style>
    </>
  );
};

const ProspecDrawerContacto = ({ lead }) => {
  const emailMeta = PROSPEC_EMAIL_STATUS[lead.emailStatus];
  return (
    <>
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-dim)', letterSpacing: '0.1em', marginBottom: 10, fontFamily: 'var(--font-mono)' }}>PORQUÊ ESTE SCORE</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 10 }}>
          {lead.razoes.map((r, i) => (
            <span key={i} style={{
              padding: '5px 10px', borderRadius: 6, fontSize: 11,
              background: r.strong ? 'color-mix(in oklch, var(--success) 14%, transparent)' : r.soft ? 'color-mix(in oklch, var(--warning) 10%, transparent)' : 'var(--bg-sunken)',
              color: r.strong ? 'var(--success)' : r.soft ? 'var(--warning)' : 'var(--text-muted)',
              border: `1px solid ${r.strong ? 'color-mix(in oklch, var(--success) 30%, var(--border))' : 'var(--border)'}`,
              fontWeight: 500,
            }}>
              {r.strong ? '✓' : r.soft ? '≈' : '○'} {r.label}
            </span>
          ))}
        </div>
      </div>

      <ProspecField label="Nome" value={lead.fullName} />
      <ProspecField label="Cargo" value={lead.cargo} />
      <ProspecField label="Senioridade" value={lead.senioridade} />
      <ProspecField label="Departamento" value={lead.depart} />
      <ProspecField label="Email" value={lead.email ? (
        <span>
          <a href={`mailto:${lead.email}`} style={{ color: 'var(--ai-500)', textDecoration: 'none' }}>{lead.email}</a>
          {emailMeta && (
            <span style={{ marginLeft: 8, fontSize: 10, color: emailMeta.color, fontFamily: 'var(--font-mono)' }}>
              {emailMeta.icon} {emailMeta.label}
            </span>
          )}
        </span>
      ) : null} />
      <ProspecField label="Telemóvel" value={lead.telMovel} mono />
      <ProspecField label="LinkedIn" value={lead.linkedin ? (
        <a href={lead.linkedin} target="_blank" rel="noopener" style={{ color: 'var(--ai-500)', fontSize: 11, wordBreak: 'break-all' }}>
          {lead.linkedin.replace(/^https?:\/\/(www\.)?/, '')}
        </a>
      ) : null} />
      <ProspecField label="Apollo ID" value={lead.apolloId} mono />
    </>
  );
};

const ProspecDrawerEmpresa = ({ lead }) => (
  <>
    <ProspecField label="Empresa" value={lead.empresa} />
    <ProspecField label="Indústria" value={lead.industria} />
    <ProspecField label="Funcionários" value={lead.funcionarios ? `${lead.funcionarios} colab.` : null} mono />
    <ProspecField label="Cidade" value={lead.cidade} />
    <ProspecField label="País" value={lead.pais} />
    <ProspecField label="Telefone" value={lead.telEmpresa} mono />
    <ProspecField label="Website" value={lead.website ? (
      <a href={lead.website} target="_blank" rel="noopener" style={{ color: 'var(--ai-500)', wordBreak: 'break-all' }}>
        {lead.website.replace(/^https?:\/\/(www\.)?/, '')}
      </a>
    ) : null} />
  </>
);

const ProspecDrawerGMB = ({ lead }) => (
  <>
    {lead.gmbRating ? (
      <div style={{
        padding: 14, marginBottom: 14, borderRadius: 10,
        background: 'var(--bg-sunken)', border: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 16,
      }}>
        <div style={{ textAlign: 'center' }}>
          <div className="font-display" style={{ fontSize: 32, fontWeight: 700, lineHeight: 1, color: '#f59e0b' }}>{lead.gmbRating}</div>
          <div style={{ fontSize: 16, letterSpacing: 2, color: '#f59e0b', marginTop: 4 }}>
            {'★'.repeat(Math.round(lead.gmbRating))}
          </div>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>{lead.gmbReviews} reviews</div>
          <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>Perfil Google activo</div>
        </div>
        {lead.gmbMaps && (
          <ProspecExtLink href={lead.gmbMaps} label="Ver no Maps" icon="🗺" />
        )}
      </div>
    ) : (
      <div style={{ padding: 14, marginBottom: 14, borderRadius: 10, background: 'var(--bg-sunken)', border: '1px dashed var(--border)', textAlign: 'center', color: 'var(--text-muted)', fontSize: 12 }}>
        Sem perfil Google My Business
      </div>
    )}
    <ProspecField label="Morada" value={lead.gmbMorada} multiline />
    <ProspecField label="Categorias" value={lead.gmbCateg} />
    {lead.gmbHorario && lead.gmbHorario.length > 0 && (
      <div style={{ padding: '8px 0', borderBottom: '1px solid var(--border-subtle)' }}>
        <div style={{ fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 6 }}>Horário</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {lead.gmbHorario.map((h, i) => (
            <div key={i} style={{ fontSize: 11, color: 'var(--text)', fontFamily: 'var(--font-mono)' }}>{h}</div>
          ))}
        </div>
      </div>
    )}
  </>
);

const ProspecDrawerFinanc = ({ lead }) => (
  <>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, marginBottom: 16 }}>
      <div style={{ padding: 12, background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 8 }}>
        <div style={{ fontSize: 10, color: 'var(--text-muted)', marginBottom: 4, fontFamily: 'var(--font-mono)' }}>FACTURAÇÃO</div>
        <div className="font-display" style={{ fontSize: 22, fontWeight: 700, lineHeight: 1, color: 'var(--text)' }}>
          {prospecFormatFact(lead.facturacao)}
        </div>
      </div>
      <div style={{ padding: 12, background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 8 }}>
        <div style={{ fontSize: 10, color: 'var(--text-muted)', marginBottom: 4, fontFamily: 'var(--font-mono)' }}>FUNCIONÁRIOS</div>
        <div className="font-display" style={{ fontSize: 22, fontWeight: 700, lineHeight: 1, color: 'var(--text)' }}>
          {lead.funcionarios || '—'}
        </div>
      </div>
    </div>
    <ProspecField label="CNAE" value={lead.cnae} mono />
    <ProspecField label="Descrição" value={lead.cnaeDesc} multiline />
    <ProspecField label="Ano Fundação" value={lead.anoFund} mono />
    <ProspecField label="Capital Social" value={lead.capitalSocial ? prospecFormatFact(lead.capitalSocial) : null} mono />

    <div style={{ marginTop: 16 }}>
      <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-dim)', letterSpacing: '0.1em', marginBottom: 8, fontFamily: 'var(--font-mono)' }}>VERIFICAR EM</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        <ProspecExtLink href={lead.axesorLink} label="Axesor" icon="📊" />
        <ProspecExtLink href={lead.infoempresas} label="InfoEmpresas" icon="📋" />
        <ProspecExtLink href={lead.kompass} label="Kompass" icon="🔍" />
      </div>
    </div>
  </>
);

const ProspecDrawerSinais = ({ lead }) => {
  const sinais = [
    { label: 'Hiring activo', v: lead.hiring, on: lead.hiring && lead.hiring !== 'Não' },
    { label: 'Crescimento detectado', v: lead.crescimento, on: lead.crescimento && lead.crescimento !== 'Não' },
    { label: 'Equipamento actual', v: lead.equipActual, on: !!lead.equipActual },
    { label: 'Concorrência detectada', v: lead.concorrencia, on: !!lead.concorrencia },
    { label: 'Notícias recentes', v: lead.noticias, on: !!lead.noticias },
    { label: 'Presente em feiras', v: lead.feiras, on: !!lead.feiras },
    { label: 'LinkedIn seguidores', v: lead.seguidores, on: !!lead.seguidores },
    { label: 'Última publicação', v: lead.ultimaPublic, on: !!lead.ultimaPublic },
  ];
  return (
    <>
      <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-dim)', letterSpacing: '0.1em', marginBottom: 10, fontFamily: 'var(--font-mono)' }}>SINAIS DE COMPRA · LINKEDIN</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {sinais.map((s, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 12px', borderRadius: 8,
            background: s.on ? 'color-mix(in oklch, var(--success) 8%, transparent)' : 'var(--bg-sunken)',
            border: `1px solid ${s.on ? 'color-mix(in oklch, var(--success) 25%, var(--border))' : 'var(--border)'}`,
          }}>
            <span style={{
              width: 18, height: 18, borderRadius: '50%', flexShrink: 0,
              background: s.on ? 'var(--success)' : 'var(--text-dim)',
              display: 'grid', placeItems: 'center', fontSize: 10, color: '#fff', fontWeight: 700,
            }}>{s.on ? '✓' : '—'}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 500 }}>{s.label}</div>
              {s.v && s.v !== 'Não' && <div style={{ fontSize: 10.5, color: 'var(--text-muted)', marginTop: 1 }}>{s.v}</div>}
            </div>
          </div>
        ))}
      </div>
      <div style={{
        marginTop: 16, padding: 12, borderRadius: 8,
        background: 'color-mix(in oklch, var(--ai-500) 6%, transparent)',
        border: '1px solid color-mix(in oklch, var(--ai-500) 20%, var(--border))',
        fontSize: 11.5, lineHeight: 1.5,
      }}>
        <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--ai-500)', marginBottom: 4, fontFamily: 'var(--font-mono)' }}>📊 LI STATUS</div>
        <div style={{ color: 'var(--text-muted)' }}>{lead.liStatus || 'Sem pesquisa LinkedIn executada.'}</div>
      </div>
    </>
  );
};

window.PROSPEC_MARCAS = PROSPEC_MARCAS;
window.PROSPEC_ABORDAGEM = PROSPEC_ABORDAGEM;
window.PROSPEC_EMAIL_STATUS = PROSPEC_EMAIL_STATUS;
window.PROSPEC_REGIOES_PRIO = PROSPEC_REGIOES_PRIO;
window.prospecRegiaoOf = prospecRegiaoOf;
window.prospecScoreColor = prospecScoreColor;
window.prospecFormatFact = prospecFormatFact;
window.ProspecDrawer = ProspecDrawer;
