/* ================================================================
   Tracker FMN — Contatos
   A base única: uma ficha por e-mail, com o que a pessoa é agora
   (tipo principal), uma tag por produto e tudo o que chegou pela
   Hotmart. A ficha é montada no banco por recalcular_contato()
   (migrations 149 e 150) e se refaz sozinha a cada lead, venda ou
   carrinho. Esta tela só lê. Base do envio de e-mail próprio.
   ================================================================ */
(function () {
const { useState, useEffect, useCallback } = React;
const { LucideIcon, Btn, Badge, CardKPI, SectionCard, PageBody, PageHeader } = window;

const nfC = n => (n == null ? '—' : Number(n).toLocaleString('pt-BR'));
const brl = n => Number(n || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
const dataBR = d => d ? new Date(d).toLocaleDateString('pt-BR', { timeZone: 'America/Sao_Paulo' }) : '—';

const TIPOS = [
  { id: 'cliente-blindagem', label: 'Cliente Blindagem', tone: 'teal' },
  { id: 'aluno-mcv',         label: 'Aluno MCV',         tone: 'gold' },
  { id: 'cliente-outro',     label: 'Cliente de outro produto', tone: 'info' },
  { id: 'quase-comprou',     label: 'Quase comprou',     tone: 'warn' },
  { id: 'lead-quente',       label: 'Lead quente',       tone: 'ok' },
  { id: 'lead',              label: 'Lead',              tone: 'neutral' },
  { id: 'bloqueado',         label: 'Bloqueado',         tone: 'danger' },
];
const PRODUTOS = [
  { id: 'blindagem', label: 'Blindagem' }, { id: 'mcv', label: 'MCV' },
  { id: 'mqv', label: 'Mensagens que Vendem' }, { id: 'pack-pro-lightroom', label: 'Pack Pro Lightroom' },
  { id: 'cenarios-natalinos', label: 'Cenários Natalinos' }, { id: 'combo-presets', label: 'Combo de Presets' },
  { id: 'mentoria-xp', label: 'Mentoria XP' },
];
const ESTADOS_PROD = [
  { id: 'cliente', label: 'Cliente', tone: 'ok' },
  { id: 'carrinho', label: 'Carrinho', tone: 'warn' },
  { id: 'reembolso', label: 'Reembolso', tone: 'danger' },
];
const nomeProduto = id => PRODUTOS.find(p => p.id === id)?.label || id;
const tipoDef = id => TIPOS.find(t => t.id === id) || { label: id, tone: 'neutral' };
function rotuloTagProduto(tag) {
  const [estado, ...resto] = tag.split('-');
  const e = ESTADOS_PROD.find(x => x.id === estado);
  return e ? { label: `${e.label} ${nomeProduto(resto.join('-'))}`, tone: e.tone } : { label: tag, tone: 'neutral' };
}
function telBR(t) {
  const d = String(t || '').replace(/\D/g, '');
  const l = d.startsWith('55') && d.length > 11 ? d.slice(2) : d;
  if (l.length === 11) return `(${l.slice(0, 2)}) ${l.slice(2, 7)}-${l.slice(7)}`;
  if (l.length === 10) return `(${l.slice(0, 2)}) ${l.slice(2, 6)}-${l.slice(6)}`;
  return t || '';
}

const pill = on => ({
  display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', padding: '6px 12px', borderRadius: 999,
  fontSize: 12.5, fontFamily: 'Roboto, sans-serif', transition: 'all .15s',
  background: on ? 'var(--app-primary)' : 'var(--app-surface)', color: on ? 'var(--app-primary-fg)' : 'var(--text-2)',
  border: `1px solid ${on ? 'var(--app-primary)' : 'var(--app-border)'}`,
});

function BotaoWhats({ contato, grande }) {
  const [abrindo, setAbrindo] = useState(false);
  if (!contato.telefone) return grande ? <span style={{ color: 'var(--text-3)', fontSize: 13 }}>Sem WhatsApp</span> : <span style={{ color: 'var(--text-3)' }}>—</span>;
  const abrir = async e => {
    e.stopPropagation(); setAbrindo(true);
    await window.abrirNoFMNPro(contato.telefone, contato.nome, contato.email);
    setAbrindo(false);
  };
  return (
    <button onClick={abrir} title="Abrir a conversa no FMN Pro" disabled={abrindo}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer', border: 'none', background: 'none',
        color: '#25D366', fontFamily: 'Roboto,sans-serif', fontSize: grande ? 14 : 13, padding: 0, fontVariantNumeric: 'tabular-nums' }}>
      <LucideIcon icon="message-circle" size={grande ? 16 : 14}/>{abrindo ? 'Abrindo...' : telBR(contato.telefone)}
    </button>
  );
}

function Linha({ rotulo, children }) {
  return (
    <div style={{ display: 'flex', gap: 12, padding: '6px 0', fontSize: 13 }}>
      <div style={{ width: 120, flexShrink: 0, color: 'var(--text-3)' }}>{rotulo}</div>
      <div style={{ color: 'var(--text-1)', minWidth: 0, wordBreak: 'break-word' }}>{children || '—'}</div>
    </div>
  );
}

function Ficha({ email, onClose }) {
  const [c, setC] = useState(null);
  useEffect(() => {
    window.db.from('contatos').select('*').eq('email', email).maybeSingle().then(({ data }) => setC(data));
  }, [email]);
  const endereco = c && [c.endereco && `${c.endereco}${c.numero ? ', ' + c.numero : ''}`, c.bairro,
    [c.cidade, c.estado].filter(Boolean).join(' / '), c.cep && `CEP ${c.cep}`].filter(Boolean).join(' · ');
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.55)', zIndex: 200, display: 'flex', justifyContent: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 'min(560px, 100%)', height: '100%', overflowY: 'auto',
        background: 'var(--app-bg)', borderLeft: '1px solid var(--app-border)', padding: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--text-1)' }}>{c?.nome || email}</div>
            <div style={{ fontSize: 13, color: 'var(--text-3)', marginTop: 2 }}>{email}</div>
          </div>
          <Btn size="sm" variant="ghost" icon="x" onClick={onClose}/>
        </div>
        {!c ? <div style={{ padding: 40, color: 'var(--text-3)' }}>Carregando...</div> : (<>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', margin: '14px 0' }}>
            <Badge tone={tipoDef(c.tipo).tone}>{tipoDef(c.tipo).label}</Badge>
            {(c.produtos || []).map(t => { const r = rotuloTagProduto(t); return <Badge key={t} tone={r.tone}>{r.label}</Badge>; })}
          </div>
          <div style={{ margin: '8px 0 18px' }}><BotaoWhats contato={c} grande/></div>

          <SectionCard title="Cadastro" icon="id-card">
            <Linha rotulo="CPF">{c.cpf}</Linha>
            <Linha rotulo="Endereço">{endereco}</Linha>
            <Linha rotulo="País">{c.pais}</Linha>
            <Linha rotulo="Origem">{c.origem}</Linha>
            <Linha rotulo="Primeiro contato">{dataBR(c.primeiro_contato)}</Linha>
            <Linha rotulo="Última atividade">{dataBR(c.ultima_atividade)}</Linha>
            <Linha rotulo="Engajamento">{c.email_engagement != null ? `${Math.round(c.email_engagement * 100)}%` : null}</Linha>
            {c.bloqueado && <Linha rotulo="Bloqueado">{c.motivo_bloqueio}</Linha>}
          </SectionCard>

          <div style={{ height: 14 }}/>
          <SectionCard title={`Compras · ${brl(c.total_gasto)} em ${nfC(c.qtd_compras)}`} icon="shopping-cart">
            {!(c.compras || []).length ? <div style={{ fontSize: 13, color: 'var(--text-3)' }}>Nenhuma compra.</div> :
              c.compras.map((v, i) => (
                <div key={i} style={{ padding: '10px 0', borderTop: i ? '1px solid var(--app-border)' : 'none', fontSize: 13 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                    <strong style={{ color: 'var(--text-1)' }}>{nomeProduto(v.produto) || v.produto_nome}</strong>
                    <span style={{ color: 'var(--text-1)', fontVariantNumeric: 'tabular-nums' }}>{brl(v.valor)}</span>
                  </div>
                  <div style={{ color: 'var(--text-3)', marginTop: 4, lineHeight: 1.6 }}>
                    {dataBR(v.data)} · {v.status}{v.metodo ? ` · ${v.metodo}` : ''}{v.parcelas > 1 ? ` em ${v.parcelas}x` : ''}
                    {v.oferta ? ` · ${v.oferta}` : ''}{v.cupom ? ` · cupom ${v.cupom}` : ''}{v.order_bump ? ' · order bump' : ''}
                    {v.ads ? ` · ADS ${v.ads}` : v.utm_source ? ` · ${v.utm_source}` : ''}
                  </div>
                </div>
              ))}
          </SectionCard>

          <div style={{ height: 14 }}/>
          <SectionCard title="Todas as tags" icon="tags">
            <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
              {(c.tags || []).map(t => <Badge key={t} tone="neutral">{t}</Badge>)}
            </div>
          </SectionCard>
        </>)}
      </div>
    </div>
  );
}

