/* Radar de Prospecção — IA ativa procurando leads em tempo real */

const Radar = () => {
  const t = useTheme();
  const { prompt, alert } = useDialog();
  const isBloom = t.name === 'BLOOM';

  const { data: prospectsData, refetch: refetchProspects } = useRadarProspects();
  const { data: statsData } = useRadarStats();
  const { data: criteriaData, refetch: refetchCriteria } = useRadarCriteria();

  const prospects = prospectsData || [];
  const stats = statsData || {
    opportunities: 0, opportunitiesDelta_2h: 0, avgMatch: 0, target: 0, converted: 0, conversionRate: 0, accountsAnalyzedToday: 0
  };
  const criteria = criteriaData || {};

  const handleApproach = async (id) => {
    try {
      await FluxoEndpoints.radar.approach(id);
      refetchProspects();
      await alert('Prospect abordado! Foi adicionado ao seu Kanban.');
    } catch (e) {}
  };

  const handleSkip = async (id) => {
    try {
      await FluxoEndpoints.radar.skip(id);
      refetchProspects();
    } catch (e) {}
  };

  return (
    <div style={{ padding: '24px 28px 40px', maxWidth: 1480, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 20, gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <span style={{ fontSize: 11, color: t.textMuted, letterSpacing: '0.14em', fontFamily: t.fontMono }}>
              INTELIGÊNCIA · PROSPECÇÃO ATIVA
            </span>
            <Status ok label="VARREDURA AO VIVO" color={t.red}/>
          </div>
          <h1 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em', color: t.text }}>
            Radar de Prospecção
          </h1>
          <div style={{ marginTop: 8, fontSize: 14, color: t.textMuted, maxWidth: 720 }}>
            A Assistente varre o Google Maps, diretórios empresariais e redes públicas buscando empresas com sinais de compra. Você decide quem abordar.
          </div>
        </div>
        <Btn variant="primary" icon={<Icons.Settings size={14} stroke="#fff"/>} onClick={async () => {
          const keyword = await prompt("O que a Assistente deve buscar no Radar? (Ex: contabilidades, lojas de roupas)", criteria.keywords ? criteria.keywords[0] : "");
          if (keyword) {
            await FluxoEndpoints.radar.updateCriteria({ keywords: [keyword] });
            refetchCriteria();
            refetchProspects();
          }
        }}>Editar critérios de busca</Btn>
      </div>

      {/* Radar viz + stats */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 18, marginBottom: 24 }}>
        <Card style={{ padding: 22, position: 'relative', overflow: 'hidden', minHeight: 320 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
            <Icons.Radar size={18} stroke={isBloom ? t.text : t.primary}/>
            <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 17, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Varredura ativa
            </h3>
          </div>
          <div style={{ position: 'relative', width: '100%', aspectRatio: '1', maxWidth: 260, margin: '0 auto' }}>
            <svg viewBox="0 0 200 200" style={{ width: '100%', height: '100%' }}>
              <defs>
                <radialGradient id="radarGrad">
                  <stop offset="0%" stopColor={t.primary} stopOpacity="0.4"/>
                  <stop offset="100%" stopColor={t.primary} stopOpacity="0"/>
                </radialGradient>
              </defs>
              <circle cx="100" cy="100" r="90" fill="none" stroke={isBloom ? t.border : 'rgba(91,141,239,0.15)'} strokeWidth={isBloom ? 1.5 : 1}/>
              <circle cx="100" cy="100" r="60" fill="none" stroke={isBloom ? t.border : 'rgba(91,141,239,0.15)'} strokeWidth={isBloom ? 1.5 : 1}/>
              <circle cx="100" cy="100" r="30" fill="none" stroke={isBloom ? t.border : 'rgba(91,141,239,0.15)'} strokeWidth={isBloom ? 1.5 : 1}/>
              <line x1="100" y1="10" x2="100" y2="190" stroke={isBloom ? t.border : 'rgba(91,141,239,0.1)'} strokeWidth="1"/>
              <line x1="10" y1="100" x2="190" y2="100" stroke={isBloom ? t.border : 'rgba(91,141,239,0.1)'} strokeWidth="1"/>
              {/* Sweep line */}
              <g style={{ animation: 'sweep 4s linear infinite', transformOrigin: '100px 100px' }}>
                <line x1="100" y1="100" x2="100" y2="10" stroke={t.green} strokeWidth="2"/>
                <path d="M 100 100 L 100 10 A 90 90 0 0 1 162 38 Z" fill="url(#radarGrad)" opacity="0.5"/>
              </g>
              {/* dots */}
              {[
                { x: 70, y: 55, c: t.pink },
                { x: 130, y: 70, c: t.primary },
                { x: 145, y: 130, c: t.green },
                { x: 60, y: 140, c: t.orange },
                { x: 85, y: 120, c: t.purple },
                { x: 115, y: 100, c: t.green },
              ].map((d, i) => (
                <g key={i}>
                  <circle cx={d.x} cy={d.y} r="3" fill={d.c}/>
                  <circle cx={d.x} cy={d.y} r="3" fill="none" stroke={d.c} strokeWidth="1" opacity="0.4">
                    <animate attributeName="r" from="3" to="14" dur="2s" begin={`${i*0.3}s`} repeatCount="indefinite"/>
                    <animate attributeName="opacity" from="0.4" to="0" dur="2s" begin={`${i*0.3}s`} repeatCount="indefinite"/>
                  </circle>
                </g>
              ))}
              <circle cx="100" cy="100" r="4" fill={t.primary}/>
            </svg>
            <style>{`@keyframes sweep { from { transform: rotate(0deg) } to { transform: rotate(360deg) } }`}</style>
          </div>
          <div style={{ textAlign: 'center', marginTop: 14, fontSize: 12, color: t.textMuted, fontFamily: t.fontMono }}>
            <strong style={{ color: t.text }}>{stats.accountsAnalyzedToday}</strong> contas analisadas hoje
          </div>
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            <Card style={{ padding: 16 }}>
              <div style={{ fontSize: 10, color: t.textMuted, fontFamily: t.fontMono, letterSpacing: '0.08em' }}>OPORTUNIDADES</div>
              <div style={{ fontFamily: t.fontDisplay, fontSize: 30, fontWeight: 700, color: t.text, letterSpacing: '-0.02em', marginTop: 4 }}>{stats.opportunities}</div>
              <div style={{ fontSize: 11, color: t.green, fontWeight: 600, marginTop: 2, fontFamily: t.fontMono }}>+{stats.opportunitiesDelta_2h} nas últimas 2h</div>
            </Card>
            <Card style={{ padding: 16 }}>
              <div style={{ fontSize: 10, color: t.textMuted, fontFamily: t.fontMono, letterSpacing: '0.08em' }}>MATCH MÉDIO</div>
              <div style={{ fontFamily: t.fontDisplay, fontSize: 30, fontWeight: 700, color: t.text, letterSpacing: '-0.02em', marginTop: 4 }}>{Math.round(stats.avgMatch * 100)}%</div>
              <div style={{ fontSize: 11, color: t.textMuted, marginTop: 2, fontFamily: t.fontMono }}>alvo: &gt;{Math.round(stats.target * 100)}%</div>
            </Card>
            <Card style={{ padding: 16 }}>
              <div style={{ fontSize: 10, color: t.textMuted, fontFamily: t.fontMono, letterSpacing: '0.08em' }}>VIRARAM CLIENTE</div>
              <div style={{ fontFamily: t.fontDisplay, fontSize: 30, fontWeight: 700, color: t.text, letterSpacing: '-0.02em', marginTop: 4 }}>{stats.converted}</div>
              <div style={{ fontSize: 11, color: t.green, fontWeight: 600, marginTop: 2, fontFamily: t.fontMono }}>conv. {Math.round(stats.conversionRate * 100)}%</div>
            </Card>
          </div>
          <Card style={{ padding: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
              <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 15, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                Critérios ativos
              </h3>
              <Btn variant="ghost" size="sm">Editar</Btn>
            </div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {criteria.keywords && criteria.keywords.map(k => (
                <Pill key={k} soft={t.primarySoft} color={isBloom ? t.text : t.primary}>🎯 {k}</Pill>
              ))}
              <Pill soft={t.greenSoft} color={isBloom ? t.text : t.green}>📍 Brasil</Pill>
              <Pill soft={t.orangeSoft} color={isBloom ? t.text : t.orange}>🛒 Alta atividade B2B</Pill>
            </div>
          </Card>
        </div>
      </div>

      {/* Prospect list */}
      <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' }}>
              Empresas que combinam com seu ICP
            </h3>
            <div style={{ fontSize: 12, color: t.textMuted, marginTop: 3 }}>{prospects.length} encontrados · ordenados por probabilidade de virar cliente</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Tab active>Match alto</Tab>
            <Tab>Por canal</Tab>
            <Tab>Recentes</Tab>
          </div>
        </div>

        {prospects.map((p, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '50px 2fr 1.4fr 2fr 1fr 1fr',
            gap: 16, padding: '16px 22px', alignItems: 'center',
            borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
          }}>
            <Avatar name={p.name.split(' ').map(w=>w[0]).slice(0,2).join('')} color={p.color} size={42}/>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: t.text, letterSpacing: '-0.01em' }}>{p.name}</div>
              <div style={{ fontSize: 12, color: t.textMuted, fontFamily: t.fontMono, marginTop: 2 }}>{p.handle}</div>
            </div>
            <div>
              <Pill soft={
                p.channel === 'Instagram' ? t.pinkSoft :
                p.channel === 'WhatsApp' ? t.greenSoft :
                t.primarySoft
              } color={isBloom ? t.text : (
                p.channel === 'Instagram' ? t.pink :
                p.channel === 'WhatsApp' ? t.green :
                t.primary
              )}>{p.channel}</Pill>
              <div style={{ fontSize: 11, color: t.textMuted, marginTop: 6, fontFamily: t.fontMono }}>{p.city}</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icons.Sparkles size={13} stroke={t.primary} style={{ flexShrink: 0, marginTop: 2 }}/>
              <span style={{ fontSize: 12.5, color: t.textMuted, lineHeight: 1.4 }}>{p.signal}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <ScoreRing value={p.match} size={36}/>
              <div>
                <div style={{ fontSize: 10, color: t.textMuted, fontFamily: t.fontMono }}>MATCH</div>
                <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>{p.match}%</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
              <Btn variant="secondary" size="sm" onClick={() => handleSkip(p.id)}>Pular</Btn>
              <Btn variant="green" size="sm" icon={<Icons.Send size={11}/>} onClick={() => handleApproach(p.id)}>Abordar</Btn>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
};

window.Radar = Radar;
