/* Prospecção v2 · vista de LEADS (cards ricos + filtros laterais + search + paginação) */

const ProspecFilterChip = ({ active, onClick, children, count, color }) => (
  <button onClick={onClick} style={{
    padding: '5px 10px', borderRadius: 999,
    fontSize: 11, fontWeight: 500,
    border: `1px solid ${active ? (color || 'var(--ai-500)') : 'var(--border)'}`,
    background: active ? (color ? `color-mix(in oklch, ${color} 14%, transparent)` : 'color-mix(in oklch, var(--ai-500) 14%, transparent)') : 'transparent',
    color: active ? (color || 'var(--ai-500)') : 'var(--text-muted)',
    cursor: 'pointer', fontFamily: 'inherit', transition: 'all 0.1s',
    display: 'inline-flex', alignItems: 'center', gap: 5,
  }}>
    {children}
    {count != null && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, opacity: 0.7 }}>{count}</span>}
  </button>
);

const ProspecFilterSection = ({ title, children, defaultOpen = true }) => {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ borderBottom: '1px solid var(--border-subtle)' }}>
      <button onClick={() => setOpen(!open)} style={{
        width: '100%', padding: '12px 14px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: 'transparent', border: 'none', cursor: 'pointer',
        fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700,
        color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.08em',
      }}>
        {title}
        <Icon name={open ? 'chevron-down' : 'chevron-right'} size={10} />
      </button>
      {open && <div style={{ padding: '0 14px 14px' }}>{children}</div>}
    </div>
  );
};

// ---- Lead card (linha alta, densa) ----
const ProspecLeadCard = ({ lead, onClick }) => {
  const marca = PROSPEC_MARCAS[lead.marca];
  const abord = PROSPEC_ABORDAGEM[lead.abordagem];
  const emailMeta = PROSPEC_EMAIL_STATUS[lead.emailStatus];
  const scoreCol = prospecScoreColor(lead.score);

  // render até 4 chips de razões strong
  const razoesTop = lead.razoes.filter(r => r.strong).slice(0, 4);

  return (
    <button onClick={() => onClick(lead)} style={{
      width: '100%', textAlign: 'left', cursor: 'pointer',
      padding: 14, borderRadius: 10,
      background: 'var(--bg-elev)', border: '1px solid var(--border)',
      display: 'grid', gridTemplateColumns: '52px 1fr auto', gap: 14,
      fontFamily: 'inherit', transition: 'all 0.1s',
    }}
      onMouseEnter={e => { e.currentTarget.style.borderColor = scoreCol; e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = `0 4px 12px color-mix(in oklch, ${scoreCol} 15%, transparent)`; }}
      onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'none'; }}
    >
      {/* Score block */}
      <div style={{
        width: 52, height: 52, borderRadius: 10, flexShrink: 0,
        background: `linear-gradient(135deg, ${scoreCol}, color-mix(in oklch, ${scoreCol} 70%, #000))`,
        display: 'grid', placeItems: 'center',
        color: '#fff', fontFamily: 'var(--font-display)',
        boxShadow: `0 2px 8px color-mix(in oklch, ${scoreCol} 30%, transparent)`,
      }}>
        <div style={{ fontSize: 20, fontWeight: 700, lineHeight: 1 }}>{lead.score}</div>
        <div style={{ fontSize: 8, opacity: 0.85, marginTop: -2, letterSpacing: '0.1em' }}>SCORE</div>
      </div>

      {/* Middle block */}
      <div style={{ minWidth: 0, overflow: 'hidden' }}>
        <div className="font-display" style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--text)', letterSpacing: '-0.005em', lineHeight: 1.2, marginBottom: 3 }}>
          {lead.fullName}
          {lead.senioridade && (
            <span style={{ marginLeft: 8, fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
              {lead.senioridade}
            </span>
          )}
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          <span style={{ whiteSpace: 'nowrap' }}>{lead.cargo}</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span style={{ fontWeight: 500, color: 'var(--text)', whiteSpace: 'nowrap' }}>{lead.empresa}</span>
          {lead.funcionarios && <>
            <span style={{ opacity: 0.4 }}>·</span>
            <span style={{ fontFamily: 'var(--font-mono)', whiteSpace: 'nowrap' }}>{lead.funcionarios} emp</span>
          </>}
          {lead.cidade && <>
            <span style={{ opacity: 0.4 }}>·</span>
            <span style={{ whiteSpace: 'nowrap' }}>{lead.cidade}</span>
          </>}
        </div>

        {/* razões como chips */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {razoesTop.map((r, i) => (
            <span key={i} style={{
              padding: '2px 7px', borderRadius: 4, fontSize: 10,
              background: 'color-mix(in oklch, var(--success) 10%, transparent)',
              color: 'var(--success)', fontWeight: 500, whiteSpace: 'nowrap',
            }}>✓ {r.label}</span>
          ))}
          {lead.gmbRating && (
            <span style={{ padding: '2px 7px', borderRadius: 4, fontSize: 10, background: 'color-mix(in oklch, #f59e0b 10%, transparent)', color: '#f59e0b', fontWeight: 500, whiteSpace: 'nowrap' }}>
              ★ {lead.gmbRating} · {lead.gmbReviews}
            </span>
          )}
        </div>
      </div>

      {/* Right block */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, minWidth: 100 }}>
        {marca && (
          <span style={{
            padding: '3px 9px', borderRadius: 999,
            fontSize: 10, fontWeight: 700, letterSpacing: '0.04em',
            background: marca.bg, color: marca.color,
          }}>{lead.marca}</span>
        )}
        {abord && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: abord.color, fontWeight: 600 }}>
            <span>{abord.icon}</span>
            <span>{abord.short}</span>
          </div>
        )}
        <div style={{ display: 'flex', gap: 4, marginTop: 2 }}>
          {lead.email && emailMeta && (
            <span title={`Email ${emailMeta.label}`} style={{
              width: 20, height: 20, borderRadius: 4,
              background: `color-mix(in oklch, ${emailMeta.color} 14%, transparent)`,
              color: emailMeta.color,
              display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700,
            }}>@</span>
          )}
          {lead.telMovel && (
            <span title="Tem telemóvel" style={{ width: 20, height: 20, borderRadius: 4, background: 'var(--bg-sunken)', color: 'var(--text-muted)', display: 'grid', placeItems: 'center' }}>
              <Icon name="phone" size={10} />
            </span>
          )}
          {lead.linkedin && (
            <span title="LinkedIn" style={{ width: 20, height: 20, borderRadius: 4, background: 'var(--bg-sunken)', color: 'var(--text-muted)', display: 'grid', placeItems: 'center' }}>
              <Icon name="linkedin" size={10} />
            </span>
          )}
        </div>
      </div>
    </button>
  );
};

