/* Prospecção · Chat view — conversa fullscreen com a Digi
 * Substitui a lista de leads. Empresas/Mapa/Análise ficam intactos.
 *
 * Layout:
 *   [Header: Digi · online · mesma conversa WhatsApp (clicável → mini-preview)]
 *   [Stream de mensagens · cards inline · chips Queres que…]
 *   [Action chips: Abordar / Simular / Ver empresa / Exportar / Coach]
 *   [Input: Pergunta à Digi…]
 */

// ======== Paleta das marcas (reutilizada em todo o chat) ========
const prospecMarcaColor = (marca, alpha = 1) => {
  const map = {
    'BIOND':   `rgba(138, 92, 245, ${alpha})`,   // roxo
    'Decal':   `rgba(59, 155, 240, ${alpha})`,   // azul
    'Mimaki':  `rgba(230, 60, 60, ${alpha})`,    // vermelho
    'Sensek':  `rgba(245, 168, 60, ${alpha})`,   // laranja
  };
  return map[marca] || `rgba(150, 150, 160, ${alpha})`;
};

// ======== Mini-preview WhatsApp (popover ao clicar no chip do header) ========
const ProspecWhatsPreview = ({ onClose }) => {
  const msgs = [
    { me: false, t: '22:47', body: 'Daniel, o João Afonso da Olimpo respondeu agora no WhatsApp. Disse que reuniu com a Roland hoje.' },
    { me: true, t: '22:48', body: 'O que é que o Digi AI sugere?' },
    { me: false, t: '22:48', body: 'Mandar-lhe já o comparativo UCJV330-160 vs VG3 Gen2 — foco em CAPEX + ROI 14m. Posso preparar?' },
    { me: true, t: '22:49', body: 'Sim. Envia em PDF.' },
    { me: false, t: '22:50', body: 'Enviado ✓✓  Ele abriu às 23:12. Sem resposta ainda.' },
  ];
  return (
    <div style={{
      position: 'absolute', top: '100%', right: 12, marginTop: 6, zIndex: 30,
      width: 360, background: 'var(--bg-elev)',
      border: '1px solid var(--border)', borderRadius: 12,
      boxShadow: '0 14px 40px rgba(0,0,0,0.45)',
      overflow: 'hidden',
    }}>
      <div style={{
        padding: '10px 12px',
        display: 'flex', alignItems: 'center', gap: 10,
        borderBottom: '1px solid var(--border)',
        background: 'linear-gradient(to right, #075e54 0%, #128c7e 100%)',
      }}>
        <div style={{
          width: 30, height: 30, borderRadius: '50%',
          background: 'rgba(255,255,255,0.18)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fff', fontWeight: 700, fontSize: 13,
        }}>JA</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ color: '#fff', fontSize: 12.5, fontWeight: 600 }}>João Afonso · Olimpo</div>
          <div style={{ color: 'rgba(255,255,255,0.7)', fontSize: 10.5 }}>ontem à noite · via Digi AI bridge</div>
        </div>
        <button onClick={onClose} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          color: 'rgba(255,255,255,0.8)', padding: 4, display: 'flex',
        }}>
          <Icon name="x" size={14} />
        </button>
      </div>

      <div style={{
        padding: '10px 12px',
        maxHeight: 260, overflowY: 'auto',
        background: 'color-mix(in oklch, #075e54 5%, var(--bg))',
        display: 'flex', flexDirection: 'column', gap: 6,
      }} className="scrollbar">
        {msgs.map((m, i) => (
          <div key={i} style={{
            alignSelf: m.me ? 'flex-end' : 'flex-start',
            maxWidth: '78%',
            padding: '6px 9px', borderRadius: 8,
            background: m.me ? 'color-mix(in oklch, #25d366 35%, var(--bg-elev))' : 'var(--bg)',
            border: '1px solid var(--border)',
            fontSize: 11.5, lineHeight: 1.4, color: 'var(--text)',
          }}>
            <div>{m.body}</div>
            <div style={{ fontSize: 9, color: 'var(--text-dim)', marginTop: 2, textAlign: 'right', fontFamily: 'var(--font-mono)' }}>{m.t}</div>
          </div>
        ))}
      </div>

      <div style={{
        padding: '8px 12px', borderTop: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 8,
        fontSize: 10.5, color: 'var(--text-muted)',
      }}>
        <Icon name="info" size={11} />
        <span>A Digi AI fala pelo Daniel no WhatsApp do Olimpo (número 351 928 456 401). Pausa a qualquer momento com “pausa digi”.</span>
      </div>
    </div>
  );
};

