// intelligence-panel.jsx — Horos Intelligence UI — Fase 6
// Componentes React para o painel de IA integrado em messages.html
// Carregado via jsx-loader.js ANTES de messages.jsx

/* ── Label maps (PT-BR) ─────────────────────────────────────────────────── */

const _HI_QUAL_LABELS = {
  HIGH_INTENT:         'Alta intenção',
  QUALIFIED:           'Qualificado',
  PARTIALLY_QUALIFIED: 'Parcialmente qualificado',
  UNQUALIFIED:         'Não qualificado',
  UNKNOWN:             'Analisando',
};

const _HI_QUAL_COLORS = {
  HIGH_INTENT:         '#34d399',
  QUALIFIED:           '#1F93FF',
  PARTIALLY_QUALIFIED: '#f5b544',
  UNQUALIFIED:         '#ef4444',
  UNKNOWN:             '#94a3b8',
};

const _HI_NBA_LABELS = {
  NO_ACTION:      'Aguardar',
  ASK_QUESTION:   'Fazer pergunta qualificadora',
  SEND_PROPERTY:  'Enviar sugestão de imóvel',
  FOLLOW_UP:      'Retomar contato',
  INVITE_VISIT:   'Convidar para visita',
  SCHEDULE_VISIT: 'Agendar visita',
  HUMAN_HANDOFF:  'Transferir para corretor',
  WAIT:           'Aguardar resposta',
};

const _HI_SIGNAL_LABELS = {
  FINANCING_INTEREST: 'Interesse em financiamento',
  VISIT_INTENT:       'Intenção de visita',
  PROPERTY_INTEREST:  'Interesse no imóvel',
  NEGOTIATION_SIGNAL: 'Negociação em vista',
  DECISION_PENDING:   'Decisão pendente',
  HIGH_URGENCY:       'Alta urgência',
  PRICE_ACCEPTANCE:   'Aceita o preço',
  FAMILY_APPROVAL:    'Decisão familiar',
  REFERRAL_TRUST:     'Veio por indicação',
  FOLLOW_UP_REQUEST:  'Pediu mais informações',
  DOCUMENT_READINESS: 'Documentação pronta',
  BUDGET_CONFIRMED:   'Orçamento confirmado',
};

const _HI_OBJ_LABELS = {
  PRICE:          'Preço elevado',
  DOWN_PAYMENT:   'Entrada',
  FINANCING:      'Restrição de crédito',
  LOCATION:       'Localização',
  SIZE:           'Tamanho',
  TIMELINE:       'Prazo',
  DECISION_MAKER: 'Precisa consultar',
  COMPETITION:    'Avaliando concorrência',
  TRUST:          'Confiança',
};

const _HI_STATUS_DISPLAY = {
  PENDING:  { label: 'Aguardando aprovação',  color: '#1F93FF' },
  APPROVED: { label: 'Enviada com sucesso',   color: '#34d399' },
  EDITED:   { label: 'Enviada com edição',    color: '#a78bfa' },
  REJECTED: { label: 'Recusada',              color: '#94a3b8' },
  EXPIRED:  { label: 'Expirou (30 min)',       color: '#64748b' },
  STALE:    { label: 'Conversa avançou',      color: '#f5b544' },
};

/* ── API helpers ─────────────────────────────────────────────────────────── */

function _hiTok() {
  return window.HOROS_SESSION?.access_token || '';
}

function _hiSuggText(sugg) {
  if (!sugg) return '';
  const resp = sugg.edited_response || sugg.original_response || {};
  if (typeof resp.message === 'string' && resp.message) return resp.message;
  if (Array.isArray(resp.messages) && resp.messages.length > 0) {
    return resp.messages
      .map(m => (typeof m === 'string' ? m : m.content || m.text || ''))
      .filter(Boolean)
      .join('\n');
  }
  return '';
}

function _hiEffectiveStatus(sugg, convVersion) {
  if (!sugg) return null;
  const st = sugg.effective_status || sugg.status;
  if (st === 'PENDING') {
    const created = new Date(sugg.created_at).getTime();
    if (!isNaN(created) && Date.now() - created > 30 * 60 * 1000) return 'EXPIRED';
    if (convVersion !== null && convVersion !== undefined &&
        sugg.conversation_version !== convVersion) return 'STALE';
  }
  return st;
}

