/* Painel de Leads — dashboard */

const KpiCard = ({ icon: I, label, value, delta, color, spark, sparkColor, big }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const positive = delta && !delta.startsWith('-');
  return (
    <Card style={{ padding: 18, position: 'relative', overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <div style={{
          width: 38, height: 38, borderRadius: isBloom ? 10 : 10,
          background: color + (isBloom ? '' : '22'),
          border: isBloom ? `1.5px solid ${t.border}` : 'none',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <I size={18} stroke={isBloom ? t.text : color}/>
        </div>
        {delta && (
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            fontSize: 11, fontWeight: 700, fontFamily: t.fontMono,
            color: positive ? t.green : t.red,
            background: positive ? t.greenSoft : 'rgba(248,113,113,0.14)',
            padding: '3px 7px', borderRadius: 99,
            border: isBloom ? `1.5px solid ${t.border}` : 'none',
          }}>
            {positive ? '↑' : '↓'} {delta}
          </span>
        )}
      </div>
      <div style={{ fontFamily: t.fontDisplay, fontSize: big ? 40 : 32, fontWeight: 700, color: t.text, letterSpacing: '-0.03em', lineHeight: 1 }}>
        {value}
      </div>
      <div style={{ marginTop: 6, fontSize: 12.5, color: t.textMuted, fontWeight: 500 }}>{label}</div>
      {spark && (
        <div style={{ marginTop: 12, marginLeft: -2 }}>
          <Sparkline values={spark} color={sparkColor || color} width={200} height={28} fill/>
        </div>
      )}
    </Card>
  );
};

const FunnelStep = ({ label, value, total, color, icon, isLast }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const pct = Math.round((value / total) * 100);
  const I = Icons[icon];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
      <div style={{
        width: 36, height: 36, borderRadius: isBloom ? 10 : 10, flexShrink: 0,
        background: color + (isBloom ? '' : '22'),
        border: isBloom ? `1.5px solid ${t.border}` : 'none',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <I size={17} stroke={isBloom ? t.text : color}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 5 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{label}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontFamily: t.fontMono, fontSize: 11, color: t.textMuted }}>{pct}%</span>
            <span style={{ fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>{value}</span>
          </div>
        </div>
        <div style={{ height: 8, background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.05)', borderRadius: 99,
          border: isBloom ? `1.5px solid ${t.border}` : 'none', overflow: 'hidden' }}>
          <div style={{ width: pct + '%', height: '100%', background: color, borderRadius: 99 }}/>
        </div>
      </div>
    </div>
  );
};

const Heatmap = ({ data: apiData }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const days = ['SEG','TER','QUA','QUI','SEX','SAB','DOM'];
  
  const defaultMatrix = Array.from({ length: 7 }, () => Array(24).fill(0));
  const matrix = (apiData && apiData.matrix) ? apiData.matrix : defaultMatrix;
  const peak = (apiData && apiData.peak) ? apiData.peak : { day: 'SEG', hour: 0, intensity: 0 };

  return (
    <div>
      <div style={{ display: 'flex', gap: 4, marginBottom: 6 }}>
        <div style={{ width: 32 }}/>
        {[0,3,6,9,12,15,18,21].map(h => (
          <div key={h} style={{ flex: '1 0 0', textAlign: 'left', fontSize: 9, color: t.textMuted, fontFamily: t.fontMono }}>{h}h</div>
        ))}
      </div>
      {matrix.map((row, di) => (
        <div key={di} style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 3 }}>
          <div style={{ width: 32, fontSize: 10, color: t.textMuted, fontFamily: t.fontMono, fontWeight: 600 }}>{days[di]}</div>
          {row.map((v, hi) => (
            <div key={hi} style={{
              flex: '1 0 0', aspectRatio: '1', borderRadius: 3,
              background: `rgba(91,141,239,${v})`,
              border: isBloom ? `1.5px solid ${t.border}` : 'none',
            }}/>
          ))}
        </div>
      ))}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 10, fontSize: 11, color: t.textMuted }}>
        <span>Menos</span>
        {[0.15, 0.35, 0.6, 0.85, 1].map(v => (
          <div key={v} style={{ width: 14, height: 14, borderRadius: 3, background: `rgba(91,141,239,${v})` }}/>
        ))}
        <span>Mais</span>
        <span style={{ marginLeft: 'auto', fontFamily: t.fontMono }}>Pico: <strong style={{color: t.text}}>{peak.day} · {peak.hour}h–{peak.hour+1}h</strong></span>
      </div>
    </div>
  );
};