// ======== Bolha de chat ========
const ProspecChatBubble = ({ from, time, children, compact }) => {
  const isMe = from === 'me';
  return (
    <div style={{
      display: 'flex', gap: 10, marginBottom: compact ? 6 : 14,
      flexDirection: isMe ? 'row-reverse' : 'row',
      alignItems: 'flex-end',
    }}>
      {!isMe && (
        <div style={{
          width: 26, height: 26, borderRadius: '50%',
          background: 'color-mix(in oklch, var(--ai-500) 24%, var(--bg-elev))',
          border: '1px solid color-mix(in oklch, var(--ai-500) 40%, transparent)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <Icon name="sparkle" size={12} style={{ color: 'var(--ai-500)' }} />
        </div>
      )}
      {isMe && (
        <div style={{
          width: 26, height: 26, borderRadius: '50%',
          background: 'color-mix(in oklch, var(--accent, #22c55e) 14%, var(--bg-elev))',
          border: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0, fontSize: 10, fontWeight: 700, color: 'var(--text)',
        }}>DM</div>
      )}
      <div style={{
        maxWidth: '72%',
        display: 'flex', flexDirection: 'column',
        alignItems: isMe ? 'flex-end' : 'flex-start',
      }}>
        <div style={{
          padding: '10px 14px',
          borderRadius: isMe ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
          background: isMe
            ? 'color-mix(in oklch, var(--ai-500) 18%, var(--bg-elev))'
            : 'var(--bg-elev)',
          border: isMe
            ? '1px solid color-mix(in oklch, var(--ai-500) 30%, transparent)'
            : '1px solid var(--border)',
          fontSize: 13, lineHeight: 1.55,
          color: 'var(--text)',
        }}>
          {children}
        </div>
        {time && (
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginTop: 3 }}>
            {time}
          </div>
        )}
      </div>
    </div>
  );
};

