/* COMERCIAL · PROSPECÇÃO v2
 * 571 leads reais · 72 empresas · PAULA PARTNERS ES
 * 4 vistas: Leads · Empresas · Mapa · Análise
 */

const ProspecTab = ({ active, label, count, icon, onClick }) => (
  <button onClick={onClick} style={{
    padding: '10px 16px',
    display: 'inline-flex', alignItems: 'center', gap: 8,
    background: 'transparent', border: 'none', cursor: 'pointer',
    color: active ? 'var(--text)' : 'var(--text-muted)',
    borderBottom: `2px solid ${active ? 'var(--ai-500)' : 'transparent'}`,
    fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600,
    transition: 'color 0.1s',
  }}>
    <Icon name={icon} size={13} />
    {label}
    {count != null && (
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--text-dim)', fontWeight: 500 }}>
        {count}
      </span>
    )}
  </button>
);

const ProspecSortBtn = ({ active, label, onClick }) => (
  <button onClick={onClick} style={{
    padding: '6px 10px', borderRadius: 6,
    fontSize: 11, fontWeight: 500,
    background: active ? 'var(--bg-hover)' : 'transparent',
    border: '1px solid ' + (active ? 'var(--border)' : 'transparent'),
    color: active ? 'var(--text)' : 'var(--text-muted)',
    cursor: 'pointer', fontFamily: 'inherit',
  }}>{label}</button>
);

