const { useState: useStateMI, useEffect: useEffectMI } = React;

const STATUS_OPTIONS = ['Nou', 'În discuție', 'Acceptat', 'Respins', 'În așteptare'];
const STATUS_COLORS = {
  'Nou': { bg: 'rgba(82,242,15,.1)', color: 'var(--accent-1)' },
  'În discuție': { bg: 'rgba(63,169,245,.1)', color: '#3FA9F5' },
  'Acceptat': { bg: 'rgba(255,215,0,.1)', color: '#FFD700' },
  'Respins': { bg: 'rgba(255,90,90,.1)', color: '#FF5A5A' },
  'În așteptare': { bg: 'rgba(255,255,255,.05)', color: 'var(--txt-2)' },
};

function MediaAdminInfluencers({ onNav }) {
  const [profile, setProfile] = useStateMI(null);
  const [loading, setLoading] = useStateMI(true);
  const [apps, setApps] = useStateMI([]);
  const [staffList, setStaffList] = useStateMI([]);
  const [search, setSearch] = useStateMI('');
  const [statusFilter, setStatusFilter] = useStateMI('Toate');
  const [selectedApp, setSelectedApp] = useStateMI(null);
  const [refreshKey, setRefreshKey] = useStateMI(0);
  const [activeCampaignsByInfluencer, setActiveCampaignsByInfluencer] = useStateMI({});
  const [sortBy, setSortBy] = useStateMI('created_at');
  const [sortDir, setSortDir] = useStateMI('desc');
  const [showAddDrawer, setShowAddDrawer] = useStateMI(false);

  useEffectMI(() => {
    (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;
        }
        setProfile(prof);

        // Fetch toate aplicațiile + staff list
        const [{ data: appsData }, { data: staff }] = await Promise.all([
          window.sb.from('influencer_applications').select('*').order('created_at', { ascending: false }),
          window.sb.from('staff_profiles').select('id, full_name').eq('is_active', true).order('full_name'),
        ]);
        setApps(appsData || []);
        setStaffList(staff || []);

        // Fetch campanii active per influencer
        const { data: ccData } = await window.sb
          .from('campaign_creators')
          .select('influencer_id, campaigns(status)');

        const counts = {};
        (ccData || []).forEach(cc => {
          if (cc.campaigns && cc.campaigns.status === 'Activă') {
            counts[cc.influencer_id] = (counts[cc.influencer_id] || 0) + 1;
          }
        });
        setActiveCampaignsByInfluencer(counts);

        setLoading(false);
      } catch (err) {
        console.error('[4U Media Admin] Influencers page error:', err);
        onNav('media-login');
      }
    })();
  }, [refreshKey]);

  const filteredApps = apps.filter(app => {
    if (statusFilter !== 'Toate' && app.status !== statusFilter) return false;
    if (search) {
      const s = search.toLowerCase();
      const inName = (app.full_name || '').toLowerCase().includes(s);
      const inEmail = (app.email || '').toLowerCase().includes(s);
      const inTiktok = (app.tiktok_handle || '').toLowerCase().includes(s);
      const inBackstage = (app.backstage_id || '').toLowerCase().includes(s);
      if (!inName && !inEmail && !inTiktok && !inBackstage) return false;
    }
    return true;
  }).sort((a, b) => {
    let valA, valB;
    if (sortBy === 'campaigns_active') {
      valA = activeCampaignsByInfluencer[a.id] || 0;
      valB = activeCampaignsByInfluencer[b.id] || 0;
    } else if (sortBy === 'contract_signed') {
      valA = a.contract_signed ? 1 : 0;
      valB = b.contract_signed ? 1 : 0;
    } else {
      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 handleSort = (key) => {
    if (sortBy === key) {
      setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(key);
      setSortDir('asc');
    }
  };

  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: 'mi-spin 0.8s linear infinite' }} />
          <span style={{ color: 'var(--txt-3)', fontSize: 13 }}>Se încarcă...</span>
        </div>
        <style>{`@keyframes mi-spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  return (
    <MediaAdminLayout onNav={onNav} currentPage="media-admin-influencers" profile={profile}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 32, flexWrap: 'wrap', gap: 16 }}>
        <div>
          <h1 className="display" style={{ fontSize: 'clamp(28px, 4vw, 40px)', margin: '0 0 8px' }}>Aplicații influenceri</h1>
          <p style={{ color: 'var(--txt-2)', fontSize: 15, margin: 0 }}>
            Total: <strong style={{ color: 'var(--txt-0)' }}>{apps.length}</strong> aplicații
            {filteredApps.length !== apps.length && (<> · Afișate: <strong style={{ color: 'var(--accent-1)' }}>{filteredApps.length}</strong></>)}
          </p>
        </div>
        <button onClick={() => setShowAddDrawer(true)} className="btn btn-primary">+ Adaugă influencer</button>
      </div>

      {/* Filtre */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 24, flexWrap: 'wrap' }}>
        <input type="text" placeholder="🔍 Caută după nume, email, TikTok handle sau ID Backstage..."
          value={search} onChange={e => setSearch(e.target.value)}
          className="input" style={{ flex: 1, minWidth: 300 }} />
        <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)}
          className="input" style={{ width: 200, color: '#FFFFFF', backgroundColor: '#1a1a1a' }}>
          <option value="Toate" style={{ backgroundColor: '#1a1a1a' }}>Toate statusurile</option>
          {STATUS_OPTIONS.map(s => <option key={s} value={s} style={{ backgroundColor: '#1a1a1a' }}>{s}</option>)}
        </select>
      </div>

      {/* Tabel */}
      <div className="card-glass" style={{ padding: 0, overflow: 'hidden' }}>
        {filteredApps.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--txt-3)' }}>
            {apps.length === 0 ? 'Nicio aplicație în baza de date.' : 'Niciun rezultat care să corespundă filtrelor.'}
          </div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: 'rgba(255,255,255,.03)' }}>
                  <ThSortable sortKey="full_name" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Nume</ThSortable>
                  <ThSortable sortKey="email" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Contact</ThSortable>
                  <ThSortable sortKey="tiktok_handle" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>TikTok</ThSortable>
                  <ThSortable sortKey="tiktok_followers" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Followers</ThSortable>
                  <ThSortable sortKey="contract_signed" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Contract</ThSortable>
                  <ThSortable sortKey="campaigns_active" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Camp. active</ThSortable>
                  <ThSortable sortKey="status" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Status</ThSortable>
                  <ThSortable sortKey="assigned_to" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Alocat la</ThSortable>
                  <ThSortable sortKey="created_at" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Data aplicare</ThSortable>
                </tr>
              </thead>
              <tbody>
                {filteredApps.map(app => {
                  const assignedStaff = staffList.find(s => s.id === app.assigned_to);
                  const campCount = activeCampaignsByInfluencer[app.id] || 0;
                  return (
                    <tr key={app.id} onClick={() => setSelectedApp(app)}
                      style={{ cursor: 'pointer', borderTop: '.5px solid var(--line)', transition: 'background .15s' }}
                      onMouseEnter={e => e.currentTarget.style.background = 'rgba(82,242,15,.04)'}
                      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                      <Td><strong>{app.full_name}</strong></Td>
                      <Td><span style={{ color: 'var(--txt-2)' }}>{app.email}</span></Td>
                      <Td>{app.tiktok_handle ? '@' + app.tiktok_handle : <span style={{ color: 'var(--txt-3)' }}>—</span>}</Td>
                      <Td>{app.tiktok_followers ? app.tiktok_followers.toLocaleString('ro-RO') : '—'}</Td>
                      <Td>{app.contract_signed ? (
                        <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: 'rgba(82,242,15,.1)', color: 'var(--accent-1)', fontWeight: 500 }}>✓ Semnat</span>
                      ) : (
                        <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: 'rgba(255,255,255,.04)', color: 'var(--txt-3)', fontWeight: 500 }}>✗ Nesemnat</span>
                      )}</Td>
                      <Td>{campCount > 0 ? <strong style={{ color: 'var(--accent-1)' }}>{campCount}</strong> : <span style={{ color: 'var(--txt-3)' }}>0</span>}</Td>
                      <Td><StatusBadge status={app.status} /></Td>
                      <Td>{assignedStaff ? assignedStaff.full_name : <span style={{ color: 'var(--txt-3)' }}>—</span>}</Td>
                      <Td><span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>{new Date(app.created_at).toLocaleDateString('ro-RO')}</span></Td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Drawer cu detalii */}
      {selectedApp && (
        <InfluencerDrawer
          app={selectedApp}
          staffList={staffList}
          onClose={() => setSelectedApp(null)}
          onUpdate={() => { setRefreshKey(k => k + 1); setSelectedApp(null); }}
        />
      )}

      {showAddDrawer && (
        <InfluencerAddDrawer
          staffList={staffList}
          onClose={() => setShowAddDrawer(false)}
          onAdd={() => { setRefreshKey(k => k + 1); setShowAddDrawer(false); }}
        />
      )}
    </MediaAdminLayout>
  );
}

function ThSortable({ 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 Td({ children }) {
  return <td style={{ padding: '14px 16px', color: 'var(--txt-1)' }}>{children}</td>;
}
function StatusBadge({ status }) {
  const c = STATUS_COLORS[status] || STATUS_COLORS['În așteptare'];
  return <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: c.bg, color: c.color, fontWeight: 500 }}>{status}</span>;
}

function InfluencerDrawer({ app, staffList, onClose, onUpdate }) {
  const [status, setStatus] = useStateMI(app.status);
  const [assignedTo, setAssignedTo] = useStateMI(app.assigned_to || '');
  const [internalNotes, setInternalNotes] = useStateMI(app.internal_notes || '');
  const [backstageId, setBackstageId] = useStateMI(app.backstage_id || '');
  const [contractSigned, setContractSigned] = useStateMI(app.contract_signed || false);
  const [contractSignedAt, setContractSignedAt] = useStateMI(app.contract_signed_at || '');
  const [contractNumber, setContractNumber] = useStateMI(app.contract_number || '');
  const [contractNotes, setContractNotes] = useStateMI(app.contract_notes || '');
  const [country, setCountry] = useStateMI(app.country || '');
  const [county, setCounty] = useStateMI(app.county || '');
  const [city, setCity] = useStateMI(app.city || '');
  const [saving, setSaving] = useStateMI(false);
  const [errorMsg, setErrorMsg] = useStateMI('');

  const handleSave = async () => {
    setSaving(true);
    setErrorMsg('');
    try {
      const { error } = await window.sb.from('influencer_applications').update({
        status,
        assigned_to: assignedTo || null,
        internal_notes: internalNotes.trim() || null,
        backstage_id: backstageId.trim() || null,
        contract_signed: contractSigned,
        contract_signed_at: contractSignedAt || null,
        contract_number: contractNumber.trim() || null,
        contract_notes: contractNotes.trim() || null,
        country: country || null,
        county: county || null,
        city: city || null,
      }).eq('id', app.id);

      if (error) {
        console.error('[4U Media Admin] Update error:', error);
        if (error.code === '23505') {
          setErrorMsg('ID Backstage e deja folosit pentru alt creator.');
        } else {
          setErrorMsg('Eroare la salvare. Încearcă din nou.');
        }
        setSaving(false);
        return;
      }
      setSaving(false);
      onUpdate();
    } catch (err) {
      setErrorMsg('Conexiune eșuată. Verifică internetul.');
      setSaving(false);
    }
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.6)', backdropFilter: 'blur(4px)' }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        maxWidth: 900, 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: 24 }}>
          <h2 className="display" style={{ fontSize: 22, margin: 0 }}>Detalii aplicație</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer', padding: 4 }}>✕</button>
        </div>

        {/* Date personale (read-only) */}
        <Section title="Date personale">
          <Field label="Nume complet" value={app.full_name} />
          <Field label="Email" value={app.email} />
          <Field label="Telefon" value={app.phone} />
          <Field label="Țară" value={app.country} />
          <Field label="Județ" value={app.county} />
          <Field label="Oraș" value={app.city} />
          <Field label="Adresă" value={app.address} />
        </Section>

        {/* Platforme */}
        <Section title="Platforme">
          <PlatformRow handle={app.tiktok_handle} followers={app.tiktok_followers} label="TikTok" />
          <PlatformRow handle={app.insta_handle} followers={app.insta_followers} label="Instagram" />
          <PlatformRow handle={app.fb_handle} followers={app.fb_followers} label="Facebook" />
          <PlatformRow handle={app.yt_handle} followers={app.yt_followers} label="YouTube" />
        </Section>

        {/* Detalii colaborare */}
        <Section title="Detalii colaborare">
          {app.niches && app.niches.length > 0 && <Tags label="Niche-uri" items={app.niches} />}
          {app.collab_types && app.collab_types.length > 0 && <Tags label="Tipuri colaborare" items={app.collab_types} />}
          {app.rate_range && <Field label="Tarif" value={app.rate_range} />}
          {app.message && <Field label="Mesaj" value={app.message} multiline />}
        </Section>

        <Section title="Trimisă pe">
          <Field label="Data aplicare" value={new Date(app.created_at).toLocaleString('ro-RO')} />
          {app.terms_accepted && <Field label="Acord GDPR" value="✓ Acceptat" />}
        </Section>

        {/* SECTION CONTRACT */}
        <div style={{ marginTop: 32, padding: 20, borderRadius: 12, background: 'rgba(63,169,245,.03)', border: '1px solid rgba(63,169,245,.15)' }}>
          <h3 style={{ fontSize: 14, margin: '0 0 20px', color: '#3FA9F5' }}>📄 Contract</h3>

          <EditField label="Status contract">
            <div style={{ display: 'flex', gap: 8 }}>
              <button type="button" onClick={() => setContractSigned(true)} style={{ flex: 1, padding: '10px 14px', borderRadius: 8, border: contractSigned ? '1px solid var(--accent-1)' : '.5px solid var(--line)', background: contractSigned ? 'rgba(82,242,15,.1)' : 'transparent', color: contractSigned ? 'var(--accent-1)' : 'var(--txt-2)', fontSize: 13, cursor: 'pointer', fontWeight: 500 }}>✓ Semnat</button>
              <button type="button" onClick={() => setContractSigned(false)} style={{ flex: 1, padding: '10px 14px', borderRadius: 8, border: !contractSigned ? '1px solid #FF5A5A' : '.5px solid var(--line)', background: !contractSigned ? 'rgba(255,90,90,.08)' : 'transparent', color: !contractSigned ? '#FF5A5A' : 'var(--txt-2)', fontSize: 13, cursor: 'pointer', fontWeight: 500 }}>✗ Nesemnat</button>
            </div>
          </EditField>

          {contractSigned && (
            <>
              <EditField label="Număr contract">
                <input type="text" value={contractNumber} onChange={e => setContractNumber(e.target.value)} className="input" style={{ width: '100%' }} placeholder="ex: 4UM-2026-001" />
              </EditField>
              <EditField label="Data semnării">
                <input type="date" value={contractSignedAt} onChange={e => setContractSignedAt(e.target.value)} className="input" style={{ width: '100%', color: '#FFFFFF', backgroundColor: '#1a1a1a' }} />
              </EditField>
            </>
          )}

          <EditField label="Note contract">
            <textarea value={contractNotes} onChange={e => setContractNotes(e.target.value)} rows={3} className="input" style={{ width: '100%', resize: 'vertical', minHeight: 60, fontFamily: 'inherit' }} placeholder="Observații despre contract..." />
          </EditField>
        </div>

        {/* SECTION EDITABILĂ */}
        <div style={{ marginTop: 32, padding: 20, borderRadius: 12, background: 'rgba(82,242,15,.03)', border: '1px solid rgba(82,242,15,.15)' }}>
          <h3 style={{ fontSize: 14, margin: '0 0 20px', color: 'var(--accent-1)' }}>⚙️ Management intern</h3>

          <EditField label="Status">
            <select value={status} onChange={e => setStatus(e.target.value)} className="input"
              style={{ width: '100%', color: '#FFFFFF', backgroundColor: '#1a1a1a' }}>
              {STATUS_OPTIONS.map(s => <option key={s} value={s} style={{ backgroundColor: '#1a1a1a' }}>{s}</option>)}
            </select>
          </EditField>

          <EditField label="Alocat la">
            <select value={assignedTo} onChange={e => setAssignedTo(e.target.value)} className="input"
              style={{ width: '100%', color: '#FFFFFF', backgroundColor: '#1a1a1a' }}>
              <option value="" style={{ backgroundColor: '#1a1a1a' }}>— Nealocat —</option>
              {staffList.map(s => <option key={s.id} value={s.id} style={{ backgroundColor: '#1a1a1a' }}>{s.full_name}</option>)}
            </select>
          </EditField>

          <EditField label="Țară / Județ / Oraș">
            <window.CountryCascade
              country={country}
              county={county}
              city={city}
              setCountry={setCountry}
              setCounty={setCounty}
              setCity={setCity}
              required={false}
              showLabels={false}
            />
          </EditField>

          <EditField label="ID Backstage (TikTok)">
            <input type="text" value={backstageId} onChange={e => setBackstageId(e.target.value)}
              placeholder="Completează manual după acceptare"
              className="input" style={{ width: '100%' }} />
          </EditField>

          <EditField label="Note interne (vizibile doar staff-ului)">
            <textarea value={internalNotes} onChange={e => setInternalNotes(e.target.value)}
              rows={4} placeholder="Observații, follow-up, etc."
              className="input" style={{ width: '100%', resize: 'vertical', minHeight: 80, fontFamily: 'inherit', lineHeight: 1.5 }} />
          </EditField>

          {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>
      </div>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div style={{ marginBottom: 28 }}>
      <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14 }}>{title.toUpperCase()}</h3>
      {children}
    </div>
  );
}
function Field({ label, value, multiline }) {
  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)', whiteSpace: multiline ? 'pre-wrap' : 'normal', wordBreak: 'break-word' }}>{value}</div>
    </div>
  );
}
function PlatformRow({ handle, followers, label }) {
  if (!handle && !followers) return null;
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: '.5px solid rgba(255,255,255,.04)' }}>
      <div>
        <div style={{ fontSize: 12, color: 'var(--txt-3)' }}>{label}</div>
        <div style={{ fontSize: 13, color: 'var(--txt-0)' }}>{handle ? '@' + handle : '—'}</div>
      </div>
      {followers && <div style={{ fontSize: 13, color: 'var(--accent-1)', fontWeight: 600 }}>{followers.toLocaleString('ro-RO')} followers</div>}
    </div>
  );
}
function Tags({ label, items }) {
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 6 }}>{label}</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {items.map((tag, i) => (
          <span key={i} style={{ fontSize: 11, padding: '4px 10px', borderRadius: 5, background: 'rgba(82,242,15,.08)', border: '.5px solid rgba(82,242,15,.2)', color: 'var(--accent-1)' }}>{tag}</span>
        ))}
      </div>
    </div>
  );
}
function EditField({ label, children }) {
  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}
    </div>
  );
}

const NICHES_OPTIONS = ['Beauty', 'Fashion', 'Lifestyle', 'Gaming', 'Music', 'Talk Show', 'Comedy', 'Food', 'Travel', 'Fitness', 'Education', 'Tech', 'Other'];
const COLLAB_TYPES_OPTIONS = ['TikTok Live', 'Video TikTok', 'Story Instagram', 'Reel Instagram', 'Post Instagram', 'YouTube', 'Mix'];

function InfluencerAddDrawer({ staffList, onClose, onAdd }) {
  const [fullName, setFullName] = useStateMI('');
  const [email, setEmail] = useStateMI('');
  const [phone, setPhone] = useStateMI('');
  const [address, setAddress] = useStateMI('');
  const [country, setCountry] = useStateMI('România');
  const [county, setCounty] = useStateMI('');
  const [city, setCity] = useStateMI('');
  const [tiktokHandle, setTiktokHandle] = useStateMI('');
  const [tiktokFollowers, setTiktokFollowers] = useStateMI('');
  const [instaHandle, setInstaHandle] = useStateMI('');
  const [instaFollowers, setInstaFollowers] = useStateMI('');
  const [fbHandle, setFbHandle] = useStateMI('');
  const [fbFollowers, setFbFollowers] = useStateMI('');
  const [ytHandle, setYtHandle] = useStateMI('');
  const [ytFollowers, setYtFollowers] = useStateMI('');
  const [niches, setNiches] = useStateMI([]);
  const [collabTypes, setCollabTypes] = useStateMI([]);
  const [rateRange, setRateRange] = useStateMI('');
  const [message, setMessage] = useStateMI('');
  const [saving, setSaving] = useStateMI(false);
  const [errorMsg, setErrorMsg] = useStateMI('');

  const toggleArrayValue = (arr, setArr, value) => {
    setArr(arr.includes(value) ? arr.filter(x => x !== value) : [...arr, value]);
  };

  const validateAndSave = async () => {
    setErrorMsg('');

    const required = [
      [fullName.trim(), 'Nume complet'],
      [email.trim(), 'Email'],
      [phone.trim(), 'Telefon'],
      [country.trim(), 'Țară'],
      [address.trim(), 'Adresă'],
      [tiktokHandle.trim(), 'TikTok handle'],
      [tiktokFollowers, 'TikTok followers'],
      [rateRange.trim(), 'Tarif'],
    ];
    for (const [val, label] of required) {
      if (!val) { setErrorMsg('Câmpul "' + label + '" e obligatoriu.'); return; }
    }
    if (country === 'România' && !county.trim()) { setErrorMsg('Selectează județul.'); return; }
    if (country === 'România' && !city.trim()) { setErrorMsg('Selectează orașul.'); return; }
    if (niches.length === 0) { setErrorMsg('Selectează minim 1 niche.'); return; }
    if (collabTypes.length === 0) { setErrorMsg('Selectează minim 1 tip colaborare.'); return; }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email.trim())) { setErrorMsg('Email-ul nu pare valid.'); return; }
    const phoneRegex = /^\+?[\d\s()-]{8,20}$/;
    if (!phoneRegex.test(phone.trim())) { setErrorMsg('Telefonul nu pare valid.'); return; }

    if ((instaHandle.trim() && !instaFollowers) || (!instaHandle.trim() && instaFollowers)) {
      setErrorMsg('Pentru Instagram, completează AMBELE: handle și followers, sau lasă AMBELE goale.'); return;
    }
    if ((fbHandle.trim() && !fbFollowers) || (!fbHandle.trim() && fbFollowers)) {
      setErrorMsg('Pentru Facebook, completează AMBELE: handle și followers, sau lasă AMBELE goale.'); return;
    }
    if ((ytHandle.trim() && !ytFollowers) || (!ytHandle.trim() && ytFollowers)) {
      setErrorMsg('Pentru YouTube, completează AMBELE: handle și followers, sau lasă AMBELE goale.'); return;
    }

    setSaving(true);
    try {
      const { error } = await window.sb.from('influencer_applications').insert({
        full_name: fullName.trim(),
        email: email.trim().toLowerCase(),
        phone: phone.trim(),
        country: country.trim() || null,
        county: county.trim() || null,
        city: city.trim() || null,
        address: address.trim(),
        tiktok_handle: tiktokHandle.trim().replace(/^@/, ''),
        tiktok_followers: parseInt(tiktokFollowers) || 0,
        insta_handle: instaHandle.trim() ? instaHandle.trim().replace(/^@/, '') : null,
        insta_followers: instaFollowers ? parseInt(instaFollowers) : null,
        fb_handle: fbHandle.trim() ? fbHandle.trim().replace(/^@/, '') : null,
        fb_followers: fbFollowers ? parseInt(fbFollowers) : null,
        yt_handle: ytHandle.trim() ? ytHandle.trim().replace(/^@/, '') : null,
        yt_followers: ytFollowers ? parseInt(ytFollowers) : null,
        niches: niches,
        collab_types: collabTypes,
        rate_range: rateRange.trim(),
        message: message.trim() || null,
        terms_accepted: true,
        status: 'Acceptat',
        added_manually: true,
      });
      if (error) {
        setErrorMsg('Eroare la salvare: ' + error.message);
        setSaving(false);
        return;
      }
      setSaving(false);
      onAdd();
    } catch (err) {
      setErrorMsg('Conexiune eșuată. Încearcă din nou.');
      setSaving(false);
    }
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.6)', backdropFilter: 'blur(4px)' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: 900, 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: 16 }}>
          <h2 className="display" style={{ fontSize: 22, margin: 0 }}>Adaugă influencer manual</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer', padding: 4 }}>✕</button>
        </div>
        <p style={{ fontSize: 13, color: 'var(--txt-2)', marginBottom: 24 }}>Folosește la apel telefonic sau întâlnire. Status default: <strong style={{ color: 'var(--accent-1)' }}>Acceptat</strong>.</p>

        <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14, marginTop: 24 }}>DATE PERSONALE</h3>
        <EditField label="Nume complet *"><input type="text" value={fullName} onChange={e => setFullName(e.target.value)} className="input" style={{ width: '100%' }} /></EditField>
        <EditField label="Email *"><input type="email" value={email} onChange={e => setEmail(e.target.value)} className="input" style={{ width: '100%' }} /></EditField>
        <EditField label="Telefon *"><input type="tel" value={phone} onChange={e => setPhone(e.target.value)} className="input" style={{ width: '100%' }} placeholder="+40712345678" /></EditField>
        <EditField label="Țară / Județ / Oraș *">
          <window.CountryCascade
            country={country} county={county} city={city}
            setCountry={setCountry} setCounty={setCounty} setCity={setCity}
            required={true} showLabels={false}
          />
        </EditField>
        <EditField label="Adresă *"><input type="text" value={address} onChange={e => setAddress(e.target.value)} className="input" style={{ width: '100%' }} placeholder="Stradă, număr, bloc, scară, ap." /></EditField>

        <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14, marginTop: 32 }}>TIKTOK (OBLIGATORIU)</h3>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
          <EditField label="Handle *"><input type="text" value={tiktokHandle} onChange={e => setTiktokHandle(e.target.value)} className="input" style={{ width: '100%' }} placeholder="username" /></EditField>
          <EditField label="Followers *"><input type="number" min="0" value={tiktokFollowers} onChange={e => setTiktokFollowers(e.target.value)} className="input" style={{ width: '100%' }} /></EditField>
        </div>

        <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14, marginTop: 32 }}>ALTE PLATFORME (OPȚIONAL)</h3>
        <p style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 12 }}>Dacă influencerul are cont, completează AMBELE câmpuri pentru platformă. Dacă nu, lasă AMBELE goale.</p>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
          <EditField label="Instagram handle"><input type="text" value={instaHandle} onChange={e => setInstaHandle(e.target.value)} className="input" style={{ width: '100%' }} /></EditField>
          <EditField label="Instagram followers"><input type="number" min="0" value={instaFollowers} onChange={e => setInstaFollowers(e.target.value)} className="input" style={{ width: '100%' }} /></EditField>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
          <EditField label="Facebook handle"><input type="text" value={fbHandle} onChange={e => setFbHandle(e.target.value)} className="input" style={{ width: '100%' }} /></EditField>
          <EditField label="Facebook followers"><input type="number" min="0" value={fbFollowers} onChange={e => setFbFollowers(e.target.value)} className="input" style={{ width: '100%' }} /></EditField>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
          <EditField label="YouTube handle"><input type="text" value={ytHandle} onChange={e => setYtHandle(e.target.value)} className="input" style={{ width: '100%' }} /></EditField>
          <EditField label="YouTube followers"><input type="number" min="0" value={ytFollowers} onChange={e => setYtFollowers(e.target.value)} className="input" style={{ width: '100%' }} /></EditField>
        </div>

        <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14, marginTop: 32 }}>DETALII COLABORARE</h3>
        <EditField label="Niche-uri * (minim 1)">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {NICHES_OPTIONS.map(n => (
              <button key={n} type="button" onClick={() => toggleArrayValue(niches, setNiches, n)} style={{
                padding: '6px 12px', borderRadius: 6, fontSize: 12, cursor: 'pointer',
                border: niches.includes(n) ? '1px solid var(--accent-1)' : '.5px solid var(--line)',
                background: niches.includes(n) ? 'rgba(82,242,15,.1)' : 'transparent',
                color: niches.includes(n) ? 'var(--accent-1)' : 'var(--txt-2)'
              }}>{n}</button>
            ))}
          </div>
        </EditField>
        <EditField label="Tipuri colaborare * (minim 1)">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {COLLAB_TYPES_OPTIONS.map(t => (
              <button key={t} type="button" onClick={() => toggleArrayValue(collabTypes, setCollabTypes, t)} style={{
                padding: '6px 12px', borderRadius: 6, fontSize: 12, cursor: 'pointer',
                border: collabTypes.includes(t) ? '1px solid var(--accent-1)' : '.5px solid var(--line)',
                background: collabTypes.includes(t) ? 'rgba(82,242,15,.1)' : 'transparent',
                color: collabTypes.includes(t) ? 'var(--accent-1)' : 'var(--txt-2)'
              }}>{t}</button>
            ))}
          </div>
        </EditField>
        <EditField label="Tarif *"><input type="text" value={rateRange} onChange={e => setRateRange(e.target.value)} className="input" style={{ width: '100%' }} placeholder="ex: 500-1000 RON / postare" /></EditField>

        <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14, marginTop: 32 }}>NOTE (OPȚIONAL)</h3>
        <EditField label="Detalii despre creator">
          <textarea value={message} onChange={e => setMessage(e.target.value)} rows={4} className="input" style={{ width: '100%', resize: 'vertical', minHeight: 80, fontFamily: 'inherit' }} placeholder="A mai colaborat cu branduri? Ce campanii? Observații..." />
        </EditField>

        {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={validateAndSave} disabled={saving} className="btn btn-primary" style={{ width: '100%', marginTop: 20, opacity: saving ? 0.6 : 1 }}>
          {saving ? 'Se adaugă...' : 'Adaugă în baza de date'}
        </button>
      </div>
    </div>
  );
}

window.MediaAdminInfluencers = MediaAdminInfluencers;