// ======== Card inline: lead condensado ========
const ProspecChatLeadCard = ({ lead, onOpen, onWhats, onAbordar }) => (
  <div style={{
    padding: 12, borderRadius: 10,
    background: 'var(--bg)',
    border: '1px solid var(--border)',
    display: 'flex', alignItems: 'center', gap: 12,
    fontSize: 12,
  }}>
    <div style={{
      width: 44, height: 44, borderRadius: 8,
      background: prospecScoreColor(lead.score),
      color: '#fff', fontFamily: 'var(--font-display)',
      fontWeight: 800, fontSize: 16,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
    }}>{lead.score}</div>

    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, flexWrap: 'wrap' }}>
        <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--text)' }}>{lead.fullName}</div>
        <div style={{ fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>
          {lead.cargo || lead.senioridade}
        </div>
      </div>
      <div style={{ fontSize: 11.5, color: 'var(--text-muted)', display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', marginTop: 2 }}>
        <span>{lead.empresa}</span>
        {lead.cidade && <><span style={{ color: 'var(--text-dim)' }}>·</span><span>{lead.cidade}</span></>}
        {lead.marca && (
          <span style={{
            padding: '1px 6px', borderRadius: 3, fontSize: 9.5, fontWeight: 700,
            background: prospecMarcaColor(lead.marca, 0.18),
            color: prospecMarcaColor(lead.marca, 1),
            letterSpacing: '0.04em',
          }}>{lead.marca}</span>
        )}
      </div>
    </div>

    <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
      {lead.telMovel && (
        <button title="WhatsApp" onClick={(e) => { e.stopPropagation(); onWhats && onWhats(lead); }} style={chatIconBtn}>
          <Icon name="whatsapp" size={12} />
        </button>
      )}
      <button title="Abordar" onClick={(e) => { e.stopPropagation(); onAbordar && onAbordar(lead); }} style={{...chatIconBtn, color: 'var(--ai-500)', borderColor: 'color-mix(in oklch, var(--ai-500) 30%, transparent)'}}>
        <Icon name="zap" size={12} />
      </button>
      <button title="Abrir ficha" onClick={() => onOpen && onOpen(lead)} style={chatIconBtn}>
        <Icon name="arrow-right" size={12} />
      </button>
    </div>
  </div>
);

const chatIconBtn = {
  width: 26, height: 26, borderRadius: 6,
  background: 'transparent', border: '1px solid var(--border)',
  color: 'var(--text-muted)', cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
};

// ======== Card inline: lista condensada de leads ========
const ProspecChatLeadsList = ({ title, leads, onOpen, onWhats, onAbordar, onShowMore }) => (
  <div style={{
    margin: '8px 0 2px', padding: 12, borderRadius: 12,
    background: 'var(--bg)',
    border: '1px solid var(--border)',
  }}>
    <div style={{
      display: 'flex', alignItems: 'baseline', gap: 8,
      marginBottom: 10,
      paddingBottom: 8, borderBottom: '1px solid var(--border)',
    }}>
      <Icon name="users" size={13} style={{ color: 'var(--ai-500)' }} />
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, fontWeight: 600, letterSpacing: '-0.005em', flex: 1 }}>{title}</div>
      <div style={{ fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>{leads.length} leads</div>
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {leads.slice(0, 5).map(l => (
        <ProspecChatLeadCard key={l.id} lead={l} onOpen={onOpen} onWhats={onWhats} onAbordar={onAbordar} />
      ))}
    </div>
    {leads.length > 5 && onShowMore && (
      <button onClick={onShowMore} style={{
        marginTop: 8, width: '100%',
        padding: '7px 10px', borderRadius: 8,
        background: 'transparent', border: '1px dashed var(--border)',
        color: 'var(--ai-500)', fontSize: 11.5, fontWeight: 500,
        cursor: 'pointer', fontFamily: 'inherit',
      }}>
        Mostrar mais {leads.length - 5} →
      </button>
    )}
  </div>
);

// ======== Card inline: mini-mapa (SVG de Espanha) ========
const ProspecChatMiniMap = ({ buckets, onOpen }) => {
  // posições aprox em SVG 300x180 (Espanha simplificada)
  const CITY_XY = {
    'Madrid': [150, 95],
    'Barcelona': [225, 65],
    'Palau-solità i Plegamans': [222, 60],
    'Valencia': [190, 110],
    'Paterna': [186, 110],
    'Pinto': [153, 100],
    'Riba-roja de Turia': [188, 108],
    'Sevilla': [85, 140],
    'Málaga': [110, 150],
    'A Coruña': [45, 25],
    'La Coruña': [45, 25],
    'Gijón': [85, 25],
    'Bilbao': [155, 35],
    'Zaragoza': [175, 65],
    'Chinchilla de Montearagon': [150, 115],
    'Noain': [165, 38],
  };
  return (
    <div style={{
      margin: '6px 0', padding: 12, borderRadius: 12,
      background: 'var(--bg)', border: '1px solid var(--border)',
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 10, paddingBottom: 8, borderBottom: '1px solid var(--border)' }}>
        <Icon name="map-pin" size={13} style={{ color: 'var(--ai-500)' }} />
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, fontWeight: 600, flex: 1 }}>Distribuição geográfica</div>
        <button onClick={onOpen} style={{
          fontSize: 10.5, color: 'var(--ai-500)',
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontWeight: 600, fontFamily: 'inherit',
        }}>Abrir mapa cheio →</button>
      </div>
      <div style={{ position: 'relative' }}>
        <svg viewBox="0 0 300 180" style={{ width: '100%', height: 180, display: 'block' }}>
          {/* Espanha simplificada */}
          <path
            d="M 30,70 Q 25,40 55,25 Q 100,15 130,30 Q 150,25 175,32 Q 210,40 230,58 Q 260,62 270,85 Q 275,110 255,130 Q 240,160 200,170 Q 150,172 110,168 Q 70,160 45,135 Q 25,105 30,70 Z"
            fill="color-mix(in oklch, var(--ai-500) 7%, var(--bg-elev))"
            stroke="var(--border)"
            strokeWidth="0.6"
          />
          {Object.entries(buckets).map(([cidade, data]) => {
            const xy = CITY_XY[cidade];
            if (!xy) return null;
            const r = Math.max(4, Math.min(14, 3 + Math.sqrt(data.leads.length) * 1.6));
            const col = prospecScoreColor(Math.round(data.avg));
            return (
              <g key={cidade}>
                <circle cx={xy[0]} cy={xy[1]} r={r + 2} fill={col} opacity={0.15} />
                <circle cx={xy[0]} cy={xy[1]} r={r} fill={col} opacity={0.55} stroke={col} strokeWidth={1} />
                <text x={xy[0]} y={xy[1] + 1}
                  fontSize={Math.min(9, r)} textAnchor="middle"
                  dominantBaseline="middle" fontFamily="var(--font-mono)"
                  fontWeight={700} fill="#fff"
                  style={{ textShadow: '0 1px 2px rgba(0,0,0,0.6)' }}
                >{data.leads.length}</text>
              </g>
            );
          })}
        </svg>
      </div>
      <div style={{
        display: 'flex', gap: 12, marginTop: 8, paddingTop: 8,
        borderTop: '1px solid var(--border)', flexWrap: 'wrap',
        fontSize: 10.5, color: 'var(--text-muted)',
      }}>
        {Object.entries(buckets).slice(0, 4).map(([cidade, data]) => (
          <div key={cidade} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: prospecScoreColor(Math.round(data.avg)) }}></span>
            <span>{cidade}</span>
            <span style={{ color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{data.leads.length}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ======== Chips de filtros activos (clique para remover) ========
const ProspecChatFilterChips = ({ chips, onRemove, onReset }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap',
    marginTop: 8, marginBottom: 2,
  }}>
    <span style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
      FILTRADO POR
    </span>
    {chips.map((c, i) => (
      <button key={i} onClick={() => onRemove(c)} style={{
        padding: '3px 8px 3px 10px', borderRadius: 999,
        background: 'color-mix(in oklch, var(--ai-500) 10%, transparent)',
        border: '1px solid color-mix(in oklch, var(--ai-500) 28%, transparent)',
        color: 'var(--ai-500)', fontSize: 11, fontWeight: 500,
        display: 'inline-flex', alignItems: 'center', gap: 5,
        cursor: 'pointer', fontFamily: 'inherit',
      }}>
        {c.label}
        <Icon name="x" size={10} />
      </button>
    ))}
    {chips.length > 0 && (
      <button onClick={onReset} style={{
        background: 'transparent', border: 'none',
        color: 'var(--text-dim)', fontSize: 10.5,
        cursor: 'pointer', textDecoration: 'underline',
      }}>limpar tudo</button>
    )}
  </div>
);

// ======== Quick-replies "Queres que…" ========
const ProspecChatReplies = ({ replies, onPick }) => (
  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 10, marginLeft: 36 }}>
    {replies.map((r, i) => (
      <button key={i} onClick={() => onPick(r)} style={{
        padding: '6px 12px', borderRadius: 999,
        background: r.primary
          ? 'color-mix(in oklch, var(--ai-500) 20%, transparent)'
          : 'var(--bg-elev)',
        border: r.primary
          ? '1px solid var(--ai-500)'
          : '1px solid var(--border)',
        color: r.primary ? 'var(--ai-500)' : 'var(--text-muted)',
        fontSize: 11.5, fontWeight: r.primary ? 600 : 500,
        cursor: 'pointer', fontFamily: 'inherit',
        display: 'inline-flex', alignItems: 'center', gap: 5,
      }}>
        {r.icon && <Icon name={r.icon} size={11} />}
        {r.label}
      </button>
    ))}
  </div>
);

// ======== MAIN COMPONENT ========
const ProspecChat = ({ leads, empresas, onOpenLead, onTabChange }) => {
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [whatsOpen, setWhatsOpen] = React.useState(false);
  const [activeFilters, setActiveFilters] = React.useState([]);
  const streamRef = React.useRef(null);

  // Leads urgentes (score ≥ 9, top por score)
  const urgentes = React.useMemo(
    () => [...leads].filter(l => l.score >= 9).sort((a, b) => b.score - a.score).slice(0, 4),
    [leads]
  );
  const score9Count = leads.filter(l => l.score >= 9).length;
  const score8Count = leads.filter(l => l.score >= 8).length;

  // Inicial: mensagem proactiva da Digi
  React.useEffect(() => {
    if (messages.length) return;
    const greeting = getGreeting();
    const init = [
      {
        from: 'digi', time: '09:12', kind: 'text',
        body: (
          <>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, marginBottom: 6, letterSpacing: '-0.01em' }}>
              {greeting}, Daniel. 👋
            </div>
            <div>
              Acabei de rever a prospecção da <strong>Paula Partners ES</strong>. De <strong>571 contactos</strong> em 72 distribuidores,
              há <strong style={{ color: 'var(--ai-500)' }}>{score9Count} leads score 9</strong> e{' '}
              <strong>{score8Count - score9Count} leads score 8</strong> prontos para abordar esta semana.
            </div>
          </>
        ),
      },
      {
        from: 'digi', time: '09:12', kind: 'leads-list',
        title: '🔥 Urgentes para hoje',
        leads: urgentes,
      },
      {
        from: 'digi', time: '09:12', kind: 'text',
        body: 'Por onde queres começar?',
        replies: [
          { label: 'Preparar chamada p/ Alejandro', icon: 'phone', primary: true, action: 'brief-alejandro' },
          { label: 'Ver os 40 leads 9/10', icon: 'users', action: 'show-9' },
          { label: 'Distribuição no mapa', icon: 'map-pin', action: 'show-map' },
          { label: 'Top Mimaki + GMB ≥ 4.5', icon: 'sparkle', action: 'show-mimaki' },
          { label: 'Gerar briefings top 10', icon: 'doc', action: 'brief-10' },
        ],
      },
    ];
    setMessages(init);
  }, []);

  // Scroll bottom quando chegam mensagens
  React.useEffect(() => {
    if (streamRef.current) {
      streamRef.current.scrollTop = streamRef.current.scrollHeight;
    }
  }, [messages]);

  // Handlers
  const send = (text) => {
    if (!text.trim()) return;
    const now = nowTime();
    const userMsg = { from: 'me', time: now, kind: 'text', body: text };
    const reply = buildReply(text, leads, empresas, onOpenLead, setActiveFilters);
    setMessages(m => [...m, userMsg, ...reply]);
    setInput('');
  };

  const pickReply = (r) => {
    if (r.action === 'brief-alejandro') {
      setMessages(m => [...m, { from: 'me', time: nowTime(), kind: 'text', body: r.label }]);
      setTimeout(() => {
        const alej = leads.find(l => /alejandro/i.test(l.fullName)) || leads[0];
        setMessages(m => [...m, {
          from: 'digi', time: nowTime(), kind: 'briefing', lead: alej,
        }]);
      }, 400);
    } else if (r.action === 'show-9') {
      setMessages(m => [...m, { from: 'me', time: nowTime(), kind: 'text', body: r.label }]);
      setTimeout(() => {
        const list = leads.filter(l => l.score >= 9);
        setActiveFilters([{ key: 'score', label: 'Score ≥ 9', value: 9 }]);
        setMessages(m => [...m, {
          from: 'digi', time: nowTime(), kind: 'text',
          body: `Aqui estão os ${list.length} leads 9/10. Mostro-te os top 5 — carrega "mostrar mais" para ver os outros.`,
        }, {
          from: 'digi', time: nowTime(), kind: 'leads-list',
          title: '40 leads · score 9', leads: list,
        }]);
      }, 500);
    } else if (r.action === 'show-map') {
      setMessages(m => [...m, { from: 'me', time: nowTime(), kind: 'text', body: r.label }]);
      setTimeout(() => {
        const buckets = {};
        leads.filter(l => l.score >= 8).forEach(l => {
          if (!buckets[l.cidade]) buckets[l.cidade] = { leads: [], avg: 0 };
          buckets[l.cidade].leads.push(l);
        });
        Object.values(buckets).forEach(b => {
          b.avg = b.leads.reduce((a, l) => a + l.score, 0) / b.leads.length;
        });
        setMessages(m => [...m, {
          from: 'digi', time: nowTime(), kind: 'text',
          body: 'Os leads 8+ concentram-se em 4 eixos: Barcelona (Palau/Arenys), Madrid + Pinto, Valência (Paterna/Riba-roja) e Galiza. Palau-solità é o cluster mais denso.',
        }, {
          from: 'digi', time: nowTime(), kind: 'mini-map', buckets,
        }]);
      }, 500);
    } else if (r.action === 'show-mimaki') {
      setMessages(m => [...m, { from: 'me', time: nowTime(), kind: 'text', body: r.label }]);
      setTimeout(() => {
        const list = leads.filter(l => l.marca === 'Mimaki' && l.gmbRating && l.gmbRating >= 4.5).sort((a, b) => b.score - a.score);
        setActiveFilters([
          { key: 'marca', label: 'Mimaki', value: 'Mimaki' },
          { key: 'gmb', label: 'GMB ≥ 4.5', value: 4.5 },
        ]);
        setMessages(m => [...m, {
          from: 'digi', time: nowTime(), kind: 'text',
          body: `${list.length} distribuidores Mimaki com rating Google ≥ 4.5. Bem posicionados, perfil demo/instalação.`,
        }, {
          from: 'digi', time: nowTime(), kind: 'leads-list', title: 'Mimaki · GMB ≥ 4.5', leads: list,
        }]);
      }, 500);
    } else if (r.action === 'brief-10') {
      setMessages(m => [...m, { from: 'me', time: nowTime(), kind: 'text', body: r.label }]);
      setTimeout(() => {
        setMessages(m => [...m, {
          from: 'digi', time: nowTime(), kind: 'text',
          body: 'Feito. 10 briefings de 5 minutos cada, com contexto LinkedIn + equipamento actual + gatilho de chamada. Envio PDF para o teu email?',
          replies: [
            { label: 'Sim, envia agora', icon: 'mail', primary: true, action: 'noop' },
            { label: 'Pré-visualizar', icon: 'eye', action: 'noop' },
          ],
        }]);
      }, 500);
    }
  };

  const onActionChip = (action) => {
    if (action === 'ver-empresa') onTabChange('empresas');
    else if (action === 'exportar') {
      setMessages(m => [...m, {
        from: 'digi', time: nowTime(), kind: 'text',
        body: `Exportei ${leads.length} leads para o Primavera CRM como novos contactos da campanha Paula Partners ES. ✓`,
      }]);
    } else if (action === 'coach') {
      setMessages(m => [...m, {
        from: 'digi', time: nowTime(), kind: 'text',
        body: 'Coach mode. Diz-me para que lead queres treinar a chamada — eu simulo o interlocutor (resistências típicas: preço, timing, fidelização à marca actual).',
      }]);
    } else if (action === 'simular') {
      setMessages(m => [...m, {
        from: 'digi', time: nowTime(), kind: 'text',
        body: 'Abre o Simulador com o lead seleccionado. Qual?',
        replies: urgentes.slice(0, 3).map(l => ({
          label: `${l.fullName.split(' ').slice(0, 2).join(' ')} · ${l.empresa}`,
          action: 'noop',
        })),
      }]);
    } else if (action === 'abordar') {
      setMessages(m => [...m, {
        from: 'digi', time: nowTime(), kind: 'text',
        body: 'Posso iniciar abordagem multi-canal: (1) email hoje, (2) LinkedIn amanhã, (3) chamada no 3º dia. Para quantos leads?',
        replies: [
          { label: 'Top 10 urgentes', primary: true, action: 'noop' },
          { label: 'Todos os 9/10 (40)', action: 'noop' },
          { label: 'Só este lead', action: 'noop' },
        ],
      }]);
    }
  };

  const removeChip = (c) => setActiveFilters(f => f.filter(x => x.key !== c.key));

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column',
      minHeight: 0, background: 'var(--bg)',
    }}>
      {/* Header do chat */}
      <div style={{
        position: 'relative',
        padding: '12px 20px',
        display: 'flex', alignItems: 'center', gap: 12,
        borderBottom: '1px solid var(--border)',
        background: 'var(--bg-elev)',
        flexShrink: 0,
      }}>
        <div style={{
          width: 32, height: 32, borderRadius: '50%',
          background: 'color-mix(in oklch, var(--ai-500) 24%, var(--bg-elev))',
          border: '1px solid color-mix(in oklch, var(--ai-500) 40%, transparent)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="sparkle" size={14} style={{ color: 'var(--ai-500)' }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>Digi</div>
          <div style={{ fontSize: 10.5, color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{
              width: 6, height: 6, borderRadius: '50%',
              background: '#22c55e', boxShadow: '0 0 0 3px color-mix(in oklch, #22c55e 25%, transparent)',
            }}></span>
            <span>online</span>
            <span style={{ color: 'var(--text-dim)' }}>·</span>
            <button onClick={() => setWhatsOpen(v => !v)} style={{
              background: whatsOpen ? 'color-mix(in oklch, #25d366 18%, transparent)' : 'transparent',
              border: '1px solid ' + (whatsOpen ? '#25d366' : 'var(--border)'),
              borderRadius: 999, padding: '1px 8px 1px 6px',
              color: whatsOpen ? '#25d366' : 'var(--text-muted)',
              fontSize: 10.5, cursor: 'pointer', fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', gap: 4,
              transition: 'all 0.12s',
            }}>
              <Icon name="whatsapp" size={10} />
              mesma conversa do WhatsApp
            </button>
          </div>
        </div>

        <button onClick={() => setMessages([])} title="Nova conversa" style={{
          padding: '6px 10px', borderRadius: 7,
          background: 'transparent', border: '1px solid var(--border)',
          color: 'var(--text-muted)', fontSize: 11, fontWeight: 500,
          cursor: 'pointer', fontFamily: 'inherit',
          display: 'inline-flex', alignItems: 'center', gap: 5,
        }}>
          <Icon name="refresh" size={11} />
          Nova conversa
        </button>
        <button style={{
          padding: '6px 10px', borderRadius: 7,
          background: 'transparent', border: '1px solid var(--border)',
          color: 'var(--text-muted)', fontSize: 11, fontWeight: 500,
          cursor: 'pointer', fontFamily: 'inherit',
          display: 'inline-flex', alignItems: 'center', gap: 5,
        }}>
          <Icon name="info" size={11} />
          Contexto
        </button>

        {whatsOpen && <ProspecWhatsPreview onClose={() => setWhatsOpen(false)} />}
      </div>

      {/* Filter chips (se activos) */}
      {activeFilters.length > 0 && (
        <div style={{ padding: '10px 20px 0', flexShrink: 0 }}>
          <ProspecChatFilterChips
            chips={activeFilters}
            onRemove={removeChip}
            onReset={() => setActiveFilters([])}
          />
        </div>
      )}

      {/* Stream de mensagens */}
      <div ref={streamRef} className="scrollbar" style={{
        flex: 1, overflowY: 'auto',
        padding: '20px 28px 16px',
      }}>
        <div style={{ maxWidth: 780, margin: '0 auto' }}>
          {messages.map((m, i) => {
            if (m.kind === 'text') {
              return (
                <div key={i}>
                  <ProspecChatBubble from={m.from} time={m.time}>
                    {typeof m.body === 'string' ? <div>{m.body}</div> : m.body}
                  </ProspecChatBubble>
                  {m.replies && <ProspecChatReplies replies={m.replies} onPick={pickReply} />}
                </div>
              );
            }
            if (m.kind === 'leads-list') {
              return (
                <div key={i} style={{ marginLeft: 36, marginBottom: 14 }}>
                  <ProspecChatLeadsList
                    title={m.title}
                    leads={m.leads}
                    onOpen={onOpenLead}
                    onAbordar={onOpenLead}
                    onWhats={(l) => alert('WhatsApp ' + l.fullName)}
                    onShowMore={() => onTabChange && onTabChange('empresas')}
                  />
                </div>
              );
            }
            if (m.kind === 'mini-map') {
              return (
                <div key={i} style={{ marginLeft: 36, marginBottom: 14 }}>
                  <ProspecChatMiniMap buckets={m.buckets} onOpen={() => onTabChange('mapa')} />
                </div>
              );
            }
            if (m.kind === 'briefing') {
              return (
                <div key={i}>
                  <ProspecChatBubble from="digi" time={m.time}>
                    <ProspecChatBriefing lead={m.lead} onOpen={onOpenLead} />
                  </ProspecChatBubble>
                </div>
              );
            }
            return null;
          })}
        </div>
      </div>

      {/* Action chips + Input */}
      <div style={{
        borderTop: '1px solid var(--border)',
        background: 'var(--bg-elev)',
        padding: '10px 20px 14px',
        flexShrink: 0,
      }}>
        <div style={{ maxWidth: 780, margin: '0 auto' }}>
          <div style={{ display: 'flex', gap: 6, marginBottom: 10, flexWrap: 'wrap' }}>
            {[
              { id: 'abordar', icon: 'zap', label: 'Abordar' },
              { id: 'simular', icon: 'calculator', label: 'Simular' },
              { id: 'ver-empresa', icon: 'building', label: 'Ver empresa' },
              { id: 'exportar', icon: 'download', label: 'Exportar' },
              { id: 'coach', icon: 'gauge', label: 'Coach' },
            ].map(a => (
              <button key={a.id} onClick={() => onActionChip(a.id)} style={{
                padding: '5px 12px', borderRadius: 999,
                background: 'transparent', border: '1px solid var(--border)',
                color: 'var(--text-muted)', fontSize: 11.5, fontWeight: 500,
                cursor: 'pointer', fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 5,
                transition: 'all 0.12s',
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ai-500)'; e.currentTarget.style.color = 'var(--ai-500)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.color = 'var(--text-muted)'; }}
              >
                <Icon name={a.icon} size={11} />
                {a.label}
              </button>
            ))}
          </div>

          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '8px 10px', borderRadius: 12,
            background: 'var(--bg)',
            border: '1px solid var(--border)',
            transition: 'border-color 0.1s',
          }}>
            <Icon name="plus" size={14} style={{ color: 'var(--text-dim)' }} />
            <input
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(input); } }}
              placeholder="Pergunta à Digi… ex: 'mostra-me os 9/10 em Madrid com LinkedIn activo'"
              style={{
                flex: 1, border: 'none', outline: 'none',
                background: 'transparent', color: 'var(--text)',
                fontSize: 13, fontFamily: 'inherit',
                padding: '4px 2px',
              }}
            />
            <button onClick={() => send(input)} disabled={!input.trim()} style={{
              padding: '6px 12px', borderRadius: 8,
              background: input.trim() ? 'var(--ai-500)' : 'color-mix(in oklch, var(--ai-500) 25%, transparent)',
              border: 'none', color: '#fff',
              fontSize: 12, fontWeight: 600,
              cursor: input.trim() ? 'pointer' : 'default',
              fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', gap: 5,
              opacity: input.trim() ? 1 : 0.55,
            }}>
              <Icon name="send" size={11} />
              Enviar
            </button>
          </div>

          <div style={{
            textAlign: 'center', marginTop: 6,
            fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)',
          }}>
            Enter para enviar · Shift+Enter para nova linha · A Digi pode errar, confirma informação importante.
          </div>
        </div>
      </div>
    </div>
  );
};