const ScreenComercialProspeccao = () => {
  const ALL_LEADS = window.PROSPEC_LEADS || [];
  const ALL_EMPRESAS = window.PROSPEC_EMPRESAS || [];

  const [tab, setTab] = React.useState('leads');
  const [search, setSearch] = React.useState('');
  const [sort, setSort] = React.useState('score');
  const [selectedLead, setSelectedLead] = React.useState(null);
  const [selectedEmpresa, setSelectedEmpresa] = React.useState(null);
  const [pageSize, setPageSize] = React.useState(50);

  const defaultFilters = {
    minScore: 7,
    abordagem: [],
    marca: [],
    emailStatus: [],
    senioridade: [],
    regiao: [],
    tamanho: [],
    temTelemovel: false,
    temLinkedin: false,
    temGMB: false,
    gmb45: false,
  };
  const [filters, setFilters] = React.useState(defaultFilters);

  // Score weights (recalc)
  const [weights, setWeights] = React.useState({
    sector: 1, cLevel: 1, email: 1, sweetSpot: 1, gmb: 1,
  });
  const [weightsOn, setWeightsOn] = React.useState(false);

  const filteredLeads = React.useMemo(() => {
    let r = ALL_LEADS.filter(l => {
      if (l.score < filters.minScore) return false;
      if (filters.abordagem.length && !filters.abordagem.includes(l.abordagem)) return false;
      if (filters.marca.length && !filters.marca.includes(l.marca)) return false;
      if (filters.emailStatus.length && !filters.emailStatus.includes(l.emailStatus)) return false;
      if (filters.senioridade.length && !filters.senioridade.includes(l.senioridade)) return false;
      if (filters.regiao.length && !filters.regiao.includes(prospecRegiaoOf(l.cidade))) return false;
      if (filters.temTelemovel && !l.telMovel) return false;
      if (filters.temLinkedin && !l.linkedin) return false;
      if (filters.temGMB && !l.gmbRating) return false;
      if (filters.gmb45 && (!l.gmbRating || l.gmbRating < 4.5)) return false;
      if (filters.tamanho.length) {
        const f = l.funcionarios;
        const matches = filters.tamanho.some(t => {
          if (t === '1-10') return f && f <= 10;
          if (t === '11-50') return f && f > 10 && f <= 50;
          if (t === '51-200') return f && f > 50 && f <= 200;
          if (t === '201+') return f && f > 200;
          return false;
        });
        if (!matches) return false;
      }
      if (search) {
        const q = search.toLowerCase();
        const hay = [l.fullName, l.empresa, l.cargo, l.cidade, l.email, l.marca].filter(Boolean).join(' ').toLowerCase();
        if (!hay.includes(q)) return false;
      }
      return true;
    });

    // sort
    if (sort === 'score') r.sort((a, b) => b.score - a.score);
    else if (sort === 'empresa') r.sort((a, b) => (a.empresa || '').localeCompare(b.empresa || ''));
    else if (sort === 'nome') r.sort((a, b) => (a.fullName || '').localeCompare(b.fullName || ''));
    else if (sort === 'cidade') r.sort((a, b) => (a.cidade || '').localeCompare(b.cidade || ''));
    return r;
  }, [ALL_LEADS, filters, search, sort]);

  const filteredEmpresas = React.useMemo(() => {
    // filtramos empresas pela presença de pelo menos 1 lead no filtro
    const leadIds = new Set(filteredLeads.map(l => l.id));
    return ALL_EMPRESAS
      .map(e => ({ ...e, contactos: e.contactos.filter(c => leadIds.has(c.id)) }))
      .filter(e => e.contactos.length > 0)
      .sort((a, b) => {
        const aTop = Math.max(...a.contactos.map(c => c.score || 0));
        const bTop = Math.max(...b.contactos.map(c => c.score || 0));
        return bTop - aTop || b.contactos.length - a.contactos.length;
      });
  }, [ALL_EMPRESAS, filteredLeads]);

  // counts for filter chips (dentro do estado actual mas ignorando cada eixo)
  const counts = React.useMemo(() => {
    const out = { abordagem: {}, marca: {}, emailStatus: {}, senioridade: {}, regiao: {}, tamanho: {} };
    ALL_LEADS.forEach(l => {
      if (l.score < filters.minScore) return;
      if (l.abordagem) out.abordagem[l.abordagem] = (out.abordagem[l.abordagem] || 0) + 1;
      if (l.marca) out.marca[l.marca] = (out.marca[l.marca] || 0) + 1;
      if (l.emailStatus) out.emailStatus[l.emailStatus] = (out.emailStatus[l.emailStatus] || 0) + 1;
      if (l.senioridade) out.senioridade[l.senioridade] = (out.senioridade[l.senioridade] || 0) + 1;
      const r = prospecRegiaoOf(l.cidade);
      out.regiao[r] = (out.regiao[r] || 0) + 1;
      const f = l.funcionarios;
      let bucket = null;
      if (f && f <= 10) bucket = '1-10';
      else if (f && f <= 50) bucket = '11-50';
      else if (f && f <= 200) bucket = '51-200';
      else if (f) bucket = '201+';
      if (bucket) out.tamanho[bucket] = (out.tamanho[bucket] || 0) + 1;
    });
    return out;
  }, [ALL_LEADS, filters.minScore]);

  // Find selected lead (for drawer)
  const openLeadById = (id) => {
    const l = ALL_LEADS.find(x => x.id === id);
    if (l) setSelectedLead(l);
  };

  const visibleLeads = filteredLeads.slice(0, pageSize);

  // reset pageSize on filter change
  React.useEffect(() => { setPageSize(50); }, [filters, search, sort]);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)', overflow: 'hidden' }}>
      {/* Header */}
      <div style={{ padding: '16px 24px 0', borderBottom: '1px solid var(--border)', background: 'var(--bg-elev)', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 10 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 2 }}>
              <h2 className="font-display" style={{ fontSize: 22, fontWeight: 700, margin: 0, letterSpacing: '-0.01em' }}>Prospecção</h2>
              <span style={{
                padding: '2px 8px', borderRadius: 999, fontSize: 10, fontWeight: 700,
                background: 'color-mix(in oklch, var(--ai-500) 14%, transparent)',
                color: 'var(--ai-500)', letterSpacing: '0.05em',
              }}>PAULA PARTNERS ES</span>
              <span style={{ fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>
                {ALL_LEADS.length} contactos · {ALL_EMPRESAS.length} empresas
              </span>
            </div>
            <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>
              Base de prospecção Espanha · distribuidores de impressão · cruzada com Apollo + GMB + Axesor + LinkedIn
            </div>
          </div>

          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <button className="btn btn-sm" onClick={() => alert('Exportar para Primavera CRM')}>
              <Icon name="download" size={12} />
              Exportar
            </button>
            <button className="btn btn-sm btn-primary">
              <Icon name="sparkle" size={12} />
              Nova pesquisa Digi
            </button>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 4 }}>
          <ProspecTab active={tab === 'leads'} label="Leads" icon="user" count={filteredLeads.length} onClick={() => setTab('leads')} />
          <ProspecTab active={tab === 'empresas'} label="Empresas" icon="building" count={filteredEmpresas.length} onClick={() => setTab('empresas')} />
          <ProspecTab active={tab === 'mapa'} label="Mapa" icon="map-pin" onClick={() => setTab('mapa')} />
          <ProspecTab active={tab === 'analise'} label="Análise" icon="bar-chart" onClick={() => setTab('analise')} />
        </div>
      </div>

      {/* Body */}
      <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
        {/* Sidebar de filtros — só em Empresas e Mapa (Leads é chat, Análise não precisa) */}
        {(tab === 'empresas' || tab === 'mapa') && (
          <ProspecFiltersSidebar
            filters={filters} setFilters={setFilters} counts={counts}
            onReset={() => setFilters(defaultFilters)}
          />
        )}

        {/* Main panel */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          {tab === 'leads' && (
            <ProspecChat
              leads={ALL_LEADS}
              empresas={ALL_EMPRESAS}
              onOpenLead={(l) => setSelectedLead(l)}
              onTabChange={setTab}
            />
          )}

          {tab === 'empresas' && (
            <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: 16 }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 12 }}>
                {filteredEmpresas.map(e => (
                  <ProspecEmpresaCard key={e.empresa} emp={e}
                    onClick={(emp) => {
                      // Abrir primeiro contacto (top score)
                      const top = [...emp.contactos].sort((a, b) => (b.score || 0) - (a.score || 0))[0];
                      if (top) openLeadById(top.id);
                    }}
                    onLeadClick={openLeadById}
                  />
                ))}
              </div>
              {filteredEmpresas.length === 0 && (
                <div style={{ padding: 60, textAlign: 'center', color: 'var(--text-muted)' }}>
                  Sem empresas com estes filtros.
                </div>
              )}
            </div>
          )}

          {tab === 'mapa' && (
            <ProspecMapa leads={filteredLeads} onLeadClick={openLeadById} />
          )}

          {tab === 'analise' && (
            <ProspecAnalise leads={ALL_LEADS} empresas={ALL_EMPRESAS} />
          )}
        </div>
      </div>

      {/* Drawer */}
      {selectedLead && <ProspecDrawer lead={selectedLead} onClose={() => setSelectedLead(null)} />}
    </div>
  );
};

window.ScreenComercialProspeccao = ScreenComercialProspeccao;
