﻿// Clientes — extended Customer 360 dataset

// Counts computados dinamicamente em clientes-list.jsx
const CLIENTES_FILTERS = [
  { id: 'all',      label: 'Todos' },
  { id: 'hot',      label: 'Quentes',    dot: '#ff5a4e' },
  { id: 'analysis', label: 'Em análise' },
  { id: 'visit',    label: 'Com visita' },
  { id: 'approved', label: 'Aprovados' },
  { id: 'closed',   label: 'Fechados' },
];

// Property catalog (used by IA compatibility engine)
const PROPS = [
  { id: 'P01', name: 'Apartamento Alpha',  loc: 'Vila Madalena, SP',   value: 1180000, parc: 6800, grad: ['#1F93FF','#3b82f6'], type: 'Cobertura · 3Q · 142m²', tag: 'Lançamento' },
  { id: 'P02', name: 'Residencial Vista',  loc: 'Pinheiros, SP',       value: 980000,  parc: 5600, grad: ['#ec4899','#f43f5e'], type: 'Apto · 3Q · 118m²',     tag: 'Pronto' },
  { id: 'P03', name: 'Green Park',         loc: 'Perdizes, SP',        value: 850000,  parc: 4900, grad: ['#10b981','#06b6d4'], type: 'Apto · 2Q · 96m²',      tag: 'Pronto' },
  { id: 'P04', name: 'Mirante Faria Lima', loc: 'Itaim Bibi, SP',      value: 1620000, parc: 9400, grad: ['#f59e0b','#ef4444'], type: 'Cobertura · 4Q · 198m²', tag: 'Lançamento' },
  { id: 'P05', name: 'Jardins Premium',    loc: 'Jardins, SP',         value: 2100000, parc: 12200,grad: ['#8b5cf6','#7c3aed'], type: 'Duplex · 4Q · 234m²',   tag: 'Exclusivo' },
  { id: 'P06', name: 'Reserva Sul',        loc: 'Moema, SP',           value: 720000,  parc: 4100, grad: ['#22d3ee','#0ea5e9'], type: 'Apto · 2Q · 78m²',      tag: 'Pronto' },
];

