const { useState: useStateMB, useEffect: useEffectMB } = React;

const STATUS_OPTIONS_B = ['Nou', 'În discuție', 'Propunere trimisă', 'Câștigat', 'Pierdut'];
const STATUS_COLORS_B = {
  'Nou': { bg: 'rgba(82,242,15,.1)', color: 'var(--accent-1)' },
  'În discuție': { bg: 'rgba(63,169,245,.1)', color: '#3FA9F5' },
  'Propunere trimisă': { bg: 'rgba(255,215,0,.1)', color: '#FFD700' },
  'Câștigat': { bg: 'rgba(82,242,15,.15)', color: 'var(--accent-1)' },
  'Pierdut': { bg: 'rgba(255,90,90,.1)', color: '#FF5A5A' },
};

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

  useEffectMB(() => {
    (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);

        const [{ data: appsData }, { data: staff }] = await Promise.all([
          window.sb.from('brand_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 || []);

        const { data: campsData } = await window.sb
          .from('campaigns')
          .select('id, brand_id, status')
          .eq('status', 'Activă');
        const counts = {};
        (campsData || []).forEach(c => {
          if (c.brand_id) counts[c.brand_id] = (counts[c.brand_id] || 0) + 1;
        });
        setActiveCampaignsByBrand(counts);

        setLoading(false);
      } catch (err) {
        console.error('[4U Media Admin] Brands 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 inCompany = (app.company || '').toLowerCase().includes(s);
      const inContact = (app.contact_name || '').toLowerCase().includes(s);
      const inEmail = (app.email || '').toLowerCase().includes(s);
      const inBrand = (app.brand || '').toLowerCase().includes(s);
      const inIndustry = (app.industry || '').toLowerCase().includes(s);
      if (!inCompany && !inContact && !inEmail && !inBrand && !inIndustry) return false;
    }
    return true;
  }).sort((a, b) => {
    let valA, valB;
    if (sortBy === 'campaigns_active') {
      valA = activeCampaignsByBrand[a.id] || 0;
      valB = activeCampaignsByBrand[b.id] || 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: 'mb-spin 0.8s linear infinite' }} />
          <span style={{ color: 'var(--txt-3)', fontSize: 13 }}>Se încarcă...</span>
        </div>
        <style>{`@keyframes mb-spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  return (
    <MediaAdminLayout onNav={onNav} currentPage="media-admin-brands" 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 branduri</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ă brand</button>
      </div>

      {/* Filtre */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 24, flexWrap: 'wrap' }}>
        <input type="text" placeholder="🔍 Caută după companie, contact, email, brand sau industrie..."
          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: 220, color: '#FFFFFF', backgroundColor: '#1a1a1a' }}>
          <option value="Toate" style={{ backgroundColor: '#1a1a1a' }}>Toate statusurile</option>
          {STATUS_OPTIONS_B.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="company" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Companie</ThSortable>
                  <ThSortable sortKey="contact_name" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Contact</ThSortable>
                  <ThSortable sortKey="email" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Email</ThSortable>
                  <ThSortable sortKey="industry" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Industrie</ThSortable>
                  <ThSortable sortKey="brand" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Campanie</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 campaign = app.brand || (app.campaign_types && app.campaign_types[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'}>
                      <TdB><strong>{app.company}</strong></TdB>
                      <TdB>{app.contact_name || <span style={{ color: 'var(--txt-3)' }}>—</span>}</TdB>
                      <TdB><span style={{ color: 'var(--txt-2)' }}>{app.email}</span></TdB>
                      <TdB>{app.industry || <span style={{ color: 'var(--txt-3)' }}>—</span>}</TdB>
                      <TdB>{campaign || <span style={{ color: 'var(--txt-3)' }}>—</span>}</TdB>
                      <TdB>{(activeCampaignsByBrand[app.id] || 0) > 0 ? <strong style={{ color: 'var(--accent-1)' }}>{activeCampaignsByBrand[app.id]}</strong> : <span style={{ color: 'var(--txt-3)' }}>0</span>}</TdB>
                      <TdB><StatusBadgeB status={app.status} /></TdB>
                      <TdB>{assignedStaff ? assignedStaff.full_name : <span style={{ color: 'var(--txt-3)' }}>—</span>}</TdB>
                      <TdB><span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>{new Date(app.created_at).toLocaleDateString('ro-RO')}</span></TdB>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

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

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

function ThB({ children }) {
  return <th style={{ textAlign: 'left', padding: '14px 16px', fontWeight: 600, fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{children}</th>;
}
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 TdB({ children }) {
  return <td style={{ padding: '14px 16px', color: 'var(--txt-1)' }}>{children}</td>;
}
function StatusBadgeB({ status }) {
  const c = STATUS_COLORS_B[status] || { bg: 'rgba(255,255,255,.05)', color: 'var(--txt-2)' };
  return <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: c.bg, color: c.color, fontWeight: 500 }}>{status}</span>;
}

function BrandDrawer({ app, staffList, onClose, onUpdate }) {
  const [status, setStatus] = useStateMB(app.status);
  const [assignedTo, setAssignedTo] = useStateMB(app.assigned_to || '');
  const [internalNotes, setInternalNotes] = useStateMB(app.internal_notes || '');
  const [country, setCountry] = useStateMB(app.country || '');
  const [county, setCounty] = useStateMB(app.county || '');
  const [city, setCity] = useStateMB(app.city || '');
  const [saving, setSaving] = useStateMB(false);
  const [errorMsg, setErrorMsg] = useStateMB('');

  const handleSave = async () => {
    setSaving(true);
    setErrorMsg('');
    try {
      const { error } = await window.sb.from('brand_applications').update({
        status,
        assigned_to: assignedTo || null,
        internal_notes: internalNotes.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);
        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>

        <SectionB title="Date companie">
          <FieldB label="Companie" value={app.company} />
          <FieldB label="CUI" value={app.cui} />
          <FieldB label="Persoană contact" value={app.contact_name} />
          <FieldB label="Funcție" value={app.contact_role} />
          <FieldB label="Email" value={app.email} />
          <FieldB label="Telefon" value={app.phone} />
          <FieldB label="Website" value={app.website} />
          <FieldB label="Industrie" value={app.industry} />
          <FieldB label="Țară" value={app.country} />
          <FieldB label="Județ" value={app.county} />
          <FieldB label="Oraș" value={app.city} />
        </SectionB>

        <SectionB title="Detalii campanie">
          <FieldB label="Brand promovat" value={app.brand} />
          {app.campaign_types && app.campaign_types.length > 0 && <TagsB label="Tipuri campanie" items={app.campaign_types} />}
          {app.target_ages && app.target_ages.length > 0 && <TagsB label="Categorii vârstă" items={app.target_ages} />}
          {app.categories && app.categories.length > 0 && <TagsB label="Categorii" items={app.categories} />}
          {app.countries && app.countries.length > 0 && <TagsB label="Țări" items={app.countries} />}
          <FieldB label="Obiective" value={app.goals} multiline />
        </SectionB>

        <SectionB title="Buget & informații">
          <FieldB label="Buget aproximativ" value={app.budget} />
          <FieldB label="Cum a aflat de noi" value={app.source} />
          <FieldB label="Mesaj liber" value={app.message} multiline />
        </SectionB>

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

        {/* 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>

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

          <EditFieldB 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>
          </EditFieldB>

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

          <EditFieldB 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 }} />
          </EditFieldB>

          {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 SectionB({ 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 FieldB({ 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 TagsB({ 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 EditFieldB({ 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 CAMPAIGN_TYPES_BRAND_OPTIONS = ['TikTok Live', 'Video TikTok', 'Story Instagram', 'Reel Instagram', 'Post Instagram', 'YouTube', 'Mix'];
const TARGET_AGES_OPTIONS = ['13-17', '18-24', '25-34', '35-44', '45-54', '55+'];
const CATEGORIES_BRAND_OPTIONS = ['Beauty', 'Fashion', 'Lifestyle', 'Gaming', 'Music', 'Food', 'Travel', 'Fitness', 'Education', 'Tech', 'Auto', 'Finance', 'Other'];
const COUNTRIES_OPTIONS = ['România', 'Republica Moldova', 'Bulgaria', 'Ungaria', 'Polonia', 'Cehia', 'Serbia', 'Italia', 'Germania', 'Franța', 'Spania', 'UK', 'USA', 'Altele'];

function BrandAddDrawer({ staffList, onClose, onAdd }) {
  const [company, setCompany] = useStateMB('');
  const [cui, setCui] = useStateMB('');
  const [contactName, setContactName] = useStateMB('');
  const [contactRole, setContactRole] = useStateMB('');
  const [email, setEmail] = useStateMB('');
  const [phone, setPhone] = useStateMB('');
  const [website, setWebsite] = useStateMB('');
  const [industry, setIndustry] = useStateMB('');
  const [country, setCountry] = useStateMB('România');
  const [county, setCounty] = useStateMB('');
  const [city, setCity] = useStateMB('');
  const [brand, setBrand] = useStateMB('');
  const [campaignTypes, setCampaignTypes] = useStateMB([]);
  const [targetAges, setTargetAges] = useStateMB([]);
  const [categories, setCategories] = useStateMB([]);
  const [countries, setCountries] = useStateMB([]);
  const [goals, setGoals] = useStateMB('');
  const [budget, setBudget] = useStateMB('');
  const [source, setSource] = useStateMB('');
  const [message, setMessage] = useStateMB('');
  const [saving, setSaving] = useStateMB(false);
  const [errorMsg, setErrorMsg] = useStateMB('');

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

  const validateAndSave = async () => {
    setErrorMsg('');
    const required = [
      [company.trim(), 'Companie'], [cui.trim(), 'CUI'],
      [contactName.trim(), 'Persoană contact'], [contactRole.trim(), 'Funcție'],
      [email.trim(), 'Email'], [phone.trim(), 'Telefon'],
      [country.trim(), 'Țară'],
      [industry.trim(), 'Industrie'], [brand.trim(), 'Brand promovat'],
      [goals.trim(), 'Obiective'], [budget.trim(), 'Buget'], [source.trim(), 'Sursă'],
    ];
    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 (campaignTypes.length === 0) { setErrorMsg('Selectează minim 1 tip campanie.'); return; }
    if (targetAges.length === 0) { setErrorMsg('Selectează minim 1 categorie vârstă.'); return; }
    if (categories.length === 0) { setErrorMsg('Selectează minim 1 categorie.'); return; }
    if (countries.length === 0) { setErrorMsg('Selectează minim 1 țară.'); return; }

    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('brand_applications').insert({
        company: company.trim(), cui: cui.trim(),
        contact_name: contactName.trim(), contact_role: contactRole.trim(),
        email: email.trim().toLowerCase(), phone: phone.trim(),
        website: website.trim() || null, industry: industry.trim(),
        country: country.trim() || null,
        county: county.trim() || null,
        city: city.trim() || null,
        brand: brand.trim(),
        campaign_types: campaignTypes, target_ages: targetAges,
        categories: categories, countries: countries,
        goals: goals.trim(), budget: budget.trim(), source: source.trim(),
        message: message.trim() || null,
        terms_accepted: true,
        status: 'În discuție',
        added_manually: true,
      });
      if (error) { setErrorMsg('Eroare: ' + error.message); setSaving(false); return; }
      setSaving(false);
      onAdd();
    } catch (err) { setErrorMsg('Conexiune eșuată.'); 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ă brand 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 }}>Status default: <strong style={{ color: '#3FA9F5' }}>În discuție</strong>.</p>

        <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14, marginTop: 24 }}>DATE COMPANIE</h3>
        <EditFieldB label="Companie *"><input type="text" value={company} onChange={e => setCompany(e.target.value)} className="input" style={{ width: '100%' }} /></EditFieldB>
        <EditFieldB label="CUI *"><input type="text" value={cui} onChange={e => setCui(e.target.value)} className="input" style={{ width: '100%' }} placeholder="RO12345678" /></EditFieldB>
        <EditFieldB label="Persoană contact *"><input type="text" value={contactName} onChange={e => setContactName(e.target.value)} className="input" style={{ width: '100%' }} /></EditFieldB>
        <EditFieldB label="Funcție *"><input type="text" value={contactRole} onChange={e => setContactRole(e.target.value)} className="input" style={{ width: '100%' }} placeholder="ex: Marketing Manager" /></EditFieldB>
        <EditFieldB label="Email *"><input type="email" value={email} onChange={e => setEmail(e.target.value)} className="input" style={{ width: '100%' }} /></EditFieldB>
        <EditFieldB label="Telefon *"><input type="tel" value={phone} onChange={e => setPhone(e.target.value)} className="input" style={{ width: '100%' }} /></EditFieldB>
        <EditFieldB label="Website (opțional)"><input type="url" value={website} onChange={e => setWebsite(e.target.value)} className="input" style={{ width: '100%' }} placeholder="https://..." /></EditFieldB>
        <EditFieldB label="Industrie *"><input type="text" value={industry} onChange={e => setIndustry(e.target.value)} className="input" style={{ width: '100%' }} /></EditFieldB>
        <EditFieldB label="Sediu — Țară / Județ / Oraș *">
          <window.CountryCascade
            country={country} county={county} city={city}
            setCountry={setCountry} setCounty={setCounty} setCity={setCity}
            required={true} showLabels={false}
          />
        </EditFieldB>

        <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14, marginTop: 32 }}>DETALII CAMPANIE</h3>
        <EditFieldB label="Brand promovat *"><input type="text" value={brand} onChange={e => setBrand(e.target.value)} className="input" style={{ width: '100%' }} /></EditFieldB>
        <EditFieldB label="Tipuri campanie * (minim 1)">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {CAMPAIGN_TYPES_BRAND_OPTIONS.map(t => (
              <button key={t} type="button" onClick={() => toggleArrayValue(campaignTypes, setCampaignTypes, t)} style={{
                padding: '6px 12px', borderRadius: 6, fontSize: 12, cursor: 'pointer',
                border: campaignTypes.includes(t) ? '1px solid var(--accent-1)' : '.5px solid var(--line)',
                background: campaignTypes.includes(t) ? 'rgba(82,242,15,.1)' : 'transparent',
                color: campaignTypes.includes(t) ? 'var(--accent-1)' : 'var(--txt-2)'
              }}>{t}</button>
            ))}
          </div>
        </EditFieldB>
        <EditFieldB label="Categorii vârstă target * (minim 1)">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {TARGET_AGES_OPTIONS.map(a => (
              <button key={a} type="button" onClick={() => toggleArrayValue(targetAges, setTargetAges, a)} style={{
                padding: '6px 12px', borderRadius: 6, fontSize: 12, cursor: 'pointer',
                border: targetAges.includes(a) ? '1px solid var(--accent-1)' : '.5px solid var(--line)',
                background: targetAges.includes(a) ? 'rgba(82,242,15,.1)' : 'transparent',
                color: targetAges.includes(a) ? 'var(--accent-1)' : 'var(--txt-2)'
              }}>{a}</button>
            ))}
          </div>
        </EditFieldB>
        <EditFieldB label="Categorii * (minim 1)">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {CATEGORIES_BRAND_OPTIONS.map(c => (
              <button key={c} type="button" onClick={() => toggleArrayValue(categories, setCategories, c)} style={{
                padding: '6px 12px', borderRadius: 6, fontSize: 12, cursor: 'pointer',
                border: categories.includes(c) ? '1px solid var(--accent-1)' : '.5px solid var(--line)',
                background: categories.includes(c) ? 'rgba(82,242,15,.1)' : 'transparent',
                color: categories.includes(c) ? 'var(--accent-1)' : 'var(--txt-2)'
              }}>{c}</button>
            ))}
          </div>
        </EditFieldB>
        <EditFieldB label="Țări * (minim 1)">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {COUNTRIES_OPTIONS.map(c => (
              <button key={c} type="button" onClick={() => toggleArrayValue(countries, setCountries, c)} style={{
                padding: '6px 12px', borderRadius: 6, fontSize: 12, cursor: 'pointer',
                border: countries.includes(c) ? '1px solid var(--accent-1)' : '.5px solid var(--line)',
                background: countries.includes(c) ? 'rgba(82,242,15,.1)' : 'transparent',
                color: countries.includes(c) ? 'var(--accent-1)' : 'var(--txt-2)'
              }}>{c}</button>
            ))}
          </div>
        </EditFieldB>
        <EditFieldB label="Obiective *">
          <textarea value={goals} onChange={e => setGoals(e.target.value)} rows={3} className="input" style={{ width: '100%', resize: 'vertical', minHeight: 60, fontFamily: 'inherit' }} placeholder="Ce vor să obțină prin campanie..." />
        </EditFieldB>

        <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14, marginTop: 32 }}>BUGET & ALTE INFO</h3>
        <EditFieldB label="Buget aproximativ *"><input type="text" value={budget} onChange={e => setBudget(e.target.value)} className="input" style={{ width: '100%' }} placeholder="ex: 5000-10000 RON" /></EditFieldB>
        <EditFieldB label="Cum a aflat de noi / Sursă *"><input type="text" value={source} onChange={e => setSource(e.target.value)} className="input" style={{ width: '100%' }} placeholder="ex: WhatsApp, recomandare, Google" /></EditFieldB>
        <EditFieldB label="Note interne (opțional)">
          <textarea value={message} onChange={e => setMessage(e.target.value)} rows={3} className="input" style={{ width: '100%', resize: 'vertical', minHeight: 60, fontFamily: 'inherit' }} placeholder="Observații despre brand..." />
        </EditFieldB>

        {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.MediaAdminBrands = MediaAdminBrands;
