# Modelo: Lançamento Imobiliário (Cloudflare Native)

Template para páginas de lançamento imobiliário com formulário de interesse, galeria, mapa/localização, simulador de financiamento, vídeo de tour, calendário de agendamento e botão WhatsApp.

---

## 🏗️ ARQUITETURA TÉCNICA (Quantum Tier)

```
Browser (cdpTrack.js)
  ├─ PageView              → ao carregar
  ├─ ViewContent           → ao entrar na galeria
  ├─ FindLocation          → ao interagir com mapa/localização
  ├─ video_25/50/75/complete → ao assistir tour virtual
  ├─ CustomizeProduct      → ao usar simulador de financiamento
  ├─ AddToWishlist         → ao favoritar imóvel
  ├─ Contact               → ao clicar em WhatsApp/telefone
  ├─ Schedule              → ao confirmar agendamento de visita
  └─ Lead                  → ao enviar formulário (PII completo)
        │
        ▼
  Cloudflare Worker (same-domain /track)
    ├─ Fraud Gate
    ├─ LTV Prediction (Granite 4.0 Micro) + score por eventType
    ├─ D1: upsertProfile, identity graph, distanceKm
    └─ CAPI dispatch: Meta v25.0 + GA4 + TikTok v1.3
```

---

## 📘 MAPA DE EVENTOS

| Evento | Gatilho | Sinal para as plataformas |
|---|---|---|
| `PageView` | Carregamento | Topo do funil |
| `ViewContent` | Entra na galeria de fotos | Interesse no produto |
| `FindLocation` | Clica em mapa / "Como chegar" / abre localização | Intenção de visita física — +10 LTV |
| `video_25` / `video_50` / `video_75` / `video_complete` | Tour virtual / VSL em % assistido | Engajamento profundo |
| `CustomizeProduct` | Usa simulador de financiamento/parcelas/FGTS | Intenção de compra máxima — +15 LTV |
| `AddToWishlist` | Clica em "Favoritar" / coração | Interesse persistente — +8 LTV |
| `Contact` | Clica em WhatsApp ou telefone | Alta intenção de contato |
| `Schedule` | Confirma agendamento de visita | Conversão de visita |
| `Lead` | Envia formulário (nome/email/telefone) | Conversão principal com PII |

---

## 🛠️ PASSO 1: CONFIGURAÇÃO DO SDK

### 1.1 Header
```html
<script src="/js/cdpTrack.js" async></script>
<script>
  window.cdpConfig = {
    metaId: 'SEU_PIXEL_ID',
    ttId: 'SEU_TIKTOK_ID',
    trackEndpoint: '/track'
  };
</script>
```

---

## 🛠️ PASSO 2: EVENTOS DE COMPORTAMENTO

### 2.1 PageView (automático via SDK)
O SDK dispara automaticamente. Não precisa de código adicional.

---

### 2.2 ViewContent — Galeria de fotos
```javascript
// Dispara quando usuário abre/rola a galeria de imagens
document.querySelector('.galeria-imovel, [data-section="gallery"]')?.addEventListener('click', () => {
  cdpTrack.track('ViewContent', {
    contentName: 'Galeria — [NOME DO EMPREENDIMENTO]',
    contentCategory: 'imovel',
    funnel_stage: 'gallery_view',
  });
});
```

---

### 2.3 FindLocation — Mapa / Localização
```javascript
// Dispara quando usuário clica no mapa, "Como chegar" ou "Ver localização"
document.querySelectorAll(
  'a[href*="maps"], a[href*="waze"], [data-section="localizacao"], #mapa, .btn-localizacao, .btn-como-chegar'
).forEach(el => {
  el.addEventListener('click', () => {
    cdpTrack.track('FindLocation', {
      contentName: 'Localização — [NOME DO EMPREENDIMENTO]',
      contentCategory: 'imovel',
      funnel_stage: 'map_view',
      // Coordenadas do empreendimento (preencher):
      property_lat: -23.5505,   // latitude
      property_lng: -46.6333,   // longitude
    });
  });
});
```

---