function _hiErrMsg(status, body) {
  const b = body || {};
  if (status === 0)   return 'Sem conexão com a internet.';
  if (status === 401) return 'Sessão expirada. Faça login novamente.';
  if (status === 403) return b.error || 'Sem permissão para esta ação.';
  if (status === 404) return 'Sugestão não encontrada.';
  if (status === 409) return b.error || 'Não é possível realizar esta ação agora.';
  if (status === 422) return b.error || 'Dados inválidos.';
  if (status === 429) return 'Muitas requisições. Tente em instantes.';
  if (status >= 500)  return 'Erro interno. Tente novamente em instantes.';
  return b.error || `Erro ${status}.`;
}

async function _hiApprove(suggId) {
  const tok = _hiTok();
  if (!tok) return { ok: false, error: 'Sem autenticação' };
  let r;
  try {
    r = await fetch(`/api/intelligence/suggestions/${suggId}?action=approve`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${tok}` },
    });
  } catch { return { ok: false, error: 'Sem conexão.' }; }
  const body = await r.json().catch(() => ({}));
  if (!r.ok) return { ok: false, error: _hiErrMsg(r.status, body), code: body.code };
  return { ok: true, ...body };
}

async function _hiEdit(suggId, text) {
  const tok = _hiTok();
  if (!tok) return { ok: false, error: 'Sem autenticação' };
  let r;
  try {
    r = await fetch(`/api/intelligence/suggestions/${suggId}?action=edit`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${tok}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ message: text }),
    });
  } catch { return { ok: false, error: 'Sem conexão.' }; }
  const body = await r.json().catch(() => ({}));
  if (!r.ok) return { ok: false, error: _hiErrMsg(r.status, body), code: body.code };
  return { ok: true, ...body };
}

async function _hiReject(suggId) {
  const tok = _hiTok();
  if (!tok) return { ok: false, error: 'Sem autenticação' };
  let r;
  try {
    r = await fetch(`/api/intelligence/suggestions/${suggId}?action=reject`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${tok}` },
    });
  } catch { return { ok: false, error: 'Sem conexão.' }; }
  const body = await r.json().catch(() => ({}));
  if (!r.ok) return { ok: false, error: _hiErrMsg(r.status, body), code: body.code };
  return { ok: true, ...body };
}

async function _hiTakeover(suggId, convId) {
  const tok = _hiTok();
  if (!tok) return { ok: false, error: 'Sem autenticação' };
  const id = suggId || 'takeover';
  let r;
  try {
    r = await fetch(`/api/intelligence/suggestions/${id}?action=takeover`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${tok}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ conversation_id: convId }),
    });
  } catch { return { ok: false, error: 'Sem conexão.' }; }
  const body = await r.json().catch(() => ({}));
  if (!r.ok) return { ok: false, error: _hiErrMsg(r.status, body) };
  return { ok: true, ...body };
}

function _hiTrack(event, meta) {
  try {
    const m = meta && Object.keys(meta).length ? meta : '';
    console.info('[HorosAnalytics]', event, m);
  } catch {}
}

/* ── Internal components ─────────────────────────────────────────────────── */

function _HiProcessingIndicator() {
  return (
    <div className="hi-processing-row">
      <div className="hi-processing-dots">
        <span /><span /><span />
      </div>
      <span>Analisando conversa…</span>
    </div>
  );
}

function _HiQualBadge({ qual }) {
  const label = _HI_QUAL_LABELS[qual] || qual || '—';
  const color = _HI_QUAL_COLORS[qual] || '#94a3b8';
  return (
    <span className="hi-qual-badge" style={{
      color,
      borderColor: `${color}55`,
      background:  `${color}14`,
    }}>
      {label}
    </span>
  );
}