// ======== Card briefing (quando user pede "prepara chamada") ========
const ProspecChatBriefing = ({ lead, onOpen }) => (
  <div style={{ minWidth: 420 }}>
    <div style={{
      display: 'flex', alignItems: 'baseline', gap: 8,
      marginBottom: 10, paddingBottom: 8, borderBottom: '1px solid var(--border)',
    }}>
      <Icon name="doc" size={13} style={{ color: 'var(--ai-500)' }} />
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 600 }}>Briefing · {lead.fullName}</div>
      <div style={{ marginLeft: 'auto', fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>5 min leitura</div>
    </div>

    <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr', gap: '6px 14px', fontSize: 12, marginBottom: 12 }}>
      <div style={{ color: 'var(--text-muted)' }}>Empresa</div>
      <div>{lead.empresa} · {lead.cidade} · {lead.funcionarios || '—'} emp.</div>
      <div style={{ color: 'var(--text-muted)' }}>Cargo</div>
      <div>{lead.cargo} ({lead.senioridade})</div>
      <div style={{ color: 'var(--text-muted)' }}>Score</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{
          padding: '1px 6px', borderRadius: 4,
          background: prospecScoreColor(lead.score), color: '#fff',
          fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700,
        }}>{lead.score}/10</span>
        <span style={{ color: 'var(--text-muted)', fontSize: 11 }}>{lead.razoesScore}</span>
      </div>
      <div style={{ color: 'var(--text-muted)' }}>Marca sug.</div>
      <div>
        <span style={{
          padding: '2px 8px', borderRadius: 4,
          background: prospecMarcaColor(lead.marca, 0.18),
          color: prospecMarcaColor(lead.marca, 1),
          fontSize: 11, fontWeight: 700, letterSpacing: '0.04em',
        }}>{lead.marca}</span>
      </div>
      {lead.equipamentoActual && (<>
        <div style={{ color: 'var(--text-muted)' }}>Equipa.</div>
        <div>{lead.equipamentoActual}</div>
      </>)}
    </div>

    <div style={{
      padding: 10, borderRadius: 8,
      background: 'color-mix(in oklch, var(--ai-500) 6%, transparent)',
      border: '1px solid color-mix(in oklch, var(--ai-500) 20%, transparent)',
      fontSize: 11.5, lineHeight: 1.5, marginBottom: 10,
    }}>
      <div style={{ fontWeight: 600, color: 'var(--ai-500)', marginBottom: 4, letterSpacing: '0.04em', fontSize: 10.5 }}>GANCHO DA CHAMADA</div>
      <div style={{ color: 'var(--text)' }}>
        {lead.sinaisCompra || lead.razoesScore || `Contacto ${lead.senioridade} num distribuidor do sector core. Abertura: congratular pelo rating GMB e pedir 10 min para mostrar ${lead.marca}.`}
      </div>
    </div>

    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
      {lead.telMovel && (
        <a href={`tel:${lead.telMovel}`} style={briefBtnStyle('primary')}>
          <Icon name="phone" size={11} /> Ligar
        </a>
      )}
      {lead.email && (
        <a href={`mailto:${lead.email}`} style={briefBtnStyle()}>
          <Icon name="mail" size={11} /> Email
        </a>
      )}
      <button onClick={() => onOpen(lead)} style={briefBtnStyle()}>
        <Icon name="arrow-right" size={11} /> Ficha completa
      </button>
    </div>
  </div>
);