function ContatosScreen() {
  const [tipo, setTipo] = useState(null);
  const [produto, setProduto] = useState(null);
  const [estado, setEstado] = useState('cliente');
  const [busca, setBusca] = useState('');
  const [contagens, setContagens] = useState({});
  const [linhas, setLinhas] = useState([]);
  const [total, setTotal] = useState(null);
  const [carregando, setCarregando] = useState(true);
  const [aberto, setAberto] = useState(null);
  const [noApp, setNoApp] = useState(window.abrirNoApp());

  useEffect(() => {
    Promise.all(TIPOS.map(async t => {
      const { count } = await window.db.from('contatos').select('email', { count: 'exact', head: true }).eq('tipo', t.id);
      return [t.id, count || 0];
    })).then(p => setContagens(Object.fromEntries(p)));
  }, []);

  const filtrar = useCallback(q => {
    if (tipo) q = q.eq('tipo', tipo);
    if (produto) q = q.contains('produtos', [`${estado}-${produto}`]);
    const b = busca.trim().replace(/[,()]/g, ' ');
    if (b) {
      const dig = b.replace(/\D/g, '');
      q = q.or([`email.ilike.%${b}%`, `nome.ilike.%${b}%`, dig.length >= 4 ? `telefone.ilike.%${dig}%` : null].filter(Boolean).join(','));
    }
    return q;
  }, [tipo, produto, estado, busca]);

  useEffect(() => {
    let vivo = true; setCarregando(true);
    const id = setTimeout(async () => {
      const { data, count, error } = await filtrar(window.db.from('contatos')
        .select('email,nome,telefone,tipo,produtos,total_gasto,cidade,estado,ultima_atividade', { count: 'exact' }))
        .order('ultima_atividade', { ascending: false, nullsFirst: false }).limit(300);
      if (!vivo) return;
      if (error) { alert(error.message); setCarregando(false); return; }
      setLinhas(data || []); setTotal(count ?? 0); setCarregando(false);
    }, 300);
    return () => { vivo = false; clearTimeout(id); };
  }, [filtrar]);

  const totalBase = Object.values(contagens).reduce((a, b) => a + b, 0);
  const clientes = (contagens['cliente-blindagem'] || 0) + (contagens['aluno-mcv'] || 0) + (contagens['cliente-outro'] || 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <PageBody>
        <PageHeader title="Contatos"
          description="A base única: uma ficha por pessoa, com o que ela é agora e tudo o que chegou da Hotmart. Atualiza sozinha."
          actions={<label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--text-2)', cursor: 'pointer' }}
            title="Vale para todo telefone do Tracker, neste computador">
            <input type="checkbox" checked={noApp} onChange={e => { const v = e.target.checked; setNoApp(v);
              try { localStorage.setItem('fmnpro_no_app', v ? 'sim' : 'nao'); } catch {} }}/>
            WhatsApp abre no programa FMN Pro
          </label>}/>

        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
          <CardKPI label="Contatos na base" value={nfC(totalBase)} icon="users" accent/>
          <CardKPI label="Clientes" value={nfC(clientes)} icon="badge-check"/>
          <CardKPI label="Quase compraram" value={nfC(contagens['quase-comprou'])} icon="shopping-cart"/>
          <CardKPI label="Bloqueados" value={nfC(contagens['bloqueado'])} icon="mail-x" title="Pediram para sair ou o e-mail não existe. Nunca recebem e-mail."/>
        </div>

        <SectionCard title="O que a pessoa é" icon="user-round-check"
          headerRight={tipo ? <Btn size="sm" variant="ghost" icon="x" onClick={() => setTipo(null)}>Limpar</Btn> : null}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {TIPOS.map(t => (
              <button key={t.id} style={pill(tipo === t.id)} onClick={() => setTipo(tipo === t.id ? null : t.id)}>
                <span>{t.label}</span><span style={{ opacity: .65, fontVariantNumeric: 'tabular-nums' }}>{nfC(contagens[t.id])}</span>
              </button>
            ))}
          </div>
        </SectionCard>

        <SectionCard title="Produto" icon="package"
          headerRight={produto ? <Btn size="sm" variant="ghost" icon="x" onClick={() => setProduto(null)}>Limpar</Btn> : null}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 12 }}>
            {ESTADOS_PROD.map(e => <button key={e.id} style={pill(estado === e.id)} onClick={() => setEstado(e.id)}>{e.label}</button>)}
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {PRODUTOS.map(p => <button key={p.id} style={pill(produto === p.id)} onClick={() => setProduto(produto === p.id ? null : p.id)}>{p.label}</button>)}
          </div>
        </SectionCard>

        <SectionCard title={total == null ? 'Carregando...' : `${nfC(total)} contatos`} icon="contact"
          headerRight={
            <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="Buscar por e-mail, nome ou WhatsApp"
              style={{ width: 280, maxWidth: '100%', height: 32, padding: '0 12px', borderRadius: 8, fontSize: 13, fontFamily: 'Roboto, sans-serif',
                background: 'var(--app-bg)', color: 'var(--text-1)', border: '1px solid var(--app-border)', outline: 'none' }}/>
          }>
          {carregando ? <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-3)', fontSize: 13 }}>Carregando...</div>
          : !linhas.length ? <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-3)', fontSize: 13 }}>Ninguém com esse filtro.</div>
          : (
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                <thead>
                  <tr style={{ textAlign: 'left', color: 'var(--text-3)', fontSize: 11, textTransform: 'uppercase', letterSpacing: .4 }}>
                    <th style={{ padding: '8px 10px' }}>Contato</th>
                    <th style={{ padding: '8px 10px' }}>WhatsApp</th>
                    <th style={{ padding: '8px 10px' }}>Tipo</th>
                    <th style={{ padding: '8px 10px' }}>Produtos</th>
                    <th style={{ padding: '8px 10px', textAlign: 'right' }}>Gastou</th>
                    <th style={{ padding: '8px 10px' }}>Cidade</th>
                    <th style={{ padding: '8px 10px' }}>Última atividade</th>
                  </tr>
                </thead>
                <tbody>
                  {linhas.map(l => (
                    <tr key={l.email} onClick={() => setAberto(l.email)} style={{ borderTop: '1px solid var(--app-border)', cursor: 'pointer' }}>
                      <td style={{ padding: 10, maxWidth: 260 }}>
                        <div style={{ color: 'var(--text-1)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.nome || l.email}</div>
                        {l.nome && <div style={{ color: 'var(--text-3)', fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.email}</div>}
                      </td>
                      <td style={{ padding: 10, whiteSpace: 'nowrap' }}><BotaoWhats contato={l}/></td>
                      <td style={{ padding: 10, whiteSpace: 'nowrap' }}><Badge tone={tipoDef(l.tipo).tone}>{tipoDef(l.tipo).label}</Badge></td>
                      <td style={{ padding: 10 }}>
                        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                          {(l.produtos || []).map(t => { const r = rotuloTagProduto(t); return <Badge key={t} tone={r.tone}>{r.label}</Badge>; })}
                        </div>
                      </td>
                      <td style={{ padding: 10, textAlign: 'right', whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums', color: 'var(--text-2)' }}>
                        {Number(l.total_gasto) > 0 ? brl(l.total_gasto) : '—'}
                      </td>
                      <td style={{ padding: 10, whiteSpace: 'nowrap', color: 'var(--text-2)' }}>{[l.cidade, l.estado].filter(Boolean).join(' / ') || '—'}</td>
                      <td style={{ padding: 10, whiteSpace: 'nowrap', color: 'var(--text-2)', fontVariantNumeric: 'tabular-nums' }}>{dataBR(l.ultima_atividade)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {total > linhas.length && (
                <div style={{ padding: '14px 10px 2px', fontSize: 12, color: 'var(--text-3)' }}>
                  Mostrando os {nfC(linhas.length)} com atividade mais recente de {nfC(total)}. Use os filtros ou a busca para achar o resto.
                </div>
              )}
            </div>
          )}
        </SectionCard>
      </PageBody>
      {aberto && <Ficha email={aberto} onClose={() => setAberto(null)}/>}
    </div>
  );
}

window.ContatosScreen = ContatosScreen;
})();