function _HiAnalysisSection({ analysis }) {
  if (!analysis) return null;
  const qual       = analysis.qualification?.status;
  const intent     = analysis.qualification?.intent_score ?? null;
  const signals    = Array.isArray(analysis.buying_signals)  ? analysis.buying_signals  : [];
  const objections = Array.isArray(analysis.objections)      ? analysis.objections      : [];
  const nba        = analysis.nba?.action;
  const nbaReason  = analysis.nba?.reason;

  if (!qual && !signals.length && !objections.length && !nba) return null;

  return (
    <div>
      {qual && (
        <div className="hi-qual-row">
          <_HiQualBadge qual={qual} />
          {intent !== null && (
            <div className="hi-intent-bar-wrap">
              <div className="hi-intent-bar-label">Intenção de compra</div>
              <div className="hi-intent-bar-track">
                <div
                  className="hi-intent-bar-fill"
                  style={{ width: `${Math.round((intent || 0) * 100)}%` }}
                />
              </div>
            </div>
          )}
        </div>
      )}

      {signals.length > 0 && (
        <div className="hi-pills-section">
          <div className="hi-pills-label">Sinais de compra</div>
          <div className="hi-pills-row">
            {signals.map(s => (
              <span key={s} className="hi-signal-pill">
                {_HI_SIGNAL_LABELS[s] || s}
              </span>
            ))}
          </div>
        </div>
      )}

      {objections.length > 0 && (
        <div className="hi-pills-section">
          <div className="hi-pills-label">Objeções</div>
          <div className="hi-pills-row">
            {objections.map(o => (
              <span key={o} className="hi-obj-pill">
                {_HI_OBJ_LABELS[o] || o}
              </span>
            ))}
          </div>
        </div>
      )}

      {nba && nba !== 'NO_ACTION' && (
        <div className="hi-nba-card">
          <div className="hi-nba-action">{_HI_NBA_LABELS[nba] || nba}</div>
          {nbaReason && <div className="hi-nba-reason">{nbaReason}</div>}
        </div>
      )}
    </div>
  );
}