// Full Customer 360 records
const CLIENTES = [
  {
    id: 'C01',
    name: 'Helena Duarte',
    initials: 'HD',
    palette: ['#ec4899','#f43f5e'],
    cpf: '***.456.***-12',
    email: 'helena.duarte@gmail.com',
    phone: '+55 11 98765-4321',
    birth: '14/03/1986',
    civil: 'Casada',
    profession: 'Diretora de Marketing',
    company: 'Atlas Digital',
    deps: 1,
    firstBuy: true,
    region: 'Vila Madalena · Pinheiros',
    desired: 1200000,
    entry: 320000,
    renda: 32000,
    rendaFam: 58000,
    notes: 'Acompanhada desde abril. Visitou 3 imóveis. Pronta para receber contrato. Score IA subiu de 76 para 93 nas últimas 48h.',
    broker: 'Daniel Oliveira',
    temp: 'hot',
    score: 93,
    seg: 'Imobiliário',
    status: 'proposal',
    statusLabel: 'Em proposta',
    nextAction: 'Enviar contrato',
    nextWhen: 'Hoje · 14:00',
    urgency: 'now',
    last: 'há 20min',
    wa: true,
    credit: {
      origin: 'CCA · integração automática',
      status: 'approved',
      approved: 1180000,
      entry: 320000,
      maxParc: 6800,
      bank: 'Itaú Unibanco',
      term: '360 meses',
      analysisDate: '12 mai 2026',
      score: 920,
      tier: 'Excelente',
      commit: '11%',
      note: 'Cliente apto para financiamento. Renda comprovada, comprometimento dentro da política do banco.',
      docs: [
        { label: 'CPF / RG', ok: true },
        { label: 'Comprovante de renda', ok: true },
        { label: 'Certidão negativa', ok: true },
        { label: 'SCR Banco Central', ok: true },
      ],
    },
    matches: ['P01:97','P02:89','P03:76','P04:64'],
    timeline: [
      ['10:20', 'Lead criado',                       'system'],
      ['11:30', 'Primeiro contato realizado',        'broker'],
      ['12:45', 'Documentação enviada pelo cliente', 'client'],
      ['13:50', 'Análise de crédito iniciada (CCA)', 'system'],
      ['14:30', 'Crédito aprovado · R$1.18M',        'ai'],
      ['16:00', 'Visita agendada · Apto Alpha',      'broker'],
    ],
    messages: [
      { from: 'cliente',  text: 'Oi, ainda está disponível o apto frente-mar?', time: '09:14' },
      { from: 'ia',       text: 'Olá Helena! Sim, segue disponível. Quer remarcar a visita?', time: '09:15' },
      { from: 'cliente',  text: 'Sim, pode ser hoje à tarde?', time: '09:18' },
      { from: 'corretor', text: 'Helena, agendei para 15h. Confirma?', time: '09:22' },
      { from: 'cliente',  text: 'Confirmo!', time: '09:24' },
      { from: 'ia',       text: 'Visita confirmada para hoje 15h ✓ Lembrete enviado.', time: '09:25' },
      { from: 'cliente',  text: 'Daniel, e o contrato? Conseguimos avançar?', time: '12:48' },
      { from: 'corretor', text: 'Claro Helena, posso enviar ainda hoje após a visita.', time: '12:51' },
    ],
    insights: [
      { kind: 'hot',    label: 'Alta chance de fechamento', detail: '94% segundo modelo · top 3% da base' },
      { kind: 'warn',   label: 'Sem resposta há 6h',         detail: 'Último contato 12:51 · ação sugerida: ligação' },
      { kind: 'match',  label: 'Compatibilidade com 4 imóveis', detail: '1 acima de 95% · 3 acima de 70%' },
      { kind: 'money',  label: 'Entrada acima da média',     detail: 'R$320k · 27% do imóvel desejado' },
    ],
  },

  {
    id: 'C02',
    name: 'Lucas Pereira',
    initials: 'LP',
    palette: ['#1F93FF','#3b82f6'],
    cpf: '***.221.***-87',
    email: 'lucas@startup.co',
    phone: '+55 11 97654-3210',
    birth: '02/11/1991',
    civil: 'Solteiro',
    profession: 'CEO',
    company: 'Atlas Capital',
    deps: 0,
    firstBuy: false,
    region: 'Itaim Bibi · Faria Lima',
    desired: 1800000,
    entry: 500000,
    renda: 280000,
    rendaFam: 280000,
    notes: 'CEO startup série A. Busca expansão. Estrutura híbrida (FIDC + capital de giro).',
    broker: 'Daniel Oliveira',
    temp: 'hot',
    score: 91,
    seg: 'Crédito PJ',
    status: 'engaged',
    statusLabel: 'Engajado',
    nextAction: 'Reunião com sócios',
    nextWhen: 'Amanhã · 10:30',
    urgency: 'soon',
    last: 'há 15min',
    wa: true,
    credit: {
      origin: 'CCA · análise PJ',
      status: 'analysis',
      approved: 1620000,
      entry: 500000,
      maxParc: 9400,
      bank: 'Bradesco',
      term: '240 meses',
      analysisDate: '20 mai 2026',
      score: 870,
      tier: 'Muito bom',
      commit: '22%',
      note: 'Cliente PJ. Aprovação preliminar. Aguardando assinatura digital.',
      docs: [
        { label: 'CNPJ ativo', ok: true },
        { label: 'Balanço últimos 2 anos', ok: true },
        { label: 'DRE 2025', ok: true },
        { label: 'SCR Banco Central', ok: true },
      ],
    },
    matches: ['P04:94','P05:88','P01:72','P02:65'],
    timeline: [
      ['08:15', 'Lead criado',                'system'],
      ['08:34', 'Corretor respondeu em 3min', 'broker'],
      ['08:37', 'IA atualizou agenda',        'ai'],
      ['09:12', 'IA preparou resumo financeiro', 'ai'],
      ['11:48', 'Score IA 84 → 91',           'system'],
    ],
    messages: [
      { from: 'cliente',  text: 'Daniel, conseguimos avançar com a proposta?', time: '08:31' },
      { from: 'corretor', text: 'Lucas, preparei duas alternativas. Amanhã 10:30?', time: '08:34' },
      { from: 'cliente',  text: 'Perfeito, vou alinhar com os sócios.', time: '08:36' },
      { from: 'ia',       text: 'Reunião confirmada · convites enviados.', time: '08:37' },
    ],
    insights: [
      { kind: 'hot',   label: 'Cliente em decisão',           detail: 'Reunião com sócios marcada para amanhã' },
      { kind: 'match', label: 'Match alto com Mirante',       detail: '94% de compatibilidade · ticket R$1.62M' },
      { kind: 'money', label: 'Capacidade acima do desejado', detail: 'CCA aprovou R$1.62M · cliente pediu R$1.8M' },
    ],
  },

  {
    id: 'C03',
    name: 'Camila Reis',
    initials: 'CR',
    palette: ['#8b5cf6','#ec4899'],
    cpf: '***.118.***-44',
    email: 'camila.reis@me.com',
    phone: '+55 11 99988-7766',
    birth: '21/08/1979',
    civil: 'Divorciada',
    profession: 'Advogada',
    company: 'Reis Advocacia',
    deps: 2,
    firstBuy: false,
    region: 'Jardins · Vila Olímpia',
    desired: 2100000,
    entry: 600000,
    renda: 48000,
    rendaFam: 48000,
    notes: 'Avaliando 3 imóveis em paralelo. Sensível a localização e segurança.',
    broker: 'Bruna Tavares',
    temp: 'hot',
    score: 88,
    seg: 'Imobiliário',
    status: 'engaged',
    statusLabel: 'Engajado',
    nextAction: 'Follow-up visita',
    nextWhen: 'Hoje · 17:00',
    urgency: 'now',
    last: 'há 1h',
    wa: true,
    credit: {
      origin: 'CCA · integração automática',
      status: 'approved',
      approved: 2050000,
      entry: 600000,
      maxParc: 12200,
      bank: 'Santander',
      term: '360 meses',
      analysisDate: '18 mai 2026',
      score: 880,
      tier: 'Muito bom',
      commit: '18%',
      note: 'Aprovado. Aguardando definição do imóvel.',
      docs: [
        { label: 'CPF / RG', ok: true },
        { label: 'Comprovante de renda', ok: true },
        { label: 'Certidão negativa', ok: false },
        { label: 'SCR Banco Central', ok: true },
      ],
    },
    matches: ['P05:96','P04:84','P02:71'],
    timeline: [
      ['11:00', 'Lead criado',                  'system'],
      ['11:03', 'Corretora respondeu em 1min',  'broker'],
      ['11:06', 'IA agendou lembrete para 17h', 'ai'],
      ['12:30', 'IA detectou intenção de comparação', 'ai'],
    ],
    messages: [
      { from: 'cliente',  text: 'Bruna, recebi outras propostas. Pode conversar?', time: '11:02' },
      { from: 'corretor', text: 'Claro Camila, posso te ligar agora?', time: '11:03' },
      { from: 'cliente',  text: 'Hoje 17h fica melhor.', time: '11:05' },
      { from: 'ia',       text: 'Lembrete agendado para 17h.', time: '11:06' },
    ],
    insights: [
      { kind: 'warn',  label: 'Comparando 3 propostas',      detail: 'IA detectou risco de churn · ação urgente' },
      { kind: 'match', label: 'Jardins Premium · 96% match', detail: 'Pronto para enviar · valor compatível' },
      { kind: 'hot',   label: 'Capacidade premium',          detail: 'Aprovada até R$2.05M · ticket alto' },
    ],
  },

  // Lighter records for table density
  {
    id: 'C04', name: 'Tiago Vieira', initials: 'TV', palette: ['#22d3ee','#1F93FF'],
    cpf: '***.665.***-21', email: 'tiago.v@outlook.com', phone: '+55 31 98123-4567',
    seg: 'Imobiliário', cat: 'Casa em condomínio', desired: 1450000, broker: 'Daniel Oliveira',
    temp: 'hot', score: 84, status: 'qualifying', statusLabel: 'Qualificando',
    nextAction: 'Agendar visita', nextWhen: 'Quinta · 09:00', urgency: '',
    creditStatus: 'approved', creditValue: 1380000, region: 'Granja Viana',
  },
  {
    id: 'C05', name: 'Mariana Freitas', initials: 'MF', palette: ['#f59e0b','#ef4444'],
    cpf: '***.992.***-08', email: 'mari.freitas@gmail.com', phone: '+55 47 99654-1122',
    seg: 'Imobiliário', cat: 'Apartamento 2Q', desired: 520000, broker: 'Bruna Tavares',
    temp: 'hot', score: 96, status: 'won', statusLabel: 'Ganho',
    nextAction: 'Pós-venda · NPS', nextWhen: 'Sex · 11:00', urgency: '',
    creditStatus: 'approved', creditValue: 520000, region: 'Balneário',
  },
  {
    id: 'C06', name: 'Júlia Carvalho', initials: 'JC', palette: ['#22d3ee','#1F93FF'],
    cpf: '***.451.***-71', email: 'julia.c@empresa.br', phone: '+55 11 98765-1010',
    seg: 'Crédito', cat: 'Refinanciamento', desired: 620000, broker: 'Daniel Oliveira',
    temp: 'hot', score: 81, status: 'proposal', statusLabel: 'Em proposta',
    nextAction: 'Análise documentos', nextWhen: 'Hoje · 18:30', urgency: 'now',
    creditStatus: 'analysis', creditValue: 580000, region: 'Higienópolis',
  },
  {
    id: 'C07', name: 'Diogo Almeida', initials: 'DA', palette: ['#14b8a6','#3b82f6'],
    cpf: '***.207.***-33', email: 'diogo.a@protonmail.com', phone: '+55 81 99221-3344',
    seg: 'Consórcio', cat: 'Imóvel R$ 500k', desired: 500000, broker: 'Carla Mendes',
    temp: 'warm', score: 71, status: 'qualifying', statusLabel: 'Qualificando',
    nextAction: 'Apresentar carta', nextWhen: 'Qua · 15:00', urgency: 'soon',
    creditStatus: 'pending', creditValue: 0, region: 'Boa Viagem',
  },
  {
    id: 'C08', name: 'Bruno Tavares', initials: 'BT', palette: ['#f97316','#eab308'],
    cpf: '***.840.***-12', email: 'bruno.t@gmail.com', phone: '+55 51 99887-1122',
    seg: 'Veículos', cat: 'Pickup 4x4', desired: 285000, broker: 'Daniel Oliveira',
    temp: 'warm', score: 67, status: 'engaged', statusLabel: 'Engajado',
    nextAction: 'Test drive', nextWhen: 'Sáb · 10:00', urgency: '',
    creditStatus: 'approved', creditValue: 260000, region: 'Centro POA',
  },
  {
    id: 'C09', name: 'Sofia Martins', initials: 'SM', palette: ['#f43f5e','#fb7185'],
    cpf: '***.504.***-66', email: 'sofia.m@empresa.com', phone: '+55 21 99543-6677',
    seg: 'Seguros', cat: 'Empresarial', desired: 96000, broker: 'Bruna Tavares',
    temp: 'warm', score: 79, status: 'engaged', statusLabel: 'Engajado',
    nextAction: 'Renovação anual', nextWhen: 'Próx semana', urgency: '',
    creditStatus: 'na', creditValue: 0, region: '—',
  },
  {
    id: 'C10', name: 'André Nogueira', initials: 'AN', palette: ['#a855f7','#7c3aed'],
    cpf: '***.116.***-55', email: 'andre.n@gmail.com', phone: '+55 11 99887-2211',
    seg: 'Consórcio', cat: 'Veículo R$ 180k', desired: 180000, broker: 'Carla Mendes',
    temp: 'warm', score: 76, status: 'proposal', statusLabel: 'Em proposta',
    nextAction: 'Enviar simulação', nextWhen: 'Amanhã · 09:00', urgency: 'soon',
    creditStatus: 'analysis', creditValue: 150000, region: 'Tatuapé',
  },
];

// helper: get property by ID:score string
const getMatch = (s) => {
  const [pid, sc] = s.split(':');
  const p = PROPS.find(x => x.id === pid);
  return p ? { ...p, match: parseInt(sc, 10) } : null;
};

const cliFmt = (v) => {
  if (!v) return '—';
  if (v >= 1000000) return `R$ ${(v/1000000).toFixed(2).replace('.', ',')}M`;
  if (v >= 1000) return `R$ ${Math.round(v/1000)}k`;
  return `R$ ${v}`;
};

Object.assign(window, { CLIENTES, CLIENTES_FILTERS, PROPS, getMatch, cliFmt });