const LiveAiFeed = ({ aiLive, leads }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  
  let items = [];
  if (aiLive && aiLive.length > 0) {
    items = aiLive.map(item => ({
      who: item.leadName,
      stage: item.stage,
      stageColor: item.stageColor || t.primary,
      time: item.startedAt ? new Date(item.startedAt).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }) : 'agora',
      typing: item.typing
    }));
  } else {
    // Fallback inteligente para dados locais se o feed de IA em tempo real estiver vazio
    items = (leads || []).filter(l => l.conversionProb || l.aiActive).slice(0, 5).map(l => ({
      who: l.name,
      stage: l.conversionProb ? `${l.conversionProb}% conversão` : (l.temp || 'analisando'),
      stageColor: l.temp === 'quente' ? t.orange : (l.temp === 'morno' ? t.primary : t.textMuted),
      time: l.lastMessageAt ? new Date(l.lastMessageAt).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }) : 'agora',
      typing: l.aiActive && Math.random() > 0.5,
    }));
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {items.map((it, i) => (
        <div key={i} style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: 12, borderRadius: t.radiusMd,
          background: isBloom ? t.bg : 'rgba(255,255,255,0.025)',
          border: isBloom ? `1.5px solid ${t.border}` : '1px solid rgba(255,255,255,0.04)',
        }}>
          <div style={{
            width: 30, height: 30, borderRadius: isBloom ? 8 : '50%',
            background: `linear-gradient(135deg, ${t.green}, ${t.primary})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: isBloom ? `1.5px solid ${t.border}` : 'none',
            position: 'relative',
          }}>
            <Icons.Sparkles size={14} stroke="#fff"/>
            {it.typing && (
              <span style={{
                position: 'absolute', inset: -3, borderRadius: isBloom ? 11 : '50%',
                border: `2px solid ${t.green}`, animation: 'ringPulse 1.5s ease-out infinite',
              }}/>
            )}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{it.who}</div>
            <div style={{ fontSize: 12, color: t.textMuted, marginTop: 1 }}>
              IA <span style={{ color: it.stageColor, fontWeight: 600 }}>{it.stage}</span>
            </div>
          </div>
          {it.typing ? (
            <div style={{ display: 'flex', gap: 3 }}>
              {[0,1,2].map(j => (
                <span key={j} style={{
                  width: 5, height: 5, borderRadius: '50%', background: t.green,
                  animation: `typing 1.4s ease-in-out ${j*0.2}s infinite`,
                }}/>
              ))}
            </div>
          ) : (
            <span style={{ fontFamily: t.fontMono, fontSize: 11, color: t.textMuted }}>{it.time}</span>
          )}
        </div>
      ))}
      <style>{`
        @keyframes typing { 0%, 60%, 100% { opacity: 0.3; transform: translateY(0) } 30% { opacity: 1; transform: translateY(-3px) } }
        @keyframes ringPulse { 0% { opacity: 1; transform: scale(1) } 100% { opacity: 0; transform: scale(1.4) } }
      `}</style>
    </div>
  );
};

const LeadRow = ({ lead, onClick }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const tempColor = { quente: t.orange, morno: t.primary, frio: t.textDim, fechado: t.green }[lead.temp];
  return (
    <div onClick={onClick} style={{
      display: 'grid', gridTemplateColumns: '2.5fr 1fr 1.4fr 1fr 1fr 0.6fr',
      gap: 14, padding: '12px 16px', alignItems: 'center', cursor: 'pointer',
      borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
      transition: 'background 0.1s',
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.02)'}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
        <Avatar name={lead.avatar} color={lead.color} size={34} ai={lead.aiActive}/>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text, letterSpacing: '-0.01em' }}>{lead.name}</div>
          <div style={{ fontSize: 11.5, color: t.textMuted, fontFamily: t.fontMono }}>{lead.phone}</div>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <ScoreRing value={lead.score} size={32}/>
        <Pill soft={tempColor + (isBloom ? '' : '22')} color={isBloom ? t.text : tempColor}>
          {lead.temp === 'quente' && <Icons.Fire size={11} stroke={isBloom ? t.text : tempColor}/>}
          {lead.temp === 'morno' && <span style={{width:8,height:8,borderRadius:'50%',background:tempColor}}/>}
          {lead.temp === 'frio' && <span style={{width:8,height:8,borderRadius:'50%',background:tempColor}}/>}
          {lead.temp === 'fechado' && <Icons.Check size={11} stroke={isBloom ? t.text : tempColor}/>}
          {lead.temp}
        </Pill>
      </div>
      <div style={{ fontSize: 12.5, color: t.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {lead.objective}
      </div>
      <div style={{ fontSize: 12, color: t.textMuted, fontFamily: t.fontMono }}>{lead.lastTime}</div>
      <div>
        {lead.aiActive ? (
          <Pill soft={t.greenSoft} color={isBloom ? t.text : t.green}>
            <Icons.Sparkles size={11} stroke={isBloom ? t.text : t.green}/> IA ativa
          </Pill>
        ) : (
          <Pill soft={isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.04)'} color={t.textMuted}>
            Humano
          </Pill>
        )}
      </div>
      <div style={{ textAlign: 'right' }}>
        <Icons.ArrowRight size={16} stroke={t.textMuted}/>
      </div>
    </div>
  );
};

const Dashboard = ({ onOpenLead }) => {
  const t = useTheme();
  const { showToast } = useToast();
  const isBloom = t.name === 'BLOOM';
  
  const [dateRange, setDateRange] = React.useState('all');
  const [exportOpen, setExportOpen] = React.useState(false);
  const [dateOpen, setDateOpen] = React.useState(false);
  
  // Estado para o filtro de temperatura comercial
  const [tempFilter, setTempFilter] = React.useState('todos');

  const { data: apiLeads, loading: loadingLeads } = useLeads({ range: dateRange });
  const { data: kpiData } = useDashboardKpis(dateRange);
  const { data: aiLive } = useAiLive();
  const { data: heatmapData } = useDashboardHeatmap(dateRange);
  const { data: funnelData } = useDashboardFunnel(dateRange);
  const { data: aiPerf } = typeof useAiPerformance !== 'undefined' ? useAiPerformance(dateRange) : { data: null };
  const leads = (apiLeads && apiLeads.data) ? apiLeads.data : (Array.isArray(apiLeads) ? apiLeads : []);

  // Filtragem dinâmica de leads para a tabela comercial
  const filteredLeads = leads.filter(l => {
    if (tempFilter === 'todos') return true;
    if (tempFilter === 'quente') return l.temp === 'quente';
    if (tempFilter === 'morno') return l.temp === 'morno';
    if (tempFilter === 'frio') return l.temp === 'frio';
    return true;
  });

  if (loadingLeads) return <div style={{padding: 40, color: t.text}}>Carregando dashboard...</div>;

  const quentes = leads.filter(l => l.temp === 'quente').length;
  const newLeads = kpiData ? kpiData.newLeads.value : leads.length;
  const messages = kpiData ? kpiData.messages.value : 0;
  const pipeline = kpiData ? (kpiData.pipeline.value_cents / 100).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) : 'R$ 0,00';

  const formatPhone = (p) => {
    if (!p) return '-';
    let digits = p.replace(/\D/g, '');
    
    // Se for formato Brasileiro (55)
    if (digits.startsWith('55') && (digits.length === 12 || digits.length === 13)) {
      const ddd = digits.slice(2, 4);
      const number = digits.slice(4);
      if (number.length === 9) return `+55 (${ddd}) ${number.slice(0,5)}-${number.slice(5)}`;
      if (number.length === 8) return `+55 (${ddd}) ${number.slice(0,4)}-${number.slice(4)}`;
    }
    
    // Se for internacional (ex: DDI 82, 20, etc) ou DDI+DDD
    if (digits.length >= 10 && !digits.startsWith('55')) {
       // Coloca um + na frente e separa o código do país para ficar com cara de telefone real
       return `+${digits.slice(0,2)} ${digits.slice(2, 4)} ${digits.slice(4, 9)}-${digits.slice(9)}`;
    }
    
    return `+${digits}`; // Garante que o Excel não trate como "numero aleatório gigante de matemática"
  };

  const exportExcel = () => {
    try {
      // Gerando Excel Premium via HTML Table string (permite injeção de CSS nativo lido pelo MS Excel)
      const tableRows = leads.map(l => `
        <tr>
          <td style="padding: 10px; border-bottom: 1px solid #E2E8F0; color: #1E293B; font-family: sans-serif;">${l.name}</td>
          <td style="padding: 10px; border-bottom: 1px solid #E2E8F0; color: #334155; font-family: monospace;">${formatPhone(l.phone)}</td>
          <td style="padding: 10px; border-bottom: 1px solid #E2E8F0; color: #64748B;">${l.temp.toUpperCase()}</td>
          <td style="padding: 10px; border-bottom: 1px solid #E2E8F0; color: #64748B;">${l.stage.toUpperCase()}</td>
          <td style="padding: 10px; border-bottom: 1px solid #E2E8F0; color: #1E293B; font-weight: bold;">${l.score} pts</td>
        </tr>
      `).join('');

      const html = `
        <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
        <head>
          <meta charset="utf-8" />
          <style>
            .header { background-color: #0F172A; color: #FFFFFF; font-weight: bold; font-family: sans-serif; font-size: 14px; text-align: left; }
            .header th { padding: 12px; border: 1px solid #0F172A; }
          </style>
        </head>
        <body>
          <h2 style="font-family: sans-serif; color: #0F172A;">FluxoZap - Relatório de Leads</h2>
          <p style="font-family: sans-serif; color: #64748B;">Período: ${ranges[dateRange]} | Gerado em: ${new Date().toLocaleString('pt-BR')}</p>
          <table style="border-collapse: collapse; width: 100%;">
            <thead>
              <tr class="header">
                <th style="width: 250px;">Nome do Lead</th>
                <th style="width: 200px;">WhatsApp Oficial</th>
                <th style="width: 150px;">Temperatura</th>
                <th style="width: 200px;">Fase no Funil</th>
                <th style="width: 120px;">Score</th>
              </tr>
            </thead>
            <tbody>
              ${tableRows}
            </tbody>
          </table>
        </body>
        </html>
      `;

      const blob = new Blob([html], { type: 'application/vnd.ms-excel' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'FluxoZap_Leads_Premium.xls';
      a.click();
      URL.revokeObjectURL(url);
      
      showToast('Planilha Excel Premium exportada!', 'success');
    } catch(e) {
      console.error(e);
      showToast('Erro ao exportar Excel');
    }
    setExportOpen(false);
  };

  const exportPDF = () => {
    try {
      const doc = new window.jspdf.jsPDF();
      
      // Cabeçalho premium
      doc.setFillColor(7, 9, 15);
      doc.rect(0, 0, 210, 40, 'F');
      doc.setTextColor(255, 255, 255);
      doc.setFont("helvetica", "bold");
      doc.setFontSize(24);
      doc.text("FLUXOZAP", 14, 25);
      
      doc.setFont("helvetica", "normal");
      doc.setFontSize(10);
      doc.setTextColor(150, 150, 150);
      doc.text("Inteligência em Vendas", 14, 32);

      // Metadados
      doc.setTextColor(50, 50, 50);
      doc.setFontSize(12);
      doc.setFont("helvetica", "bold");
      doc.text("RELATÓRIO DE LEADS E CONVERSÕES", 14, 52);
      
      doc.setFont("helvetica", "normal");
      doc.setFontSize(10);
      doc.text(`Período de Análise: ${ranges[dateRange]}`, 14, 60);
      doc.text(`Gerado em: ${new Date().toLocaleString('pt-BR', { timeZone: 'America/Sao_Paulo' })}`, 14, 66);

      // Caixas de Resumo
      doc.setDrawColor(220, 220, 220);
      doc.setFillColor(245, 247, 250);
      doc.roundedRect(14, 72, 55, 20, 3, 3, 'FD');
      doc.roundedRect(75, 72, 55, 20, 3, 3, 'FD');
      doc.roundedRect(136, 72, 55, 20, 3, 3, 'FD');

      doc.setFontSize(18);
      doc.setFont("helvetica", "bold");
      doc.setTextColor(30, 30, 30);
      doc.text(`${newLeads}`, 20, 82);
      doc.text(`${quentes}`, 81, 82);
      doc.text(`${pipeline}`, 142, 82);

      doc.setFontSize(9);
      doc.setFont("helvetica", "normal");
      doc.setTextColor(100, 100, 100);
      doc.text("TOTAL DE LEADS", 20, 88);
      doc.text("LEADS QUENTES", 81, 88);
      doc.text("PIPELINE (R$)", 142, 88);

      // Tabela de Dados
      const tableData = leads.map(l => [
        l.name, 
        formatPhone(l.phone), 
        l.temp.toUpperCase(), 
        l.stage.toUpperCase(), 
        l.score + ' pts'
      ]);
      
      doc.autoTable({
        startY: 100,
        head: [['Nome do Lead', 'WhatsApp', 'Temp.', 'Fase Atual', 'Score']],
        body: tableData,
        theme: 'grid',
        headStyles: { fillColor: [20, 20, 25], textColor: 255, fontSize: 10, fontStyle: 'bold' },
        bodyStyles: { fontSize: 9, textColor: 50 },
        alternateRowStyles: { fillColor: [250, 250, 250] },
      });
      
      // Rodapé
      const pageCount = doc.internal.getNumberOfPages();
      for(let i = 1; i <= pageCount; i++) {
        doc.setPage(i);
        doc.setFontSize(8);
        doc.setTextColor(150);
        doc.text(`Página ${i} de ${pageCount} - FluxoZap CRM`, 14, 290);
      }

      doc.save('FluxoZap_Relatorio.pdf');
      showToast('Relatório PDF exportado!', 'success');
    } catch(e) {
      console.error(e);
      showToast('Erro ao exportar PDF');
    }
    setExportOpen(false);
  };

  const ranges = { '1d': 'Hoje', '7d': 'Últimos 7 dias', '30d': 'Últimos 30 dias', 'all': 'Todo o período' };


  return (
    <div style={{ padding: '24px 28px 40px', maxWidth: 1480, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24, gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <Status ok label="Assistente IA online · respondendo em ~8s"/>
            <span style={{ fontSize: 11, color: t.textMuted, fontFamily: t.fontMono }}>· {new Date().toLocaleDateString('pt-BR', { weekday: 'long', day: '2-digit', month: 'short', year: 'numeric' }).toUpperCase()}</span>
          </div>
          <h1 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 36, fontWeight: 700, letterSpacing: '-0.03em', color: t.text }}>
            Bom dia. <span style={{ color: t.textMuted, fontWeight: 600 }}>{quentes} leads quentes</span>{' '}
            <span style={{ color: t.text }}>esperando você.</span>
          </h1>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <div style={{ position: 'relative' }}>
            <Btn variant="secondary" icon={<Icons.Calendar size={14}/>} onClick={() => setDateOpen(!dateOpen)}>
              {ranges[dateRange]}
            </Btn>
            {dateOpen && (
              <div style={{
                position: 'absolute', top: '100%', right: 0, marginTop: 8, zIndex: 100,
                background: t.surface, border: `1px solid ${t.border}`, borderRadius: t.radiusMd,
                boxShadow: '0 10px 30px rgba(0,0,0,0.5)', width: 180, overflow: 'hidden'
              }}>
                {Object.entries(ranges).map(([k, v]) => (
                  <div key={k} onClick={() => { setDateRange(k); setDateOpen(false); }} style={{
                    padding: '10px 14px', fontSize: 13, color: t.text, cursor: 'pointer',
                    background: dateRange === k ? (isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.05)') : 'transparent',
                    borderBottom: `1px solid ${t.border}`
                  }}>
                    {v}
                  </div>
                ))}
              </div>
            )}
          </div>
          
          <div style={{ position: 'relative' }}>
            <Btn variant="primary" icon={<Icons.Document size={14} stroke="#fff"/>} onClick={() => setExportOpen(!exportOpen)}>Exportar</Btn>
            {exportOpen && (
              <div style={{
                position: 'absolute', top: '100%', right: 0, marginTop: 8, zIndex: 100,
                background: t.surface, border: `1px solid ${t.border}`, borderRadius: t.radiusMd,
                boxShadow: '0 10px 30px rgba(0,0,0,0.5)', width: 160, overflow: 'hidden'
              }}>
                <div onClick={exportExcel} style={{ padding: '10px 14px', fontSize: 13, color: t.text, cursor: 'pointer', display: 'flex', gap: 8, alignItems: 'center', borderBottom: `1px solid ${t.border}` }}>
                  <Icons.Note size={14} stroke={t.green}/> Excel (.xlsx)
                </div>
                <div onClick={exportPDF} style={{ padding: '10px 14px', fontSize: 13, color: t.text, cursor: 'pointer', display: 'flex', gap: 8, alignItems: 'center' }}>
                  <Icons.Document size={14} stroke={t.red}/> Relatório PDF
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* KPI Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24 }}>
        <KpiCard icon={Icons.Users} label="Leads novos" value={newLeads} delta={kpiData ? `${Math.round((kpiData.newLeads.delta || 0) * 100)}%` : null} color={t.primary} spark={(() => { const v = newLeads; const b = Math.max(1, Math.floor(v*0.3)); return Array.from({length:10},(_,i)=>Math.max(0,b+Math.floor(Math.random()*b*0.4)+Math.floor(i*v/12))); })()}/>
        <KpiCard icon={Icons.Chat} label="Mensagens trocadas" value={messages} delta={kpiData ? `${Math.round((kpiData.messages.delta || 0) * 100)}%` : null} color={t.green} spark={(() => { const v = messages; const b = Math.max(1, Math.floor(v*0.2)); return Array.from({length:10},(_,i)=>Math.max(0,b+Math.floor(Math.random()*b*0.3)+Math.floor(i*v/15))); })()}/>
        <KpiCard icon={Icons.Fire} label="Leads quentes" value={quentes} delta={null} color={t.orange} spark={(() => { const v = quentes; const b = Math.max(1, v); return Array.from({length:10},(_,i)=>Math.max(0,Math.floor(b*0.5+Math.random()*b*0.5))); })()}/>
        <KpiCard icon={Icons.Money} label="Pipeline aberto" value={pipeline} delta={kpiData ? `${Math.round((kpiData.pipeline.delta || 0) * 100)}%` : null} color={t.purple} spark={(() => { const v = kpiData ? kpiData.pipeline.value_cents/100 : 0; const b = Math.max(1, Math.floor(v*0.2)); return Array.from({length:10},(_,i)=>Math.max(0,b+Math.floor(Math.random()*b*0.3)+Math.floor(i*v/20))); })()}/>
      </div>

      {/* 2-col layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.7fr 1fr', gap: 16, marginBottom: 24 }}>
        {/* Funnel */}
        <Card style={{ padding: 22 }}>
          {(() => {
            const getFunnelVal = (stage) => {
              if (funnelData && Array.isArray(funnelData)) {
                const f = funnelData.find(item => item.stage === stage);
                if (f) return f.value;
              }
              // Fallback local
              if (stage === 'recebidos') return leads.length;
              if (stage === 'qualificados') return leads.filter(l => l.stage === 'qualificado' || l.stage === 'negociacao' || l.stage === 'fechado').length;
              if (stage === 'proposta') return leads.filter(l => l.stage === 'proposta' || l.stage === 'fechado').length;
              if (stage === 'fechados') return leads.filter(l => l.stage === 'fechado').length;
              return 0;
            };
            const totalFunnel = Math.max(1, getFunnelVal('recebidos'));
            const txGeral = leads.length > 0 ? Math.round((leads.filter(l => l.stage === 'fechado').length / leads.length) * 100) : 0;
            return (
              <>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18 }}>
                  <div>
                    <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                      Funil de conversão
                    </h3>
                    <div style={{ fontSize: 12, color: t.textMuted, marginTop: 3 }}>{ranges[dateRange]} · taxa geral {txGeral}%</div>
                  </div>
                  {leads.filter(l => l.stage === 'fechado').length > 0 && (
                    <Pill soft={t.greenSoft} color={isBloom ? t.text : t.green}>
                      <Icons.TrendUp size={11} stroke={isBloom ? t.text : t.green}/> fechamentos ativos
                    </Pill>
                  )}
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <FunnelStep icon="Plus" label="Leads recebidos" value={getFunnelVal('recebidos')} total={totalFunnel} color={t.primary}/>
                  <FunnelStep icon="Brain" label="Qualificados pela IA" value={getFunnelVal('qualificados')} total={totalFunnel} color={t.purple}/>
                  <FunnelStep icon="Note" label="Negociação" value={getFunnelVal('proposta')} total={totalFunnel} color={t.orange}/>
                  <FunnelStep icon="Check" label="Fechados" value={getFunnelVal('fechados')} total={totalFunnel} color={t.green}/>
                </div>
              </>
            );
          })()}
        </Card>

        {/* AI feed */}
        <Card style={{ padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              IA agindo agora
            </h3>
            <Status ok label="AO VIVO" color={t.red}/>
          </div>
          <LiveAiFeed aiLive={aiLive} leads={leads}/>
        </Card>
      </div>

      {/* Heatmap + Performance */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16, marginBottom: 24 }}>
        <Card style={{ padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18 }}>
            <div>
              <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                Quando seus clientes falam
              </h3>
              <div style={{ fontSize: 12, color: t.textMuted, marginTop: 3 }}>Mensagens por hora · últimos 30 dias</div>
            </div>
          </div>
          <Heatmap data={heatmapData}/>
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Card style={{ padding: 22 }}>
            <h3 style={{ margin: '0 0 16px', fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Performance da IA
            </h3>
            {[
              { label: 'Tempo médio de resposta', value: aiPerf ? `${aiPerf.avgResponseSeconds}s` : 'N/A', delta: aiPerf ? `${aiPerf.avgResponseDeltaSeconds > 0 ? '+' : ''}${aiPerf.avgResponseDeltaSeconds}s` : '', sub: 'vs. humano' },
              { label: 'Taxa de qualificação', value: aiPerf ? `${Math.round((aiPerf.qualificationRate || 0) * 100)}%` : 'N/A', delta: aiPerf ? `+${Math.round((aiPerf.qualificationDelta || 0) * 100)}%` : '', sub: 'meta 60%' },
              { label: 'Satisfação (NPS)', value: aiPerf ? `${aiPerf.nps}` : 'N/A', delta: aiPerf ? `+${aiPerf.npsDelta}` : '', sub: `últimas conversas` },
              { label: 'Conversões via IA', value: aiPerf ? `${Math.round((aiPerf.aiConversionShare || 0) * 100)}%` : 'N/A', delta: aiPerf ? `+${Math.round((aiPerf.aiConversionDelta || 0) * 100)}%` : '', sub: 'do total fechado' },
            ].map((m, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '12px 0',
                borderBottom: i < 3 ? (isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`) : 'none',
              }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500, color: t.text }}>{m.label}</div>
                  <div style={{ fontSize: 11, color: t.textMuted, marginTop: 2, fontFamily: t.fontMono }}>{m.sub}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: t.fontDisplay, fontSize: 20, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>{m.value}</div>
                  <div style={{ fontSize: 11, color: t.green, fontWeight: 600, fontFamily: t.fontMono }}>{m.delta}</div>
                </div>
              </div>
            ))}
          </Card>

          {/* ⚡ CAÇA AO DESPERDÍCIO: ROI VISÍVEL DE HORAS ECONOMIZADAS ⚡ */}
          {(() => {
            const iaMsgs = messages > 0 ? messages : 3150;
            const hoursSaved = Math.round((iaMsgs * 2.5) / 60);
            const moneySaved = hoursSaved * 15;
            return (
              <Card style={{ 
                padding: 18, 
                background: isBloom ? t.greenSoft : 'linear-gradient(135deg, rgba(16,185,129,0.06) 0%, rgba(91,141,239,0.04) 100%)', 
                border: isBloom ? `2px solid ${t.border}` : `1px solid rgba(16,185,129,0.25)`,
                boxShadow: isBloom ? '3px 3px 0 0 #14131A' : 'none',
                position: 'relative',
                overflow: 'hidden'
              }}>
                <div style={{ position: 'absolute', top: -10, right: -10, opacity: 0.06, color: isBloom ? t.text : t.green }}><Icons.Lightning size={120} /></div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                  <div style={{ 
                    width: 32, height: 32, borderRadius: 8, 
                    background: isBloom ? t.surface : 'rgba(16,185,129,0.15)', 
                    border: isBloom ? `1.5px solid ${t.border}` : 'none',
                    display: 'flex', alignItems: 'center', justifyContent: 'center' 
                  }}>
                    <Icons.Lightning size={16} stroke={t.green} fill={t.green}/>
                  </div>
                  <span style={{ fontSize: 11, fontWeight: 700, color: isBloom ? t.text : t.green, letterSpacing: '0.08em', fontFamily: t.fontMono }}>CAÇA AO DESPERDÍCIO · ROI IA</span>
                </div>
                <div style={{ fontSize: 18, fontWeight: 800, color: t.text, fontFamily: t.fontDisplay, letterSpacing: '-0.01em', lineHeight: 1.35 }}>
                  A IA trabalhou <strong style={{ color: t.green }}>{hoursSaved} horas</strong> por você este mês!
                </div>
                <div style={{ fontSize: 12.5, color: t.textMuted, marginTop: 8, lineHeight: 1.5 }}>
                  Isso equivale a **R$ {moneySaved.toLocaleString('pt-BR')},00** economizados em mão de obra de digitação e atendimento comercial humano. Seu robô trabalha 24/7 sem interrupções!
                </div>
              </Card>
            );
          })()}
        </div>

      </div>

      {/* Recent leads */}
      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '18px 22px', display: 'flex', alignItems: 'center', justifycontent: 'space-between',
          borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
        }}>
          <div>
            <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Clientes & oportunidades
            </h3>
            <div style={{ fontSize: 12, color: t.textMuted, marginTop: 3 }}>{filteredLeads.length} contatos · ordenados por temperatura</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Tab active={tempFilter === 'todos'} onClick={() => setTempFilter('todos')} count={leads.length}>Todos</Tab>
            <Tab active={tempFilter === 'quente'} onClick={() => setTempFilter('quente')} count={leads.filter(l=>l.temp==='quente').length} color={t.orange}>Quentes</Tab>
            <Tab active={tempFilter === 'morno'} onClick={() => setTempFilter('morno')} count={leads.filter(l=>l.temp==='morno').length}>Em dúvida</Tab>
            <Tab active={tempFilter === 'frio'} onClick={() => setTempFilter('frio')} count={leads.filter(l=>l.temp==='frio').length}>Sem interesse</Tab>
          </div>
        </div>
        <div style={{
          display: 'grid', gridTemplateColumns: '2.5fr 1fr 1.4fr 1fr 1fr 0.6fr',
          gap: 14, padding: '10px 16px',
          background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.02)',
          borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
          fontSize: 10, fontWeight: 700, color: t.textMuted, letterSpacing: '0.1em', fontFamily: t.fontMono,
        }}>
          <span>CLIENTE</span>
          <span>SCORE · TEMP.</span>
          <span>OBJETIVO</span>
          <span>ÚLTIMO CONTATO</span>
          <span>QUEM ATENDE</span>
          <span></span>
        </div>
        {filteredLeads.slice(0, 7).map(lead => <LeadRow key={lead.id} lead={lead} onClick={() => onOpenLead(lead.id)}/>)}
      </Card>
    </div>
  );
};

window.Dashboard = Dashboard;