function _HiSuggestionActions({ sugg, effectiveStatus, onDone, onError }) {
  const [loading, setLoading] = React.useState(null);
  const [editing, setEditing] = React.useState(false);
  const [editText, setEditText] = React.useState('');
  const canAct = effectiveStatus === 'PENDING';

  async function handleApprove() {
    if (loading) return;
    setLoading('approve');
    _hiTrack('AI_SUGGESTION_APPROVED', { suggId: sugg.id });
    const r = await _hiApprove(sugg.id);
    setLoading(null);
    if (r.ok) onDone && onDone('APPROVED');
    else onError && onError(r.error);
  }

  function handleStartEdit() {
    if (loading || editing) return;
    setEditText(_hiSuggText(sugg));
    setEditing(true);
    _hiTrack('AI_SUGGESTION_EDIT_STARTED', { suggId: sugg.id });
  }

  async function handleSaveEdit() {
    if (loading || !editText.trim()) return;
    setLoading('save');
    _hiTrack('AI_SUGGESTION_EDITED', { suggId: sugg.id });
    const r = await _hiEdit(sugg.id, editText.trim());
    setLoading(null);
    if (r.ok) { setEditing(false); onDone && onDone('EDITED'); }
    else onError && onError(r.error);
  }

  async function handleReject() {
    if (loading) return;
    setLoading('reject');
    _hiTrack('AI_SUGGESTION_REJECTED', { suggId: sugg.id });
    const r = await _hiReject(sugg.id);
    setLoading(null);
    if (r.ok) onDone && onDone('REJECTED');
    else onError && onError(r.error);
  }

  if (editing) {
    return (
      <div>
        <textarea
          className="hi-edit-area"
          value={editText}
          onChange={e => setEditText(e.target.value)}
          placeholder="Edite a mensagem aqui…"
        />
        <div className="hi-action-row">
          <button
            className="hi-btn hi-btn-approve"
            disabled={!!loading || !editText.trim()}
            onClick={handleSaveEdit}
          >
            {loading === 'save' && <span className="hi-spinner" />}
            Enviar edição
          </button>
          <button
            className="hi-btn hi-btn-reject"
            disabled={!!loading}
            onClick={() => setEditing(false)}
          >
            Cancelar
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="hi-action-row">
      <button
        className="hi-btn hi-btn-approve"
        disabled={!canAct || !!loading}
        onClick={handleApprove}
      >
        {loading === 'approve' && <span className="hi-spinner" />}
        Aprovar e enviar
      </button>
      <button
        className="hi-btn hi-btn-edit"
        disabled={!canAct || !!loading}
        onClick={handleStartEdit}
      >
        Editar
      </button>
      <button
        className="hi-btn hi-btn-reject"
        disabled={!canAct || !!loading}
        onClick={handleReject}
      >
        {loading === 'reject' && <span className="hi-spinner" />}
        Recusar
      </button>
    </div>
  );
}

function _HiSuggestionDisplay({ sugg, effectiveStatus, convId, onDone, onError }) {
  const text = _hiSuggText(sugg);
  const disp = _HI_STATUS_DISPLAY[effectiveStatus] || { label: effectiveStatus, color: '#94a3b8' };
  const isTerminal = ['APPROVED', 'EDITED', 'REJECTED', 'EXPIRED'].includes(effectiveStatus);
  const isStale    = effectiveStatus === 'STALE';
  const isPending  = effectiveStatus === 'PENDING';

  const statusRow = (
    <div className="hi-suggestion-status-row">
      <span style={{
        width: 7, height: 7, borderRadius: '50%',
        background: disp.color, display: 'inline-block', flexShrink: 0,
      }} />
      <span className="hi-suggestion-status-label" style={{ color: disp.color }}>
        {disp.label}
      </span>
    </div>
  );

  if (isStale) {
    return (
      <div className="hi-suggestion-wrap">
        {statusRow}
        <div className="hi-stale-banner">
          <span style={{ fontWeight: 600, fontSize: 12 }}>Conversa avançou</span>
          {text && (
            <div className="hi-suggestion-box stale">
              <div className="hi-suggestion-text">{text}</div>
            </div>
          )}
          <span className="hi-stale-banner-msg">
            Novas mensagens chegaram. A IA gerará uma nova sugestão automaticamente.
          </span>
        </div>
      </div>
    );
  }

  if (isTerminal) {
    return (
      <div className="hi-suggestion-wrap">
        {statusRow}
        {text && (
          <div className={`hi-suggestion-box ${effectiveStatus.toLowerCase()}`}>
            <div className="hi-suggestion-text">{text}</div>
          </div>
        )}
      </div>
    );
  }

  if (isPending) {
    return (
      <div className="hi-suggestion-wrap">
        {statusRow}
        <div className="hi-suggestion-box pending">
          <div className="hi-suggestion-text">{text || '…'}</div>
          <div className="hi-suggestion-meta">Aguarda sua aprovação antes de enviar</div>
        </div>
        <_HiSuggestionActions
          sugg={sugg}
          effectiveStatus={effectiveStatus}
          onDone={onDone}
          onError={onError}
        />
      </div>
    );
  }

  return null;
}

function _HiTakeoverSection({ sugg, convId, onDone, onError }) {
  const [loading, setLoading] = React.useState(false);

  async function handleTakeover() {
    if (loading) return;
    setLoading(true);
    _hiTrack('AI_TAKEOVER', { convId });
    const r = await _hiTakeover(sugg?.id || '', convId);
    setLoading(false);
    if (r.ok) onDone && onDone('HUMAN_ACTIVE');
    else onError && onError(r.error);
  }

  return (
    <div className="hi-takeover-row">
      <span className="hi-takeover-hint">Prefere atender você mesmo?</span>
      <button className="hi-btn hi-btn-takeover" disabled={loading} onClick={handleTakeover}>
        {loading && <span className="hi-spinner" />}
        Assumir atendimento
      </button>
    </div>
  );
}

function _HiHumanActiveBanner({ convId, onResume }) {
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]         = React.useState('');

  async function handleResume() {
    if (loading) return;
    setLoading(true); setErr('');
    try {
      const { error } = await window.HOROS_SB
        .from('conversations')
        .update({ intelligence_status: 'IDLE' })
        .eq('id', convId);
      if (error) setErr('Não foi possível retomar a IA.');
      else onResume && onResume();
    } catch { setErr('Erro ao retomar a IA.'); }
    setLoading(false);
  }

  return (
    <div className="hi-human-banner">
      <div className="hi-human-banner-title">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="8" r="4"/>
          <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
        </svg>
        Você está no controle
      </div>
      <div className="hi-human-banner-desc">
        A IA está pausada nesta conversa. Clique em "Retomar IA" para receber sugestões novamente.
      </div>
      {err && <div style={{ fontSize: 11, color: '#ef4444' }}>{err}</div>}
      <button className="hi-btn hi-btn-resume" disabled={loading} onClick={handleResume}>
        {loading && <span className="hi-spinner" />}
        Retomar IA
      </button>
    </div>
  );
}