// ---- Filtros Sidebar ----
const ProspecFiltersSidebar = ({ filters, setFilters, counts, onReset }) => {
  const set = (k, v) => setFilters(f => ({ ...f, [k]: v }));
  const toggleSet = (k, v) => {
    setFilters(f => {
      const cur = new Set(f[k] || []);
      if (cur.has(v)) cur.delete(v); else cur.add(v);
      return { ...f, [k]: Array.from(cur) };
    });
  };
  const has = (k, v) => (filters[k] || []).includes(v);

  return (
    <aside className="scrollbar" style={{
      width: 240, flexShrink: 0, height: '100%', overflowY: 'auto',
      background: 'var(--bg-elev)', borderRight: '1px solid var(--border)',
    }}>
      <div style={{
        padding: '14px 14px 10px', borderBottom: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700, color: 'var(--text-muted)', letterSpacing: '0.1em' }}>
          FILTROS
        </div>
        <button onClick={onReset} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontSize: 10.5, color: 'var(--ai-500)', fontWeight: 500,
        }}>Limpar</button>
      </div>

      {/* Score */}
      <ProspecFilterSection title="Score mínimo">
        <div style={{ padding: '4px 0' }}>
          <input type="range" min={4} max={9} step={1} value={filters.minScore}
            onChange={e => set('minScore', parseInt(e.target.value))}
            style={{ width: '100%', accentColor: prospecScoreColor(filters.minScore) }}
          />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-dim)', marginTop: 4 }}>
            <span>4</span>
            <span style={{ color: prospecScoreColor(filters.minScore), fontWeight: 700, fontSize: 13 }}>≥ {filters.minScore}</span>
            <span>9</span>
          </div>
        </div>
      </ProspecFilterSection>

      {/* Abordagem */}
      <ProspecFilterSection title="Abordagem">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {Object.entries(PROSPEC_ABORDAGEM).map(([k, v]) => (
            <ProspecFilterChip key={k} active={has('abordagem', k)} onClick={() => toggleSet('abordagem', k)} color={v.color}
              count={counts.abordagem[k] || 0}
            >
              <span>{v.icon}</span><span>{v.short}</span>
            </ProspecFilterChip>
          ))}
        </div>
      </ProspecFilterSection>

      {/* Marca */}
      <ProspecFilterSection title="Marca sugerida">
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {Object.entries(PROSPEC_MARCAS).map(([k, v]) => (
            <ProspecFilterChip key={k} active={has('marca', k)} onClick={() => toggleSet('marca', k)} color={v.color}
              count={counts.marca[k] || 0}
            >{k}</ProspecFilterChip>
          ))}
        </div>
      </ProspecFilterSection>

      {/* Email status */}
      <ProspecFilterSection title="Email">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {Object.entries(PROSPEC_EMAIL_STATUS).map(([k, v]) => (
            <ProspecFilterChip key={k} active={has('emailStatus', k)} onClick={() => toggleSet('emailStatus', k)}
              count={counts.emailStatus[k] || 0}
            >
              <span style={{ color: v.color, fontFamily: 'var(--font-mono)', fontWeight: 700 }}>{v.icon}</span>
              {v.label}
            </ProspecFilterChip>
          ))}
        </div>
      </ProspecFilterSection>

      {/* Senioridade */}
      <ProspecFilterSection title="Senioridade" defaultOpen={false}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {Object.entries(counts.senioridade).sort((a, b) => b[1] - a[1]).map(([k, n]) => (
            <ProspecFilterChip key={k} active={has('senioridade', k)} onClick={() => toggleSet('senioridade', k)} count={n}>
              {k}
            </ProspecFilterChip>
          ))}
        </div>
      </ProspecFilterSection>

      {/* Região */}
      <ProspecFilterSection title="Região" defaultOpen={false}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {Object.entries(counts.regiao).sort((a, b) => b[1] - a[1]).map(([k, n]) => (
            <ProspecFilterChip key={k} active={has('regiao', k)} onClick={() => toggleSet('regiao', k)} count={n}>
              {k}
            </ProspecFilterChip>
          ))}
        </div>
      </ProspecFilterSection>

      {/* Sinais */}
      <ProspecFilterSection title="Sinais" defaultOpen={false}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <ProspecFilterChip active={filters.temTelemovel} onClick={() => set('temTelemovel', !filters.temTelemovel)}>
            <Icon name="phone" size={10} /> Com telemóvel
          </ProspecFilterChip>
          <ProspecFilterChip active={filters.temLinkedin} onClick={() => set('temLinkedin', !filters.temLinkedin)}>
            <Icon name="linkedin" size={10} /> LinkedIn activo
          </ProspecFilterChip>
          <ProspecFilterChip active={filters.temGMB} onClick={() => set('temGMB', !filters.temGMB)}>
            ★ Com GMB
          </ProspecFilterChip>
          <ProspecFilterChip active={filters.gmb45} onClick={() => set('gmb45', !filters.gmb45)}>
            ★ GMB ≥ 4.5
          </ProspecFilterChip>
        </div>
      </ProspecFilterSection>

      {/* Tamanho empresa */}
      <ProspecFilterSection title="Tamanho empresa" defaultOpen={false}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {[
            ['1-10', l => l.funcionarios && l.funcionarios <= 10],
            ['11-50', l => l.funcionarios && l.funcionarios > 10 && l.funcionarios <= 50],
            ['51-200', l => l.funcionarios && l.funcionarios > 50 && l.funcionarios <= 200],
            ['201+', l => l.funcionarios && l.funcionarios > 200],
          ].map(([k]) => (
            <ProspecFilterChip key={k} active={has('tamanho', k)} onClick={() => toggleSet('tamanho', k)} count={counts.tamanho[k] || 0}>
              {k} emp
            </ProspecFilterChip>
          ))}
        </div>
      </ProspecFilterSection>
    </aside>
  );
};

window.ProspecLeadCard = ProspecLeadCard;
window.ProspecFiltersSidebar = ProspecFiltersSidebar;
window.ProspecFilterChip = ProspecFilterChip;
window.ProspecFilterSection = ProspecFilterSection;