### 2.4 Vídeo / Tour Virtual
```javascript
// Para vídeo HTML5 nativo:
const video = document.querySelector('video#tour-virtual, video.tour-360');
if (video) {
  const fired = new Set();
  video.addEventListener('timeupdate', () => {
    const pct = Math.floor((video.currentTime / video.duration) * 100);
    if (pct >= 25 && !fired.has(25)) {
      fired.add(25);
      cdpTrack.track('video_25', { contentName: 'Tour Virtual — [NOME DO EMPREENDIMENTO]' });
    }
    if (pct >= 50 && !fired.has(50)) {
      fired.add(50);
      cdpTrack.track('video_50', { contentName: 'Tour Virtual — [NOME DO EMPREENDIMENTO]' });
    }
    if (pct >= 75 && !fired.has(75)) {
      fired.add(75);
      cdpTrack.track('video_75', { contentName: 'Tour Virtual — [NOME DO EMPREENDIMENTO]' });
    }
  });
  video.addEventListener('ended', () => {
    cdpTrack.track('video_complete', { contentName: 'Tour Virtual — [NOME DO EMPREENDIMENTO]' });
  });
}

// Para YouTube embed (via YouTube API):
// Adicionar ?enablejsapi=1 na URL do iframe e usar onStateChange
// Ver: https://developers.google.com/youtube/iframe_api_reference
```

---

### 2.5 CustomizeProduct — Simulador de Financiamento
```javascript
// Dispara quando usuário interage com o simulador de parcelas/FGTS/Caixa
const simulador = document.querySelector(
  '#simulador, .simulador-financiamento, [data-section="simulacao"], form.simulador'
);

if (simulador) {
  // Dispara ao 1º interact (foco em qualquer campo do simulador)
  let simuladorFired = false;
  simulador.addEventListener('focusin', () => {
    if (simuladorFired) return;
    simuladorFired = true;
    cdpTrack.track('CustomizeProduct', {
      contentName: 'Simulador de Financiamento — [NOME DO EMPREENDIMENTO]',
      contentCategory: 'imovel',
      funnel_stage: 'financing_simulation',
      intentionLevel: 'comprador',
    });
  });

  // Dispara também ao clicar em "Simular" / "Calcular"
  simulador.querySelector('button[type="submit"], .btn-simular, .btn-calcular')?.addEventListener('click', () => {
    const valorImovel = simulador.querySelector('input[name="valor"], #valor-imovel')?.value;
    cdpTrack.track('CustomizeProduct', {
      contentName: 'Simulação Concluída — [NOME DO EMPREENDIMENTO]',
      contentCategory: 'imovel',
      funnel_stage: 'financing_simulation',
      intentionLevel: 'comprador',
      value: valorImovel ? parseFloat(valorImovel.replace(/\D/g, '')) : undefined,
      currency: 'BRL',
    });
  });
}
```

---

### 2.6 AddToWishlist — Favoritar Imóvel
```javascript
// Dispara quando usuário clica em favoritar / ícone de coração
document.querySelectorAll('.btn-favoritar, .icon-heart, [data-action="favoritar"], .favorito').forEach(el => {
  el.addEventListener('click', () => {
    cdpTrack.track('AddToWishlist', {
      contentName: '[NOME DO EMPREENDIMENTO]',
      contentCategory: 'imovel',
      funnel_stage: 'wishlist',
    });
  });
});
```

---

### 2.7 Contact — WhatsApp / Telefone
```javascript
// WhatsApp
document.querySelectorAll('a[href*="wa.me"], a[href*="whatsapp.com"], .btn-whatsapp').forEach(el => {
  el.addEventListener('click', () => {
    cdpTrack.track('Contact', {
      contentName: 'WhatsApp — [NOME DO EMPREENDIMENTO]',
      contentCategory: 'imovel_whatsapp',
      funnel_stage: 'whatsapp_click',
      intentionLevel: 'comprador',
    });
  });
});

// Telefone
document.querySelectorAll('a[href^="tel:"], .btn-ligar, .btn-telefone').forEach(el => {
  el.addEventListener('click', () => {
    cdpTrack.track('Contact', {
      contentName: 'Telefone — [NOME DO EMPREENDIMENTO]',
      contentCategory: 'imovel_telefone',
      funnel_stage: 'phone_click',
      intentionLevel: 'comprador',
    });
  });
});
```

---