/* ── HorosIntelligencePanel — seção no painel direito ────────────────────── */

function HorosIntelligencePanel({ conv, suggestion, intellStatus }) {
  const [open, setOpen]           = React.useState(true);
  const [err, setErr]             = React.useState('');
  const [localSugg, setLocalSugg] = React.useState(suggestion || null);
  const [localIntell, setLocalIntell] = React.useState(intellStatus || 'IDLE');

  React.useEffect(() => { setLocalSugg(suggestion || null); }, [suggestion]);
  React.useEffect(() => { setLocalIntell(intellStatus || 'IDLE'); }, [intellStatus]);

  const convVersion     = conv?.conversation_version ?? null;
  const effectiveStatus = _hiEffectiveStatus(localSugg, convVersion);
  const analysis        = localSugg?.explainability || null;

  const dotClass = localIntell === 'PROCESSING'         ? 'processing'
    : localIntell === 'SUGGESTION_PENDING' ? 'pending'
    : localIntell === 'HUMAN_ACTIVE'       ? 'active'
    : 'idle';

  function handleDone(newStatus) {
    setErr('');
    if (newStatus === 'HUMAN_ACTIVE') {
      setLocalIntell('HUMAN_ACTIVE');
      setLocalSugg(null);
    } else {
      setLocalSugg(s => s ? { ...s, status: newStatus, effective_status: newStatus } : s);
      setLocalIntell('IDLE');
    }
  }

  const showAnalysis   = !!analysis && localIntell !== 'HUMAN_ACTIVE';
  const showSuggestion = !!localSugg && localIntell !== 'HUMAN_ACTIVE' && effectiveStatus !== null;
  const showTakeover   = !!localSugg && effectiveStatus === 'PENDING' && localIntell !== 'HUMAN_ACTIVE';
  const showEmpty      = !localSugg && localIntell === 'IDLE';

  return (
    <div className="hi-panel">
      <div
        className="hi-panel-head"
        onClick={() => {
          const next = !open;
          setOpen(next);
          if (next) _hiTrack('AI_PANEL_OPENED', {});
        }}
      >
        <div className="hi-panel-title">
          <horos-mascot size="24" aria-hidden="true"
            state={localIntell === 'PROCESSING' ? 'thinking' : 'idle'}
            mood={localIntell === 'SUGGESTION_PENDING' ? 'happy' : localIntell === 'HUMAN_ACTIVE' ? 'sleepy' : 'normal'} />
          Horos Intelligence
          <span className={`hi-panel-title-dot ${dotClass}`} />
        </div>
        <svg
          className={`hi-panel-chevron ${open ? 'open' : ''}`}
          width="13" height="13" viewBox="0 0 16 16"
          fill="none" stroke="currentColor" strokeWidth="1.8"
          strokeLinecap="round" strokeLinejoin="round"
        >
          <path d="M4 6l4 4 4-4" />
        </svg>
      </div>

      {open && (
        <div className="hi-panel-body">
          {err && <div className="hi-error-msg">{err}</div>}

          {localIntell === 'HUMAN_ACTIVE' && (
            <_HiHumanActiveBanner
              convId={conv?.id}
              onResume={() => { setLocalIntell('IDLE'); setErr(''); }}
            />
          )}

          {localIntell === 'PROCESSING' && <_HiProcessingIndicator />}

          {showAnalysis && <_HiAnalysisSection analysis={analysis} />}

          {showAnalysis && showSuggestion && <hr className="hi-sep" />}

          {showSuggestion && (
            <_HiSuggestionDisplay
              sugg={localSugg}
              effectiveStatus={effectiveStatus}
              convId={conv?.id}
              onDone={handleDone}
              onError={msg => setErr(msg || 'Erro desconhecido')}
            />
          )}

          {showTakeover && (
            <_HiTakeoverSection
              sugg={localSugg}
              convId={conv?.id}
              onDone={handleDone}
              onError={msg => setErr(msg || 'Erro desconhecido')}
            />
          )}

          {showEmpty && (
            <div className="hi-empty">
              Aguardando próxima mensagem do lead.
            </div>
          )}
        </div>
      )}
    </div>
  );
}