const briefBtnStyle = (v) => ({
  padding: '6px 12px', borderRadius: 8,
  background: v === 'primary' ? 'var(--ai-500)' : 'var(--bg-elev)',
  border: v === 'primary' ? 'none' : '1px solid var(--border)',
  color: v === 'primary' ? '#fff' : 'var(--text)',
  fontSize: 11.5, fontWeight: 600,
  cursor: 'pointer', fontFamily: 'inherit', textDecoration: 'none',
  display: 'inline-flex', alignItems: 'center', gap: 5,
});

// ======== NLP leve — interpretar texto livre ========
function buildReply(text, leads, empresas, onOpenLead, setActiveFilters) {
  const q = text.toLowerCase();
  let filtered = [...leads];
  const chips = [];

  // Score
  const scoreMatch = q.match(/(?:score|^)\s*(?:≥|>=|>)?\s*(\d)(?:\/10)?/);
  const has9 = /9\/?10|score\s*9|9\s+(?:em|de|com)/.test(q);
  const has8 = /\b8\b|8\/10|score\s*8/.test(q);
  if (has9) { filtered = filtered.filter(l => l.score >= 9); chips.push({ key: 'score', label: 'Score ≥ 9', value: 9 }); }
  else if (has8) { filtered = filtered.filter(l => l.score >= 8); chips.push({ key: 'score', label: 'Score ≥ 8', value: 8 }); }

  // Marca
  ['BIOND', 'Mimaki', 'Sensek', 'Decal'].forEach(m => {
    if (q.includes(m.toLowerCase())) {
      filtered = filtered.filter(l => l.marca === m);
      chips.push({ key: 'marca', label: m, value: m });
    }
  });

  // Cidade
  ['Madrid', 'Barcelona', 'Valencia', 'Paterna', 'Pinto', 'Sevilla', 'Bilbao'].forEach(c => {
    if (q.includes(c.toLowerCase())) {
      filtered = filtered.filter(l => (l.cidade || '').toLowerCase().includes(c.toLowerCase()));
      chips.push({ key: 'cidade-' + c, label: c, value: c });
    }
  });

  // LinkedIn
  if (/linkedin/i.test(q)) {
    filtered = filtered.filter(l => l.linkedin);
    chips.push({ key: 'linkedin', label: 'Com LinkedIn', value: true });
  }

  // GMB
  if (/gmb|google|rating|4[,.]5/i.test(q)) {
    filtered = filtered.filter(l => l.gmbRating && l.gmbRating >= 4.5);
    chips.push({ key: 'gmb', label: 'GMB ≥ 4.5', value: 4.5 });
  }

  // Seniority — Director / C-Level
  if (/director|financial director|c-level|ceo|cfo|owner|founder/i.test(q)) {
    filtered = filtered.filter(l => /c[_\-\s]?level|director|owner|founder/i.test(l.senioridade || ''));
    chips.push({ key: 'senior', label: 'Director / C-Level', value: true });
  }

  if (chips.length) setActiveFilters(chips);

  // Sort & cap
  filtered.sort((a, b) => b.score - a.score);
  const top = filtered.slice(0, 20);

  // Construir resposta
  if (top.length === 0) {
    return [{
      from: 'digi', time: nowTime(), kind: 'text',
      body: 'Não encontrei leads que cruzem esses critérios. Queres alargar os filtros?',
    }];
  }

  if (/mapa|geografia|onde/i.test(q)) {
    const buckets = {};
    top.forEach(l => {
      if (!buckets[l.cidade]) buckets[l.cidade] = { leads: [], avg: 0 };
      buckets[l.cidade].leads.push(l);
    });
    Object.values(buckets).forEach(b => { b.avg = b.leads.reduce((a, l) => a + l.score, 0) / b.leads.length; });
    return [
      { from: 'digi', time: nowTime(), kind: 'text', body: `Encontrei ${filtered.length} leads. Distribuição:` },
      { from: 'digi', time: nowTime(), kind: 'mini-map', buckets },
    ];
  }

  const summary = chips.length
    ? `Filtrei por ${chips.map(c => c.label).join(' · ')}. Encontrei ${filtered.length} leads. Top:`
    : `Aqui estão os top ${top.length} de ${filtered.length}:`;

  return [
    { from: 'digi', time: nowTime(), kind: 'text', body: summary },
    {
      from: 'digi', time: nowTime(), kind: 'leads-list',
      title: chips.length ? chips.map(c => c.label).join(' + ') : 'Resultados',
      leads: top,
    },
    {
      from: 'digi', time: nowTime(), kind: 'text',
      body: 'Queres que eu…',
      replies: [
        { label: 'Gere emails personalizados', icon: 'mail', primary: true, action: 'noop' },
        { label: 'Prepare briefings top 5', icon: 'doc', action: 'noop' },
        { label: 'Ordene para chamada hoje', icon: 'phone', action: 'noop' },
      ],
    },
  ];
}

function nowTime() {
  const d = new Date();
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}

function getGreeting() {
  const h = new Date().getHours();
  if (h < 12) return 'Bom dia';
  if (h < 19) return 'Boa tarde';
  return 'Boa noite';
}

window.ProspecChat = ProspecChat;
