// media-admin-blacklist.jsx — Blacklist creatori + branduri.
// O singura lista in baza de date (blacklist_entries), doua tab-uri in interfata.
// Intrarile nu se sterg cand nu mai sunt valabile: se dezactiveaza (is_active=false),
// ca sa ramana istoricul. Stergerea definitiva e doar pentru admini.

const { useState: useStateBL, useEffect: useEffectBL } = React;

const SEVERITY_OPTIONS_BL = [
  { value: 'Blacklist', label: 'Blacklist', hint: 'Nu lucrăm cu el, punct.' },
  { value: 'Atentie', label: 'Atenționare', hint: 'Se poate lucra, dar cu grijă.' },
];
const SEVERITY_COLORS_BL = {
  'Blacklist': { bg: 'rgba(255,90,90,.12)', color: '#FF5A5A', border: 'rgba(255,90,90,.3)' },
  'Atentie': { bg: 'rgba(255,215,0,.12)', color: '#FFD700', border: 'rgba(255,215,0,.3)' },
};
const SEVERITY_LABEL_BL = { 'Blacklist': 'Blacklist', 'Atentie': 'Atenționare' };

function MediaAdminBlacklist({ onNav }) {
  const [profile, setProfile] = useStateBL(null);
  const [loading, setLoading] = useStateBL(true);
  const [entries, setEntries] = useStateBL([]);
  const [staffList, setStaffList] = useStateBL([]);
  const [tab, setTab] = useStateBL('creator');
  const [search, setSearch] = useStateBL('');
  const [severityFilter, setSeverityFilter] = useStateBL('Toate');
  const [activeFilter, setActiveFilter] = useStateBL('Active');
  const [sortBy, setSortBy] = useStateBL('created_at');
  const [sortDir, setSortDir] = useStateBL('desc');
  const [selected, setSelected] = useStateBL(null);
  const [showAdd, setShowAdd] = useStateBL(false);
  const [refreshKey, setRefreshKey] = useStateBL(0);
  const [currentPage, setCurrentPage] = useStateBL(1);
  const [perPage, setPerPage] = useStateBL(20);
  const [loadError, setLoadError] = useStateBL('');

  useEffectBL(() => { setCurrentPage(1); }, [tab, search, severityFilter, activeFilter, perPage]);

  useEffectBL(() => {
    let mounted = true;
    (async () => {
      try {
        let tries = 0;
        while (!window.sb && tries < 100) { await new Promise(r => setTimeout(r, 50)); tries++; }
        if (!window.sb) { onNav('media-login'); return; }

        const { data: { session } } = await window.sb.auth.getSession();
        if (!session) { onNav('media-login'); return; }

        const { data: prof, error } = await window.sb
          .from('staff_profiles').select('id, full_name, email, role, is_active')
          .eq('id', session.user.id).maybeSingle();
        if (error || !prof || !prof.is_active) {
          await window.sb.auth.signOut(); onNav('media-login'); return;
        }
        if (!mounted) return;
        setProfile(prof);

        const [{ data: list, error: listErr }, { data: staff }] = await Promise.all([
          window.sb.from('blacklist_entries').select('*').order('created_at', { ascending: false }),
          window.sb.from('staff_profiles').select('id, full_name').eq('is_active', true).order('full_name'),
        ]);
        if (!mounted) return;
        if (listErr) {
          console.error('[4U Media Admin] Blacklist load error:', listErr);
          setLoadError('Nu am putut încărca lista. Dacă e prima folosire, rulează scriptul din media/sql/01-blacklist.sql în Supabase.');
        }
        setEntries(list || []);
        setStaffList(staff || []);
        setLoading(false);
      } catch (err) {
        console.error('[4U Media Admin] Blacklist page error:', err);
        onNav('media-login');
      }
    })();
    return () => { mounted = false; };
  }, [refreshKey]);

  const ofType = entries.filter(e => e.type === tab);

  const filtered = ofType.filter(e => {
    if (activeFilter === 'Active' && !e.is_active) return false;
    if (activeFilter === 'Inactive' && e.is_active) return false;
    if (severityFilter !== 'Toate' && e.severity !== severityFilter) return false;
    if (search) {
      const s = search.toLowerCase();
      const haystack = [e.name, e.tiktok_handle, e.email, e.phone, e.cui, e.website, e.reason]
        .map(v => (v || '').toLowerCase()).join(' ');
      if (!haystack.includes(s)) return false;
    }
    return true;
  }).sort((a, b) => {
    let valA = a[sortBy], valB = b[sortBy];
    if (valA === null || valA === undefined) valA = '';
    if (valB === null || valB === undefined) valB = '';
    if (typeof valA === 'string') valA = valA.toLowerCase();
    if (typeof valB === 'string') valB = valB.toLowerCase();
    if (valA < valB) return sortDir === 'asc' ? -1 : 1;
    if (valA > valB) return sortDir === 'asc' ? 1 : -1;
    return 0;
  });

  const totalPages = Math.max(1, Math.ceil(filtered.length / perPage));
  const safePage = Math.min(Math.max(1, currentPage), totalPages);
  const paginated = filtered.slice((safePage - 1) * perPage, safePage * perPage);

  const handleSort = (key) => {
    if (sortBy === key) setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    else { setSortBy(key); setSortDir('asc'); }
  };

  const countActive = (type, severity) => entries.filter(e =>
    e.type === type && e.is_active && (!severity || e.severity === severity)).length;

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
          <span style={{ width: 32, height: 32, borderRadius: 999, border: '3px solid rgba(82,242,15,.2)', borderTopColor: 'var(--accent-1)', animation: 'bl-spin 0.8s linear infinite' }} />
          <span style={{ color: 'var(--txt-3)', fontSize: 13 }}>Se încarcă...</span>
        </div>
        <style>{`@keyframes bl-spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  const isCreator = tab === 'creator';

  return (
    <MediaAdminLayout onNav={onNav} currentPage="media-admin-blacklist" profile={profile}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28, flexWrap: 'wrap', gap: 16 }}>
        <div>
          <h1 className="display" style={{ fontSize: 'clamp(28px, 4vw, 40px)', margin: '0 0 8px' }}>Blacklist</h1>
          <p style={{ color: 'var(--txt-2)', fontSize: 15, margin: 0, maxWidth: 620 }}>
            Creatori și branduri cu care nu mai lucrăm. Lista e vizibilă doar echipei — nu apare nicăieri pe site.
          </p>
        </div>
        <button onClick={() => setShowAdd(true)} className="btn btn-primary" style={{ cursor: 'pointer' }}>
          + Adaugă {isCreator ? 'creator' : 'brand'}
        </button>
      </div>

      {loadError && (
        <div style={{ marginBottom: 24, padding: '14px 16px', borderRadius: 10, background: 'rgba(255,90,90,.08)', border: '.5px solid rgba(255,100,100,.3)', fontSize: 13, color: 'var(--txt-1)' }}>
          ⚠️ {loadError}
        </div>
      )}

      {/* Sumar */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16, marginBottom: 28 }}>
        <BlStat label="Creatori blocați" count={countActive('creator', 'Blacklist')} accent="#FF5A5A" />
        <BlStat label="Creatori sub atenționare" count={countActive('creator', 'Atentie')} accent="#FFD700" />
        <BlStat label="Branduri blocate" count={countActive('brand', 'Blacklist')} accent="#FF5A5A" />
        <BlStat label="Branduri sub atenționare" count={countActive('brand', 'Atentie')} accent="#FFD700" />
      </div>

      {/* Tab-uri */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 20, borderBottom: '.5px solid var(--line)' }}>
        {[['creator', '🎬 Creatori'], ['brand', '🏢 Branduri']].map(([id, label]) => {
          const active = tab === id;
          return (
            <button key={id} onClick={() => setTab(id)} style={{
              padding: '10px 18px', border: 'none', background: 'transparent',
              color: active ? 'var(--accent-1)' : 'var(--txt-2)',
              fontSize: 14, fontWeight: active ? 600 : 500, cursor: 'pointer',
              borderBottom: active ? '2px solid var(--accent-1)' : '2px solid transparent',
              marginBottom: -1, transition: 'color .15s'
            }}>
              {label}
              <span style={{ marginLeft: 8, fontSize: 12, color: 'var(--txt-3)' }}>
                {entries.filter(e => e.type === id && e.is_active).length}
              </span>
            </button>
          );
        })}
      </div>

      {/* Filtre */}
      <div className="filter-panel" style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
        <input type="text" className="input" style={{ flex: 1, minWidth: 280 }}
          placeholder={isCreator ? '🔍 Caută după nume, @tiktok, email, telefon sau motiv...' : '🔍 Caută după companie, CUI, email, site sau motiv...'}
          value={search} onChange={e => setSearch(e.target.value)} />
        <select value={severityFilter} onChange={e => setSeverityFilter(e.target.value)}
          className="input" style={{ width: 200, color: '#FFFFFF', backgroundColor: '#1a1a1a', cursor: 'pointer' }}>
          <option value="Toate" style={{ backgroundColor: '#1a1a1a' }}>Toate gravitățile</option>
          {SEVERITY_OPTIONS_BL.map(s => <option key={s.value} value={s.value} style={{ backgroundColor: '#1a1a1a' }}>{s.label}</option>)}
        </select>
        <select value={activeFilter} onChange={e => setActiveFilter(e.target.value)}
          className="input" style={{ width: 200, color: '#FFFFFF', backgroundColor: '#1a1a1a', cursor: 'pointer' }}>
          <option value="Active" style={{ backgroundColor: '#1a1a1a' }}>Doar active</option>
          <option value="Inactive" style={{ backgroundColor: '#1a1a1a' }}>Doar ridicate</option>
          <option value="Toate" style={{ backgroundColor: '#1a1a1a' }}>Toate</option>
        </select>
      </div>

      {/* Tabel */}
      <div className="card-glass" style={{ padding: 0, overflow: 'hidden' }}>
        {filtered.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--txt-3)' }}>
            {ofType.length === 0
              ? (isCreator ? 'Niciun creator pe blacklist. Bine!' : 'Niciun brand pe blacklist. Bine!')
              : 'Niciun rezultat care să corespundă filtrelor.'}
          </div>
        ) : (
          <div className="ma-table-scroll" style={{ overflowX: 'auto', overflowY: 'hidden' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: 'rgba(255,255,255,.03)' }}>
                  <ThBl sortKey="name" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>{isCreator ? 'Nume' : 'Companie'}</ThBl>
                  {isCreator
                    ? <ThBl sortKey="tiktok_handle" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>TikTok</ThBl>
                    : <ThBl sortKey="cui" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>CUI</ThBl>}
                  <ThBl sortKey="email" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Contact</ThBl>
                  <ThBl sortKey="severity" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Gravitate</ThBl>
                  <ThBl>Motiv</ThBl>
                  <ThBl sortKey="added_by" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Adăugat de</ThBl>
                  <ThBl sortKey="created_at" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Data</ThBl>
                </tr>
              </thead>
              <tbody>
                {paginated.map(e => {
                  const by = staffList.find(s => s.id === e.added_by);
                  return (
                    <tr key={e.id} onClick={() => setSelected(e)}
                      style={{ cursor: 'pointer', borderTop: '.5px solid var(--line)', transition: 'background .15s', opacity: e.is_active ? 1 : 0.45 }}
                      onMouseEnter={ev => ev.currentTarget.style.background = 'rgba(255,90,90,.04)'}
                      onMouseLeave={ev => ev.currentTarget.style.background = 'transparent'}>
                      <TdBl>
                        <strong>{e.name}</strong>
                        {!e.is_active && <span style={{ marginLeft: 8, fontSize: 10, padding: '2px 7px', borderRadius: 4, background: 'rgba(255,255,255,.06)', color: 'var(--txt-3)' }}>ridicat</span>}
                      </TdBl>
                      <TdBl>
                        {isCreator
                          ? (e.tiktok_handle ? <span className="mono" style={{ fontSize: 12 }}>@{e.tiktok_handle}</span> : <span style={{ color: 'var(--txt-3)' }}>—</span>)
                          : (e.cui ? <span className="mono" style={{ fontSize: 12 }}>{e.cui}</span> : <span style={{ color: 'var(--txt-3)' }}>—</span>)}
                      </TdBl>
                      <TdBl>
                        <span style={{ color: 'var(--txt-2)' }}>{e.email || e.phone || '—'}</span>
                      </TdBl>
                      <TdBl><SeverityBadgeBl severity={e.severity} /></TdBl>
                      <TdBl>
                        <span style={{ color: 'var(--txt-2)', display: 'inline-block', maxWidth: 260, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', verticalAlign: 'middle' }}>{e.reason}</span>
                      </TdBl>
                      <TdBl>{by ? by.full_name : <span style={{ color: 'var(--txt-3)' }}>—</span>}</TdBl>
                      <TdBl><span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>{new Date(e.created_at).toLocaleDateString('ro-RO')}</span></TdBl>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <window.PaginationControl
        totalItems={filtered.length}
        currentPage={safePage}
        perPage={perPage}
        onPageChange={setCurrentPage}
        onPerPageChange={(v) => { setPerPage(v); setCurrentPage(1); }}
      />

      {selected && (
        <BlacklistDrawer
          entry={selected}
          staffList={staffList}
          profile={profile}
          onClose={() => setSelected(null)}
          onUpdate={() => { setRefreshKey(k => k + 1); setSelected(null); }}
        />
      )}

      {showAdd && (
        <BlacklistAddDrawer
          type={tab}
          profile={profile}
          onClose={() => setShowAdd(false)}
          onAdd={() => { setRefreshKey(k => k + 1); setShowAdd(false); }}
        />
      )}
    </MediaAdminLayout>
  );
}

// ---------------------------------------------------------------- componente

function BlStat({ label, count, accent }) {
  return (
    <div className="card-glass" style={{ padding: 20 }}>
      <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 10 }}>{label.toUpperCase()}</div>
      <div className="display" style={{ fontSize: 34, color: count > 0 ? accent : 'var(--txt-3)', lineHeight: 1 }}>{count}</div>
    </div>
  );
}

function ThBl({ children, sortKey, currentSort, currentDir, onSort }) {
  const isActive = sortKey && currentSort === sortKey;
  const clickable = !!sortKey;
  return (
    <th onClick={clickable ? () => onSort(sortKey) : undefined}
      style={{
        textAlign: 'left', padding: '14px 16px', fontWeight: 600, fontSize: 11,
        color: isActive ? 'var(--accent-1)' : 'var(--txt-3)',
        textTransform: 'uppercase', letterSpacing: '0.05em',
        cursor: clickable ? 'pointer' : 'default', userSelect: 'none'
      }}>
      {children}
      {isActive && <span style={{ marginLeft: 6 }}>{currentDir === 'asc' ? '↑' : '↓'}</span>}
    </th>
  );
}

function TdBl({ children }) {
  return <td style={{ padding: '14px 16px', color: 'var(--txt-1)' }}>{children}</td>;
}

function SeverityBadgeBl({ severity }) {
  const c = SEVERITY_COLORS_BL[severity] || { bg: 'rgba(255,255,255,.05)', color: 'var(--txt-2)', border: 'var(--line)' };
  return (
    <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: c.bg, color: c.color, border: '.5px solid ' + c.border, fontWeight: 500, whiteSpace: 'nowrap' }}>
      {SEVERITY_LABEL_BL[severity] || severity}
    </span>
  );
}

function FieldBl({ label, value }) {
  if (!value) return null;
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 14, color: 'var(--txt-0)', wordBreak: 'break-word' }}>{value}</div>
    </div>
  );
}

function EditFieldBl({ label, children, hint }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 6, display: 'block' }}>{label.toUpperCase()}</label>
      {children}
      {hint && <div style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 5 }}>{hint}</div>}
    </div>
  );
}

function SeverityPickerBl({ value, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
      {SEVERITY_OPTIONS_BL.map(opt => {
        const active = value === opt.value;
        const c = SEVERITY_COLORS_BL[opt.value];
        return (
          <button key={opt.value} type="button" onClick={() => onChange(opt.value)} style={{
            flex: '1 1 180px', padding: '10px 14px', borderRadius: 8, textAlign: 'left',
            border: active ? '1px solid ' + c.color : '.5px solid var(--line)',
            background: active ? c.bg : 'transparent',
            color: active ? c.color : 'var(--txt-2)',
            fontSize: 13, fontWeight: 500, cursor: 'pointer'
          }}>
            <div>{opt.label}</div>
            <div style={{ fontSize: 11, opacity: .75, marginTop: 3, fontWeight: 400 }}>{opt.hint}</div>
          </button>
        );
      })}
    </div>
  );
}

// ------------------------------------------------------------------- drawere

function BlacklistDrawer({ entry, staffList, profile, onClose, onUpdate }) {
  const isCreator = entry.type === 'creator';
  const [name, setName] = useStateBL(entry.name || '');
  const [handle, setHandle] = useStateBL(entry.tiktok_handle || '');
  const [email, setEmail] = useStateBL(entry.email || '');
  const [phone, setPhone] = useStateBL(entry.phone || '');
  const [cui, setCui] = useStateBL(entry.cui || '');
  const [website, setWebsite] = useStateBL(entry.website || '');
  const [severity, setSeverity] = useStateBL(entry.severity || 'Blacklist');
  const [reason, setReason] = useStateBL(entry.reason || '');
  const [evidence, setEvidence] = useStateBL(entry.evidence || '');
  const [notes, setNotes] = useStateBL(entry.internal_notes || '');
  const [saving, setSaving] = useStateBL(false);
  const [errorMsg, setErrorMsg] = useStateBL('');
  const [confirm, setConfirm] = useStateBL(null);

  const addedBy = staffList.find(s => s.id === entry.added_by);
  const isAdmin = profile && profile.role === 'admin';

  const handleSave = async () => {
    setErrorMsg('');
    if (!name.trim()) { setErrorMsg('Numele e obligatoriu.'); return; }
    if (!reason.trim()) { setErrorMsg('Motivul e obligatoriu — altfel lista nu ajută pe nimeni peste 6 luni.'); return; }
    setSaving(true);
    try {
      const { error } = await window.sb.from('blacklist_entries').update({
        name: name.trim(),
        tiktok_handle: isCreator ? (handle.trim().replace(/^@/, '') || null) : null,
        email: email.trim().toLowerCase() || null,
        phone: phone.trim() || null,
        cui: isCreator ? null : (cui.trim() || null),
        website: isCreator ? null : (website.trim() || null),
        severity,
        reason: reason.trim(),
        evidence: evidence.trim() || null,
        internal_notes: notes.trim() || null,
      }).eq('id', entry.id);
      if (error) { setErrorMsg('Eroare la salvare: ' + error.message); setSaving(false); return; }
      setSaving(false);
      onUpdate();
    } catch (err) {
      setErrorMsg('Conexiune eșuată. Verifică internetul.');
      setSaving(false);
    }
  };

  const toggleActive = async () => {
    setSaving(true);
    setErrorMsg('');
    try {
      const { error } = await window.sb.from('blacklist_entries')
        .update({ is_active: !entry.is_active }).eq('id', entry.id);
      if (error) { setErrorMsg('Eroare: ' + error.message); setSaving(false); return; }
      setSaving(false);
      onUpdate();
    } catch (err) { setErrorMsg('Conexiune eșuată.'); setSaving(false); }
  };

  const handleDelete = async () => {
    setSaving(true);
    setErrorMsg('');
    try {
      const { error } = await window.sb.from('blacklist_entries').delete().eq('id', entry.id);
      if (error) { setErrorMsg('Eroare la ștergere: ' + error.message); setSaving(false); return; }
      setSaving(false);
      onUpdate();
    } catch (err) { setErrorMsg('Conexiune eșuată.'); setSaving(false); }
  };

  return (
    <div className="ma-modal-wrap" onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.6)', backdropFilter: 'blur(4px)' }}>
      <div className="ma-modal" onClick={e => e.stopPropagation()} style={{
        maxWidth: 780, width: '90vw', maxHeight: '90vh', overflow: 'auto',
        background: '#0a0a0a', border: '.5px solid var(--line)', borderRadius: 16, padding: 32
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8, gap: 16 }}>
          <div>
            <h2 className="display" style={{ fontSize: 22, margin: '0 0 8px' }}>{entry.name}</h2>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
              <SeverityBadgeBl severity={entry.severity} />
              <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: 'rgba(255,255,255,.05)', color: 'var(--txt-2)' }}>
                {isCreator ? 'Creator' : 'Brand'}
              </span>
              {!entry.is_active && (
                <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: 'rgba(82,242,15,.1)', color: 'var(--accent-1)' }}>
                  Restricție ridicată
                </span>
              )}
            </div>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer', padding: 4 }}>✕</button>
        </div>

        <div style={{ marginTop: 24, marginBottom: 24, paddingBottom: 20, borderBottom: '.5px solid var(--line)' }}>
          <FieldBl label="Adăugat de" value={addedBy ? addedBy.full_name : '—'} />
          <FieldBl label="Adăugat pe" value={new Date(entry.created_at).toLocaleString('ro-RO')} />
          {entry.updated_at && entry.updated_at !== entry.created_at && (
            <FieldBl label="Ultima modificare" value={new Date(entry.updated_at).toLocaleString('ro-RO')} />
          )}
        </div>

        <h3 style={{ fontSize: 14, margin: '0 0 20px', color: 'var(--accent-1)' }}>✏️ Modifică</h3>

        <EditFieldBl label={isCreator ? 'Nume creator' : 'Nume companie'}>
          <input className="input" style={{ width: '100%' }} value={name} onChange={e => setName(e.target.value)} />
        </EditFieldBl>

        {isCreator ? (
          <EditFieldBl label="Cont TikTok">
            <input className="input" style={{ width: '100%' }} value={handle} onChange={e => setHandle(e.target.value)} placeholder="numecont (fără @)" />
          </EditFieldBl>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
            <EditFieldBl label="CUI">
              <input className="input" style={{ width: '100%' }} value={cui} onChange={e => setCui(e.target.value)} />
            </EditFieldBl>
            <EditFieldBl label="Website">
              <input className="input" style={{ width: '100%' }} value={website} onChange={e => setWebsite(e.target.value)} />
            </EditFieldBl>
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
          <EditFieldBl label="Email">
            <input className="input" style={{ width: '100%' }} type="email" value={email} onChange={e => setEmail(e.target.value)} />
          </EditFieldBl>
          <EditFieldBl label="Telefon">
            <input className="input" style={{ width: '100%' }} value={phone} onChange={e => setPhone(e.target.value)} />
          </EditFieldBl>
        </div>

        <EditFieldBl label="Gravitate">
          <SeverityPickerBl value={severity} onChange={setSeverity} />
        </EditFieldBl>

        <EditFieldBl label="Motiv" hint="Scrie concret ce s-a întâmplat. Peste un an nimeni nu mai ține minte.">
          <textarea className="input" rows={3} value={reason} onChange={e => setReason(e.target.value)}
            style={{ width: '100%', resize: 'vertical', minHeight: 70, fontFamily: 'inherit', lineHeight: 1.5 }} />
        </EditFieldBl>

        <EditFieldBl label="Dovezi" hint="Link-uri către conversații, capturi, contracte.">
          <textarea className="input" rows={2} value={evidence} onChange={e => setEvidence(e.target.value)}
            style={{ width: '100%', resize: 'vertical', minHeight: 56, fontFamily: 'inherit', lineHeight: 1.5 }} />
        </EditFieldBl>

        <EditFieldBl label="Note interne">
          <textarea className="input" rows={3} value={notes} onChange={e => setNotes(e.target.value)}
            style={{ width: '100%', resize: 'vertical', minHeight: 70, fontFamily: 'inherit', lineHeight: 1.5 }} />
        </EditFieldBl>

        {errorMsg && (
          <div style={{ marginTop: 16, padding: '10px 12px', borderRadius: 8, background: 'rgba(255,90,90,.08)', border: '.5px solid rgba(255,100,100,.3)', fontSize: 12, color: 'var(--txt-2)' }}>
            ⚠️ {errorMsg}
          </div>
        )}

        <button onClick={handleSave} disabled={saving} className="btn btn-primary"
          style={{ width: '100%', marginTop: 20, opacity: saving ? 0.6 : 1, cursor: saving ? 'not-allowed' : 'pointer' }}>
          {saving ? 'Se salvează...' : 'Salvează modificările'}
        </button>

        <div style={{ display: 'flex', gap: 10, marginTop: 12, flexWrap: 'wrap' }}>
          <button onClick={() => setConfirm('toggle')} disabled={saving} className="btn btn-glass"
            style={{ flex: '1 1 200px', cursor: saving ? 'not-allowed' : 'pointer' }}>
            {entry.is_active ? 'Ridică restricția' : 'Pune la loc pe blacklist'}
          </button>
          {isAdmin && (
            <button onClick={() => setConfirm('delete')} disabled={saving}
              style={{
                flex: '1 1 200px', padding: '12px 20px', borderRadius: 10,
                border: '.5px solid rgba(255,90,90,.3)', background: 'rgba(255,90,90,.06)',
                color: '#FF5A5A', fontSize: 14, fontWeight: 500,
                cursor: saving ? 'not-allowed' : 'pointer'
              }}>
              Șterge definitiv
            </button>
          )}
        </div>

        {!isAdmin && (
          <p style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 12, textAlign: 'center' }}>
            Ștergerea definitivă e disponibilă doar adminilor. Tu poți ridica restricția — intrarea rămâne în istoric.
          </p>
        )}

        {confirm === 'toggle' && (
          <window.ConfirmDialog
            title={entry.is_active ? 'Ridici restricția?' : 'Pui la loc pe blacklist?'}
            message={entry.is_active
              ? 'Intrarea rămâne salvată în istoric, dar nu mai apare ca activă și nu mai declanșează avertisment când persoana asta apare în aplicații.'
              : 'Intrarea redevine activă și va apărea din nou ca avertisment.'}
            confirmText={entry.is_active ? 'Da, ridică' : 'Da, pune la loc'}
            cancelText="Anulează"
            onConfirm={() => { setConfirm(null); toggleActive(); }}
            onCancel={() => setConfirm(null)}
          />
        )}

        {confirm === 'delete' && (
          <window.ConfirmDialog
            title="Ștergi definitiv?"
            message={'"' + entry.name + '" dispare complet din baza de date, împreună cu motivul și dovezile. Nu se poate anula. Dacă vrei doar să nu mai apară ca activ, folosește "Ridică restricția".'}
            confirmText="Da, șterge definitiv"
            cancelText="Anulează"
            danger={true}
            onConfirm={() => { setConfirm(null); handleDelete(); }}
            onCancel={() => setConfirm(null)}
          />
        )}
      </div>
    </div>
  );
}

function BlacklistAddDrawer({ type, profile, onClose, onAdd }) {
  const isCreator = type === 'creator';
  const [name, setName] = useStateBL('');
  const [handle, setHandle] = useStateBL('');
  const [email, setEmail] = useStateBL('');
  const [phone, setPhone] = useStateBL('');
  const [cui, setCui] = useStateBL('');
  const [website, setWebsite] = useStateBL('');
  const [severity, setSeverity] = useStateBL('Blacklist');
  const [reason, setReason] = useStateBL('');
  const [evidence, setEvidence] = useStateBL('');
  const [notes, setNotes] = useStateBL('');
  const [saving, setSaving] = useStateBL(false);
  const [errorMsg, setErrorMsg] = useStateBL('');

  const save = async () => {
    setErrorMsg('');
    if (!name.trim()) { setErrorMsg(isCreator ? 'Numele creatorului e obligatoriu.' : 'Numele companiei e obligatoriu.'); return; }
    if (!reason.trim()) { setErrorMsg('Scrie motivul — altfel lista nu ajută pe nimeni peste 6 luni.'); return; }
    if (email.trim()) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(email.trim())) { setErrorMsg('Email-ul nu pare valid.'); return; }
    }
    setSaving(true);
    try {
      const { error } = await window.sb.from('blacklist_entries').insert({
        type,
        name: name.trim(),
        tiktok_handle: isCreator ? (handle.trim().replace(/^@/, '') || null) : null,
        email: email.trim().toLowerCase() || null,
        phone: phone.trim() || null,
        cui: isCreator ? null : (cui.trim() || null),
        website: isCreator ? null : (website.trim() || null),
        severity,
        reason: reason.trim(),
        evidence: evidence.trim() || null,
        internal_notes: notes.trim() || null,
        is_active: true,
        added_by: profile ? profile.id : null,
      });
      if (error) { setErrorMsg('Eroare: ' + error.message); setSaving(false); return; }
      setSaving(false);
      onAdd();
    } catch (err) { setErrorMsg('Conexiune eșuată.'); setSaving(false); }
  };

  return (
    <div className="ma-modal-wrap" onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.6)', backdropFilter: 'blur(4px)' }}>
      <div className="ma-modal" onClick={e => e.stopPropagation()} style={{
        maxWidth: 780, width: '90vw', maxHeight: '90vh', overflow: 'auto',
        background: '#0a0a0a', border: '.5px solid var(--line)', borderRadius: 16, padding: 32
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
          <h2 className="display" style={{ fontSize: 22, margin: 0 }}>
            Adaugă {isCreator ? 'creator' : 'brand'} pe blacklist
          </h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer', padding: 4 }}>✕</button>
        </div>
        <p style={{ color: 'var(--txt-2)', fontSize: 13, margin: '0 0 24px' }}>
          Doar numele și motivul sunt obligatorii. Restul datelor ajută la recunoașterea lui dacă revine sub alt nume.
        </p>

        <EditFieldBl label={isCreator ? 'Nume creator *' : 'Nume companie *'}>
          <input className="input" style={{ width: '100%' }} value={name} onChange={e => setName(e.target.value)}
            placeholder={isCreator ? 'Ion Popescu' : 'Exemplu SRL'} />
        </EditFieldBl>

        {isCreator ? (
          <EditFieldBl label="Cont TikTok">
            <input className="input" style={{ width: '100%' }} value={handle} onChange={e => setHandle(e.target.value)} placeholder="numecont (fără @)" />
          </EditFieldBl>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
            <EditFieldBl label="CUI">
              <input className="input" style={{ width: '100%' }} value={cui} onChange={e => setCui(e.target.value)} placeholder="RO12345678" />
            </EditFieldBl>
            <EditFieldBl label="Website">
              <input className="input" style={{ width: '100%' }} value={website} onChange={e => setWebsite(e.target.value)} placeholder="exemplu.ro" />
            </EditFieldBl>
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
          <EditFieldBl label="Email">
            <input className="input" style={{ width: '100%' }} type="email" value={email} onChange={e => setEmail(e.target.value)} />
          </EditFieldBl>
          <EditFieldBl label="Telefon">
            <input className="input" style={{ width: '100%' }} value={phone} onChange={e => setPhone(e.target.value)} />
          </EditFieldBl>
        </div>

        <EditFieldBl label="Gravitate *">
          <SeverityPickerBl value={severity} onChange={setSeverity} />
        </EditFieldBl>

        <EditFieldBl label="Motiv *" hint="Concret: ce a făcut, când, ce ne-a costat.">
          <textarea className="input" rows={3} value={reason} onChange={e => setReason(e.target.value)}
            placeholder={isCreator
              ? 'Ex: a acceptat 3 campanii în ianuarie și nu a livrat niciuna, nu a mai răspuns la mesaje.'
              : 'Ex: nu a plătit factura din februarie, a schimbat brief-ul după filmare, a cerut conținut gratuit.'}
            style={{ width: '100%', resize: 'vertical', minHeight: 70, fontFamily: 'inherit', lineHeight: 1.5 }} />
        </EditFieldBl>

        <EditFieldBl label="Dovezi" hint="Link-uri către conversații, capturi, contracte.">
          <textarea className="input" rows={2} value={evidence} onChange={e => setEvidence(e.target.value)}
            style={{ width: '100%', resize: 'vertical', minHeight: 56, fontFamily: 'inherit', lineHeight: 1.5 }} />
        </EditFieldBl>

        <EditFieldBl label="Note interne">
          <textarea className="input" rows={3} value={notes} onChange={e => setNotes(e.target.value)}
            placeholder="Observații pentru echipă."
            style={{ width: '100%', resize: 'vertical', minHeight: 70, fontFamily: 'inherit', lineHeight: 1.5 }} />
        </EditFieldBl>

        {errorMsg && (
          <div style={{ marginTop: 16, padding: '10px 12px', borderRadius: 8, background: 'rgba(255,90,90,.08)', border: '.5px solid rgba(255,100,100,.3)', fontSize: 12, color: 'var(--txt-2)' }}>
            ⚠️ {errorMsg}
          </div>
        )}

        <div style={{ display: 'flex', gap: 10, marginTop: 24, flexWrap: 'wrap' }}>
          <button onClick={onClose} className="btn btn-glass" style={{ flex: '1 1 140px', cursor: 'pointer' }}>Anulează</button>
          <button onClick={save} disabled={saving} className="btn btn-primary"
            style={{ flex: '2 1 240px', opacity: saving ? 0.6 : 1, cursor: saving ? 'not-allowed' : 'pointer' }}>
            {saving ? 'Se salvează...' : 'Adaugă pe blacklist'}
          </button>
        </div>
      </div>
    </div>
  );
}

window.MediaAdminBlacklist = MediaAdminBlacklist;
