// blacklist-match.jsx — potrivirea automata intre blacklist si aplicatiile primite.
//
// Ideea: o lista de blacklist pe care nimeni nu o deschide nu foloseste la nimic.
// Asa ca incarcam intrarile ACTIVE o data pe pagina si marcam direct in tabelul de
// influenceri / branduri pe cine avem deja pe lista. Potrivirea e "cat de bine putem",
// nu garantata: cine isi schimba si numele, si contul, si emailul nu e prins automat.
//
// Expune:
//   window.loadBlacklistIndex(type)  -> Promise<index>
//   window.matchBlacklist(index, {handle, email, cui, name}) -> intrare | null

function _blNorm(v) {
  return (v || '').toString().trim().toLowerCase().replace(/^@/, '');
}

async function loadBlacklistIndex(type) {
  const empty = { byHandle: {}, byEmail: {}, byCui: {}, byName: {} };
  if (!window.sb) return empty;
  try {
    const { data, error } = await window.sb
      .from('blacklist_entries')
      .select('id, type, name, tiktok_handle, email, cui, severity, reason, is_active')
      .eq('type', type)
      .eq('is_active', true);
    if (error) {
      // Tabelul poate sa nu existe inca (prima instalare) — nu blocam pagina.
      console.warn('[4U Media Admin] Blacklist index indisponibil:', error.message);
      return empty;
    }
    const index = { byHandle: {}, byEmail: {}, byCui: {}, byName: {} };
    (data || []).forEach(e => {
      if (e.tiktok_handle) index.byHandle[_blNorm(e.tiktok_handle)] = e;
      if (e.email) index.byEmail[_blNorm(e.email)] = e;
      if (e.cui) index.byCui[_blNorm(e.cui)] = e;
      if (e.name) index.byName[_blNorm(e.name)] = e;
    });
    return index;
  } catch (err) {
    console.warn('[4U Media Admin] Blacklist index error:', err);
    return empty;
  }
}

function matchBlacklist(index, fields) {
  if (!index || !fields) return null;
  const handle = _blNorm(fields.handle);
  const email = _blNorm(fields.email);
  const cui = _blNorm(fields.cui);
  const name = _blNorm(fields.name);
  // Ordinea conteaza: handle si CUI sunt cele mai sigure, numele cel mai slab.
  return (handle && index.byHandle[handle])
    || (cui && index.byCui[cui])
    || (email && index.byEmail[email])
    || (name && index.byName[name])
    || null;
}

// Badge mic pentru randurile din tabel.
function BlacklistFlag({ entry, compact }) {
  if (!entry) return null;
  const isHard = entry.severity === 'Blacklist';
  const color = isHard ? '#FF5A5A' : '#FFD700';
  const bg = isHard ? 'rgba(255,90,90,.12)' : 'rgba(255,215,0,.12)';
  const label = isHard ? 'BLACKLIST' : 'ATENȚIE';
  return (
    <span
      title={entry.reason || ''}
      style={{
        display: 'inline-block', fontSize: 9, fontWeight: 700, letterSpacing: '0.06em',
        padding: compact ? '2px 6px' : '3px 8px', borderRadius: 4,
        background: bg, color: color, border: '.5px solid ' + color + '55',
        marginLeft: compact ? 8 : 0, whiteSpace: 'nowrap', verticalAlign: 'middle',
      }}
    >{label}</span>
  );
}

// Banner mare pentru drawer-ul de detalii.
function BlacklistWarning({ entry, onNav }) {
  if (!entry) return null;
  const isHard = entry.severity === 'Blacklist';
  const color = isHard ? '#FF5A5A' : '#FFD700';
  return (
    <div style={{
      marginBottom: 24, padding: '16px 18px', borderRadius: 12,
      background: isHard ? 'rgba(255,90,90,.07)' : 'rgba(255,215,0,.07)',
      border: '1px solid ' + color + '4d',
    }}>
      <div style={{ fontSize: 14, fontWeight: 600, color: color, marginBottom: 6 }}>
        {isHard ? '⛔ Este pe blacklist' : '⚠️ Este sub atenționare'}
      </div>
      <div style={{ fontSize: 13, color: 'var(--txt-1)', lineHeight: 1.5, whiteSpace: 'pre-wrap' }}>
        {entry.reason}
      </div>
      {onNav && (
        <button onClick={() => onNav('media-admin-blacklist')} style={{
          marginTop: 10, background: 'transparent', border: 'none', padding: 0,
          color: color, fontSize: 12, cursor: 'pointer', textDecoration: 'underline',
        }}>Vezi în blacklist →</button>
      )}
    </div>
  );
}

window.loadBlacklistIndex = loadBlacklistIndex;
window.matchBlacklist = matchBlacklist;
window.BlacklistFlag = BlacklistFlag;
window.BlacklistWarning = BlacklistWarning;