### 2.8 Schedule — Calendário de Agendamento de Visita
```javascript
// Dispara quando usuário CONFIRMA o agendamento (não ao abrir o calendário)
// Adaptar ao provider: Calendly, Google Calendar, formulário próprio

// Exemplo com Calendly:
window.addEventListener('message', (e) => {
  if (e.data?.event === 'calendly.event_scheduled') {
    cdpTrack.track('Schedule', {
      contentName: 'Visita Agendada — [NOME DO EMPREENDIMENTO]',
      contentCategory: 'imovel',
      funnel_stage: 'schedule_confirmed',
      intentionLevel: 'comprador',
      // Dados do lead do Calendly (se disponíveis via payload):
      email: e.data?.payload?.invitee?.email,
      firstName: e.data?.payload?.invitee?.first_name,
    });
  }
});

// Exemplo com formulário próprio de agendamento:
document.querySelector('#form-agendamento')?.addEventListener('submit', async (e) => {
  e.preventDefault();
  const data = new FormData(e.target);
  await cdpTrack.track('Schedule', {
    contentName: 'Visita Agendada — [NOME DO EMPREENDIMENTO]',
    contentCategory: 'imovel',
    funnel_stage: 'schedule_confirmed',
    intentionLevel: 'comprador',
    email: data.get('email'),
    phone: data.get('phone'),
    firstName: data.get('nome')?.split(' ')[0],
  });
  e.target.submit();
});
```

---

### 2.9 Lead — Formulário Principal de Interesse
```javascript
document.querySelector('#form-interesse, #form-lead, form.form-contato')?.addEventListener('submit', async (e) => {
  e.preventDefault();

  await cdpTrack.track('Lead', {
    // PII — enviados hasheados pelo Worker
    email:     e.target.email?.value?.trim(),
    phone:     e.target.phone?.value?.trim() || e.target.telefone?.value?.trim(),
    firstName: e.target.nome?.value?.split(' ')[0]?.trim(),
    lastName:  e.target.nome?.value?.split(' ').slice(1).join(' ')?.trim(),

    // Contexto
    contentName:     '[NOME DO EMPREENDIMENTO]',
    contentCategory: 'imovel',
    intentionLevel:  'comprador',
    funnel_stage:    'lead_form',

    // UTMs capturados pelo SDK automaticamente
    // Coordenadas do imóvel para distância geoespacial no Worker:
    property_lat: -23.5505,
    property_lng: -46.6333,
  });

  // Redirecionar para obrigado
  window.location.href = '/obrigado';
});
```

---

## 📊 LTV por Evento — O que o Worker calcula

| Evento | Bonus LTV Score | Multiplicador Valor |
|---|---|---|
| `Lead` (utm_source=facebook, intention=comprador) | ~65–80 pts | 3.5× → **High** |
| `CustomizeProduct` | +15 pts automático | Score sobe para High |
| `FindLocation` | +10 pts automático | Puxa Medium → High |
| `AddToWishlist` | +8 pts automático | Sinal de retargeting |
| `Schedule` (visita confirmada) | intention=comprador → +20 pts | Máximo High |
| `Contact` (WhatsApp) | Sem LTV (evento de sinal) | — |

---

## 🔄 FLUXO COMPLETO DO LEAD IMOBILIÁRIO

```
Usuário chega na landing
  │
  ├─ PageView → sinal de alcance
  ├─ ViewContent (galeria) → interesse qualificado
  ├─ video_50 (tour) → engajamento profundo
  ├─ FindLocation (mapa) → intenção de visita física (+10 LTV)
  ├─ CustomizeProduct (simulador) → intenção máxima (+15 LTV)
  ├─ Contact (WhatsApp) → ação de contato
  ├─ Schedule (agendamento) → visita confirmada
  └─ Lead (formulário) → conversão principal
        │
        ▼
  Worker: LTV score ~75-90 → High → valor 3.5× injetado
        │
        ▼
  Meta CAPI + GA4 + TikTok recebem Lead com value=R$689
        │
        ▼
  Algoritmo de Meta aprende a buscar mais leads de alto valor
```

---

## 📋 CHECKLIST DE IMPLEMENTAÇÃO

- [ ] SDK `cdpTrack.js` carregando no `<head>`
- [ ] `PageView` disparando (automático)
- [ ] `ViewContent` na galeria
- [ ] `FindLocation` no mapa e botão "Como chegar"
- [ ] Vídeo/tour instrumentado (`video_25`, `video_75`, `video_complete`)
- [ ] `CustomizeProduct` no simulador de financiamento
- [ ] `AddToWishlist` no botão de favoritar
- [ ] `Contact` nos botões de WhatsApp e telefone
- [ ] `Schedule` no calendário (Calendly ou formulário próprio)
- [ ] `Lead` no formulário principal com PII e `property_lat/lng`
- [ ] Verificar `/health` retornando `d1: ok, kv: ok, ai: ok`
- [ ] Testar evento `Lead` no Meta Events Manager → Test Events
- [ ] Confirmar LTV na resposta JSON do `/track` (`class: "High"`)