window.HorosIntelligencePanel = HorosIntelligencePanel;

/* ── _HiSuggestionBar — barra compacta acima do input ───────────────────── */

function _HiSuggestionBar({ conv, suggestion, intellStatus, onApproved, onRejected }) {
  const [loading, setLoading] = React.useState(null);
  const [err, setErr]         = React.useState('');

  const effectiveStatus = _hiEffectiveStatus(suggestion, conv?.conversation_version);
  const text            = _hiSuggText(suggestion);

  const isProcessing = intellStatus === 'PROCESSING';
  const isPending    = effectiveStatus === 'PENDING';
  const isStale      = effectiveStatus === 'STALE';
  const isHuman      = intellStatus === 'HUMAN_ACTIVE';

  if (!isProcessing && !isPending && !isStale && !isHuman) return null;

  const barClass = isHuman ? 'human' : isProcessing ? 'processing' : isStale ? 'stale' : '';

  async function handleApprove() {
    if (loading || !suggestion) return;
    setLoading('approve'); setErr('');
    _hiTrack('AI_SUGGESTION_APPROVED', { suggId: suggestion.id });
    const r = await _hiApprove(suggestion.id);
    setLoading(null);
    if (r.ok) { onApproved && onApproved(r); }
    else setErr('Ocorreu um erro. Tente novamente.');
  }

  async function handleReject() {
    if (loading || !suggestion) return;
    setLoading('reject'); setErr('');
    _hiTrack('AI_SUGGESTION_REJECTED', { suggId: suggestion.id });
    const r = await _hiReject(suggestion.id);
    setLoading(null);
    if (r.ok) { onRejected && onRejected(r); }
    else setErr('Ocorreu um erro. Tente novamente.');
  }

  return (
    <div className={`hi-sugg-bar ${barClass}`}>
      <div className="hi-sugg-bar-icon">
        {isProcessing ? (
          <div className="hi-spinner" style={{ width: 13, height: 13 }} />
        ) : isHuman ? (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
            stroke="#1F93FF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="8" r="4"/>
            <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
          </svg>
        ) : (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
            stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
          </svg>
        )}
      </div>

      <span className="hi-sugg-bar-label">
        {isHuman       ? 'Você está no controle'
          : isProcessing ? 'Analisando…'
          : isStale      ? 'Sugestão desatualizada'
          : 'Sugestão IA'}
      </span>

      {isPending && !err && text && (
        <span className="hi-sugg-bar-text">{text}</span>
      )}

      {err && (
        <span style={{ flex: 1, fontSize: 10.5, color: '#ef4444' }}>{err}</span>
      )}

      {isPending && (
        <div className="hi-sugg-bar-actions">
          <button
            className="hi-bar-btn approve"
            disabled={!!loading}
            onClick={handleApprove}
          >
            {loading === 'approve' && <span className="hi-spinner" />}
            Aprovar
          </button>
          <button
            className="hi-bar-btn"
            disabled={!!loading}
            onClick={handleReject}
          >
            {loading === 'reject' && <span className="hi-spinner" />}
            Recusar
          </button>
        </div>
      )}
    </div>
  );
}

window._HiSuggestionBar = _HiSuggestionBar;
