// media-admin-contracts.jsx — contracte generate din sablon si semnate online.
//
// Ordinea semnarii e intentionata: contractul pleaca NESEMNAT de noi, clientul
// semneaza primul, si abia dupa aceea semnam noi din panou. Altfel am da cuiva
// un document semnat de o singura parte, pe care il poate folosi fara sa se oblige.

const { useState: useStateCT, useEffect: useEffectCT, useRef: useRefCT } = React;

// Adresa paginii publice de semnare. Traieste pe site-ul principal, nu pe panou:
// un om caruia i se cere sa semneze se uita la domeniu, iar 4uagency.ro e cel pe
// care il stie deja. Daca vreodata se muta, se schimba doar linia asta.
const SIGN_BASE = 'https://4uagency.ro/semnare.html';

const CONTRACT_STATUS_COLORS = {
  'Draft':            { bg: 'rgba(255,255,255,.05)', color: 'var(--txt-2)' },
  'Trimis':           { bg: 'rgba(255,215,0,.12)', color: 'var(--accent-2)' },
  'Semnat de client': { bg: 'rgba(63,169,245,.12)', color: '#3FA9F5' },
  'Semnat':           { bg: 'rgba(82,242,15,.15)', color: 'var(--accent-1)' },
  'Anulat':           { bg: 'rgba(255,90,90,.1)', color: '#FF5A5A' },
};

// Locurile goale din sablon, in ordinea in care apar, fara duplicate.
function extractPlaceholders(body) {
  const out = [];
  const re = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
  let m;
  while ((m = re.exec(body || '')) !== null) {
    if (out.indexOf(m[1]) === -1) out.push(m[1]);
  }
  return out;
}

function fillTemplate(body, values) {
  return (body || '').replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (full, key) => {
    const v = values[key];
    return (v === undefined || v === null || v === '') ? full : v;
  });
}

function prettyLabel(key) {
  return key.replace(/_/g, ' ').replace(/^./, c => c.toUpperCase());
}

// Ce stim deja despre cealalta parte, ca sa nu se scrie de mana.
// Cheile sunt aceleasi cu locurile goale din sabloanele livrate; daca va scrieti
// sablonul cu alte nume, campurile apar goale si se completeaza manual.
function autoFill({ type, brand, influencer, campaign }) {
  const today = new Date().toLocaleDateString('ro-RO');
  const v = { data_contract: today };

  if (campaign) {
    v.campanie = campaign.name || '';
    if (campaign.start_date || campaign.end_date) {
      const f = (d) => d ? new Date(d + 'T00:00:00').toLocaleDateString('ro-RO') : '...';
      v.perioada = f(campaign.start_date) + ' – ' + f(campaign.end_date);
    }
    if (campaign.budget_total) v.valoare = String(campaign.budget_total);
  }

  if (type === 'brand' && brand) {
    v.companie = brand.company || '';
    v.cui_client = brand.cui || '';
    v.reprezentant_client = brand.contact_name || '';
    v.email_client = brand.email || '';
    v.telefon_client = brand.phone || '';
    v.sediu_client = [brand.city, brand.county, brand.country].filter(Boolean).join(', ');
  }

  if (type === 'creator' && influencer) {
    v.nume_creator = influencer.full_name || '';
    v.handle = influencer.tiktok_handle ? '@' + influencer.tiktok_handle : '';
    v.email_creator = influencer.email || '';
    v.telefon_creator = influencer.phone || '';
    v.adresa_creator = influencer.address || [influencer.city, influencer.county, influencer.country].filter(Boolean).join(', ');
  }

  return v;
}

function MediaAdminContracts({ onNav }) {
  const [profile, setProfile] = useStateCT(null);
  const [loading, setLoading] = useStateCT(true);
  const [tab, setTab] = useStateCT('contracte');
  const [contracts, setContracts] = useStateCT([]);
  const [templates, setTemplates] = useStateCT([]);
  const [brands, setBrands] = useStateCT([]);
  const [influencers, setInfluencers] = useStateCT([]);
  const [campaigns, setCampaigns] = useStateCT([]);
  const [staffList, setStaffList] = useStateCT([]);
  const [search, setSearch] = useStateCT('');
  const [statusFilter, setStatusFilter] = useStateCT('Toate');
  const [refreshKey, setRefreshKey] = useStateCT(0);
  const [selected, setSelected] = useStateCT(null);
  const [showCreate, setShowCreate] = useStateCT(false);

  useEffectCT(() => {
    (async () => {
      const { data: { session } } = await window.sb.auth.getSession();
      if (!session) { onNav('media-login'); return; }
      const { data: prof } = await window.sb.from('staff_profiles').select('*').eq('id', session.user.id).single();
      if (!prof || !prof.is_active) { onNav('media-login'); return; }
      setProfile(prof);

      const [{ data: ct }, { data: tpl }, { data: br }, { data: inf }, { data: cmp }, { data: st }] = await Promise.all([
        window.sb.from('contracts').select('*').order('created_at', { ascending: false }),
        window.sb.from('contract_templates').select('*').order('type'),
        window.sb.from('brand_applications').select('id, company, brand, cui, contact_name, email, phone, city, county, country').order('company'),
        window.sb.from('influencer_applications').select('id, full_name, email, phone, tiktok_handle, address, city, county, country').order('full_name'),
        window.sb.from('campaigns').select('id, name, start_date, end_date, budget_total').order('created_at', { ascending: false }),
        window.sb.from('staff_profiles').select('id, full_name').eq('is_active', true).order('full_name'),
      ]);

      setContracts(ct || []);
      setTemplates(tpl || []);
      setBrands(br || []);
      setInfluencers(inf || []);
      setCampaigns(cmp || []);
      setStaffList(st || []);
      setLoading(false);
    })();
  }, [refreshKey]);

  const refresh = () => setRefreshKey(k => k + 1);

  const filtered = contracts.filter(c => {
    if (statusFilter !== 'Toate' && c.status !== statusFilter) return false;
    if (search) {
      const s = search.toLowerCase();
      if (!(c.title || '').toLowerCase().includes(s) && !(c.signer_name || '').toLowerCase().includes(s)) return false;
    }
    return true;
  });

  const asteaptaSemnaturaNoastra = contracts.filter(c => c.status === 'Semnat de client').length;

  if (loading) {
    return <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', color: 'var(--txt-3)' }}>Se încarcă...</div>;
  }

  return (
    <MediaAdminLayout onNav={onNav} currentPage="media-admin-contracts" profile={profile}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap', marginBottom: 24 }}>
        <div>
          <h1 className="display" style={{ fontSize: 30, margin: 0 }}>Contracte</h1>
          <p style={{ color: 'var(--txt-3)', fontSize: 13, margin: '4px 0 0' }}>
            Total: <strong style={{ color: 'var(--txt-1)' }}>{contracts.length}</strong>
            {asteaptaSemnaturaNoastra > 0 && (
              <span style={{ marginLeft: 12, color: '#3FA9F5' }}>
                · {asteaptaSemnaturaNoastra} {asteaptaSemnaturaNoastra === 1 ? 'așteaptă semnătura noastră' : 'așteaptă semnătura noastră'}
              </span>
            )}
          </p>
        </div>
        {tab === 'contracte' && (
          <button onClick={() => setShowCreate(true)} className="btn btn-primary">+ Contract nou</button>
        )}
      </div>

      <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
        {[['contracte', 'Contracte'], ['sabloane', 'Șabloane']].map(([id, label]) => (
          <button key={id} type="button" onClick={() => setTab(id)} style={{
            padding: '8px 16px', borderRadius: 8, fontSize: 13, cursor: 'pointer',
            border: tab === id ? '1px solid var(--accent-1)' : '.5px solid var(--line)',
            background: tab === id ? 'rgba(82,242,15,.1)' : 'transparent',
            color: tab === id ? 'var(--accent-1)' : 'var(--txt-2)', fontWeight: 500,
          }}>{label}</button>
        ))}
      </div>

      {tab === 'contracte' ? (
        <React.Fragment>
          <div className="card-glass" style={{ padding: 16, marginBottom: 16, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <input type="text" value={search} onChange={e => setSearch(e.target.value)}
              placeholder="🔍 Caută după titlu sau semnatar..." className="input" style={{ flex: 1, minWidth: 220 }} />
            <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} className="input"
              style={{ width: 200, color: '#FFFFFF', backgroundColor: '#1a1a1a' }}>
              {['Toate', 'Draft', 'Trimis', 'Semnat de client', 'Semnat', 'Anulat'].map(s =>
                <option key={s} value={s} style={{ backgroundColor: '#1a1a1a' }}>{s === 'Toate' ? 'Toate statusurile' : s}</option>)}
            </select>
          </div>

          <div className="card-glass" style={{ padding: 0, overflow: 'hidden' }}>
            {filtered.length === 0 ? (
              <div style={{ padding: 48, textAlign: 'center', color: 'var(--txt-3)', fontSize: 13 }}>
                {contracts.length === 0
                  ? 'Niciun contract încă. Apasă „+ Contract nou" ca să faci primul.'
                  : 'Niciun contract nu corespunde filtrelor.'}
              </div>
            ) : (
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                  <thead>
                    <tr style={{ background: 'rgba(255,255,255,.03)' }}>
                      {['Titlu', 'Tip', 'Semnatar', 'Status', 'Creat'].map(h => (
                        <th key={h} style={{ textAlign: 'left', padding: '12px 16px', fontSize: 11, color: 'var(--txt-3)', letterSpacing: '.08em', textTransform: 'uppercase', fontWeight: 500 }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {filtered.map(c => (
                      <tr key={c.id} onClick={() => setSelected(c)}
                        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 style={{ padding: '12px 16px' }}><strong>{c.title}</strong></td>
                        <td style={{ padding: '12px 16px', color: 'var(--txt-2)' }}>{c.type === 'brand' ? 'Brand' : 'Creator'}</td>
                        <td style={{ padding: '12px 16px', color: 'var(--txt-2)' }}>{c.signer_name}</td>
                        <td style={{ padding: '12px 16px' }}>
                          <span style={{
                            fontSize: 11, padding: '4px 10px', borderRadius: 6, fontWeight: 500,
                            background: (CONTRACT_STATUS_COLORS[c.status] || {}).bg,
                            color: (CONTRACT_STATUS_COLORS[c.status] || {}).color,
                          }}>{c.status}</span>
                        </td>
                        <td style={{ padding: '12px 16px' }}>
                          <span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>{new Date(c.created_at).toLocaleDateString('ro-RO')}</span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </React.Fragment>
      ) : (
        <TemplatesTab templates={templates} profile={profile} onChange={refresh} />
      )}

      {showCreate && (
        <ContractCreateDrawer
          templates={templates} brands={brands} influencers={influencers}
          campaigns={campaigns} profile={profile}
          onClose={() => setShowCreate(false)}
          onCreated={() => { setShowCreate(false); refresh(); }}
        />
      )}

      {selected && (
        <ContractDrawer
          contract={selected} staffList={staffList} profile={profile}
          onClose={() => setSelected(null)}
          onChange={() => { setSelected(null); refresh(); }}
        />
      )}
    </MediaAdminLayout>
  );
}

// ---------------------------------------------------------------------------
// Contract nou
// ---------------------------------------------------------------------------
function ContractCreateDrawer({ templates, brands, influencers, campaigns, profile, onClose, onCreated }) {
  const [type, setType] = useStateCT('brand');
  const [templateId, setTemplateId] = useStateCT('');
  const [partyId, setPartyId] = useStateCT('');
  const [campaignId, setCampaignId] = useStateCT('');
  const [title, setTitle] = useStateCT('');
  const [signerName, setSignerName] = useStateCT('');
  const [signerEmail, setSignerEmail] = useStateCT('');
  const [values, setValues] = useStateCT({});
  // Campurile pe care le lasam necompletate, ca sa le scrie semnatarul: CNP, IBAN,
  // CUI-ul exact, sediul din registru — lucruri pe care nu avem de unde sa le stim.
  const [clientFields, setClientFields] = useStateCT([]);
  const [expiryDays, setExpiryDays] = useStateCT('30');
  const [preview, setPreview] = useStateCT(false);
  const [saving, setSaving] = useStateCT(false);
  const [errorMsg, setErrorMsg] = useStateCT('');

  const typeTemplates = templates.filter(t => t.type === type && t.is_active);
  const template = templates.find(t => t.id === templateId);
  const brand = type === 'brand' ? brands.find(b => b.id === partyId) : null;
  const influencer = type === 'creator' ? influencers.find(i => i.id === partyId) : null;
  const campaign = campaigns.find(c => c.id === campaignId);

  // La fiecare schimbare de sablon / parte / campanie, recompletam ce stim,
  // dar nu stergem ce a scris omul de mana.
  useEffectCT(() => {
    const auto = autoFill({ type, brand, influencer, campaign });
    setValues(prev => {
      const next = Object.assign({}, prev);
      Object.keys(auto).forEach(k => {
        if (!next[k] || next[k] === '' || next['__auto_' + k]) {
          next[k] = auto[k];
          next['__auto_' + k] = true;
        }
      });
      return next;
    });
    if (!signerName) {
      if (brand) setSignerName(brand.contact_name || brand.company || '');
      if (influencer) setSignerName(influencer.full_name || '');
    }
    if (!signerEmail) {
      if (brand && brand.email) setSignerEmail(brand.email);
      if (influencer && influencer.email) setSignerEmail(influencer.email);
    }
  }, [templateId, partyId, campaignId, type]);

  useEffectCT(() => { setPartyId(''); setTemplateId(''); }, [type]);

  const placeholders = template ? extractPlaceholders(template.body) : [];
  const isClientField = (k) => clientFields.indexOf(k) !== -1;
  // Locurile marcate pentru client raman {{asa}} in text si se completeaza pe server
  // cand semneaza el.
  const ourValues = {};
  Object.keys(values).forEach(k => { if (!isClientField(k)) ourValues[k] = values[k]; });
  const body = template ? fillTemplate(template.body, ourValues) : '';
  const stillEmpty = placeholders.filter(p => !isClientField(p) && !values[p]);

  const toggleClientField = (k) => {
    setClientFields(prev => prev.indexOf(k) !== -1 ? prev.filter(x => x !== k) : prev.concat([k]));
  };

  const autoTitle = () => {
    if (title) return title;
    const who = brand ? (brand.brand || brand.company) : (influencer ? influencer.full_name : '');
    const camp = campaign ? ' — ' + campaign.name : '';
    return who ? ('Contract ' + who + camp) : 'Contract';
  };

  const handleCreate = async () => {
    setErrorMsg('');
    if (!template) { setErrorMsg('Alege un șablon.'); return; }
    if (!signerName.trim()) { setErrorMsg('Completează numele persoanei care semnează.'); return; }
    setSaving(true);
    try {
      const days = parseInt(expiryDays, 10);
      const expires = (!Number.isNaN(days) && days > 0)
        ? new Date(Date.now() + days * 86400000).toISOString()
        : null;

      const clean = {};
      Object.keys(values).forEach(k => { if (k.indexOf('__auto_') !== 0) clean[k] = values[k]; });

      const { error } = await window.sb.from('contracts').insert({
        type,
        template_id: template.id,
        title: autoTitle().trim(),
        body,
        fields: clean,
        signer_name: signerName.trim(),
        signer_email: signerEmail.trim() || null,
        brand_id: type === 'brand' ? (partyId || null) : null,
        influencer_id: type === 'creator' ? (partyId || null) : null,
        campaign_id: campaignId || null,
        client_fields: clientFields.filter(k => placeholders.indexOf(k) !== -1),
        status: 'Draft',
        expires_at: expires,
        created_by: profile ? profile.id : null,
      });
      if (error) throw error;
      setSaving(false);
      onCreated();
    } catch (e) {
      setErrorMsg('Eroare la salvare: ' + (e.message || 'necunoscută'));
      setSaving(false);
    }
  };

  const selectStyle = { width: '100%', color: '#FFFFFF', backgroundColor: '#1a1a1a' };
  const darkOpt = { backgroundColor: '#1a1a1a' };

  return (
    <div className="ma-modal-wrap" onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.7)', backdropFilter: 'blur(6px)', padding: 16 }}>
      <div className="ma-modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 820, width: '100%', 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: 20 }}>
          <h2 className="display" style={{ fontSize: 20, margin: 0 }}>Contract nou</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer' }}>✕</button>
        </div>

        {!preview ? (
          <React.Fragment>
            <EditFieldCT label="Tip contract">
              <div style={{ display: 'flex', gap: 8 }}>
                {[['brand', 'Cu un brand'], ['creator', 'Cu un creator']].map(([id, label]) => (
                  <button key={id} type="button" onClick={() => setType(id)} style={{
                    flex: 1, padding: '10px 14px', borderRadius: 8, fontSize: 13, cursor: 'pointer',
                    border: type === id ? '1px solid var(--accent-1)' : '.5px solid var(--line)',
                    background: type === id ? 'rgba(82,242,15,.1)' : 'transparent',
                    color: type === id ? 'var(--accent-1)' : 'var(--txt-2)', fontWeight: 500,
                  }}>{label}</button>
                ))}
              </div>
            </EditFieldCT>

            <EditFieldCT label="Șablon">
              <select value={templateId} onChange={e => setTemplateId(e.target.value)} className="input" style={selectStyle}>
                <option value="" style={darkOpt}>— Alege șablonul —</option>
                {typeTemplates.map(t => <option key={t.id} value={t.id} style={darkOpt}>{t.name}</option>)}
              </select>
              {typeTemplates.length === 0 && (
                <div style={{ fontSize: 11, color: '#FFD700', marginTop: 4 }}>
                  Nu există niciun șablon activ pentru acest tip. Adaugă unul din tabul „Șabloane".
                </div>
              )}
            </EditFieldCT>

            <EditFieldCT label={type === 'brand' ? 'Brandul' : 'Creatorul'}>
              <select value={partyId} onChange={e => setPartyId(e.target.value)} className="input" style={selectStyle}>
                <option value="" style={darkOpt}>— Alege —</option>
                {(type === 'brand' ? brands : influencers).map(x => (
                  <option key={x.id} value={x.id} style={darkOpt}>
                    {type === 'brand' ? (x.brand ? x.brand + ' (' + x.company + ')' : x.company) : x.full_name}
                  </option>
                ))}
              </select>
            </EditFieldCT>

            <EditFieldCT label="Campanie (opțional)">
              <select value={campaignId} onChange={e => setCampaignId(e.target.value)} className="input" style={selectStyle}>
                <option value="" style={darkOpt}>— Fără campanie —</option>
                {campaigns.map(c => <option key={c.id} value={c.id} style={darkOpt}>{c.name}</option>)}
              </select>
            </EditFieldCT>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 12 }}>
              <EditFieldCT label="Cine semnează (nume complet)">
                <input type="text" value={signerName} onChange={e => setSignerName(e.target.value)} className="input" style={{ width: '100%' }} placeholder="Nume Prenume" />
              </EditFieldCT>
              <EditFieldCT label="Email (opțional)">
                <input type="email" value={signerEmail} onChange={e => setSignerEmail(e.target.value)} className="input" style={{ width: '100%' }} />
              </EditFieldCT>
            </div>

            <EditFieldCT label="Titlul contractului">
              <input type="text" value={title} onChange={e => setTitle(e.target.value)} className="input" style={{ width: '100%' }} placeholder={autoTitle()} />
            </EditFieldCT>

            <EditFieldCT label="Linkul expiră după (zile)">
              <input type="number" min="0" value={expiryDays} onChange={e => setExpiryDays(e.target.value)} className="input" style={{ width: '100%' }} />
              <div style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 4 }}>0 = nu expiră niciodată. Implicit 30 de zile.</div>
            </EditFieldCT>

            {template && (
              <div style={{ marginTop: 8, marginBottom: 20, padding: 18, borderRadius: 12, background: 'rgba(63,169,245,.03)', border: '1px solid rgba(63,169,245,.15)' }}>
                <h3 style={{ fontSize: 14, margin: '0 0 4px', color: '#3FA9F5' }}>Câmpuri de completat</h3>
                <p style={{ fontSize: 12, color: 'var(--txt-3)', margin: '0 0 16px', lineHeight: 1.5 }}>
                  Vin din locurile goale din șablon. Cele pe care sistemul le știa sunt deja completate.
                  Ce nu ai de unde să știi — CNP, IBAN, CUI exact — lasă pe seama semnatarului cu butonul din dreapta câmpului.
                  {stillEmpty.length > 0 && <span style={{ color: '#FFD700' }}> Mai sunt {stillEmpty.length} necompletate de tine.</span>}
                  {clientFields.length > 0 && <span style={{ color: '#3FA9F5' }}> {clientFields.length} le completează semnatarul.</span>}
                </p>
                {placeholders.length === 0 ? (
                  <div style={{ fontSize: 12, color: 'var(--txt-3)' }}>Șablonul nu are locuri goale — contractul e fix.</div>
                ) : (
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
                    {placeholders.map(k => {
                      const forClient = isClientField(k);
                      return (
                        <div key={k}>
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                            <span style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '.08em', textTransform: 'uppercase' }}>{prettyLabel(k)}</span>
                            <button
                              type="button"
                              onClick={() => toggleClientField(k)}
                              title={forClient ? 'Îl completează semnatarul' : 'Îl completezi tu acum'}
                              style={{
                                fontSize: 10, padding: '2px 8px', borderRadius: 4, cursor: 'pointer',
                                border: '.5px solid ' + (forClient ? 'rgba(63,169,245,.5)' : 'var(--line)'),
                                background: forClient ? 'rgba(63,169,245,.12)' : 'transparent',
                                color: forClient ? '#3FA9F5' : 'var(--txt-3)',
                                whiteSpace: 'nowrap', transition: 'all .15s',
                              }}
                            >{forClient ? 'semnatarul' : 'eu'}</button>
                          </div>
                          {forClient ? (
                            <div style={{
                              height: 44, display: 'flex', alignItems: 'center', padding: '0 14px',
                              borderRadius: 8, border: '.5px dashed rgba(63,169,245,.4)',
                              background: 'rgba(63,169,245,.04)', fontSize: 12, color: '#3FA9F5',
                            }}>Se completează la semnare</div>
                          ) : (
                            <input
                              type="text"
                              value={values[k] || ''}
                              onChange={e => setValues(prev => Object.assign({}, prev, { [k]: e.target.value, ['__auto_' + k]: false }))}
                              className="input"
                              style={{ width: '100%', borderColor: values[k] ? undefined : 'rgba(255,215,0,.4)' }}
                              placeholder={'{{' + k + '}}'}
                            />
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            )}

            {errorMsg && <div style={{ marginTop: 12, 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={() => setPreview(true)} disabled={!template} className="btn btn-glass" style={{ width: '100%', marginTop: 12, opacity: template ? 1 : .5 }}>
              Vezi cum arată contractul →
            </button>
          </React.Fragment>
        ) : (
          <React.Fragment>
            {stillEmpty.length > 0 && (
              <div style={{ marginBottom: 12, padding: '10px 12px', borderRadius: 8, background: 'rgba(255,215,0,.08)', border: '.5px solid rgba(255,215,0,.3)', fontSize: 12, color: 'var(--txt-2)' }}>
                ⚠️ Au rămas necompletate de tine: <strong>{stillEmpty.map(prettyLabel).join(', ')}</strong>. Vor apărea în contract ca <code>{'{{...}}'}</code>.
              </div>
            )}
            {clientFields.length > 0 && (
              <div style={{ marginBottom: 16, padding: '10px 12px', borderRadius: 8, background: 'rgba(63,169,245,.08)', border: '.5px solid rgba(63,169,245,.3)', fontSize: 12, color: 'var(--txt-2)' }}>
                Semnatarul completează: <strong>{clientFields.map(prettyLabel).join(', ')}</strong>. Le vezi completate înainte să contrasemnezi.
              </div>
            )}
            <div style={{ background: '#fff', color: '#18181b', padding: 28, borderRadius: 10, maxHeight: '50vh', overflowY: 'auto', whiteSpace: 'pre-wrap', fontSize: 13.5, lineHeight: 1.7, fontFamily: "system-ui, sans-serif" }}>
              {body}
            </div>
            {errorMsg && <div style={{ marginTop: 12, 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: 16 }}>
              <button onClick={() => setPreview(false)} className="btn btn-glass" style={{ flex: 1 }}>← Înapoi la câmpuri</button>
              <button onClick={handleCreate} disabled={saving} className="btn btn-primary" style={{ flex: 2, opacity: saving ? .6 : 1 }}>
                {saving ? 'Se salvează...' : 'Salvează contractul'}
              </button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Contract existent: trimitere, semnatura noastra, printare
// ---------------------------------------------------------------------------
function ContractDrawer({ contract, staffList, profile, onClose, onChange }) {
  const [busy, setBusy] = useStateCT(false);
  const [errorMsg, setErrorMsg] = useStateCT('');
  const [copied, setCopied] = useStateCT(false);
  const [signing, setSigning] = useStateCT(false);
  const [showPrint, setShowPrint] = useStateCT(false);
  const [accessLog, setAccessLog] = useStateCT([]);

  const link = SIGN_BASE + '?t=' + contract.sign_token;

  useEffectCT(() => {
    (async () => {
      const { data } = await window.sb.from('contract_access_log')
        .select('*').eq('contract_id', contract.id).order('accessed_at', { ascending: false }).limit(10);
      setAccessLog(data || []);
    })();
  }, [contract.id]);

  const setStatus = async (status, extra) => {
    setBusy(true); setErrorMsg('');
    const updates = Object.assign({ status }, extra || {});
    const { error } = await window.sb.from('contracts').update(updates).eq('id', contract.id);
    setBusy(false);
    if (error) { setErrorMsg('Eroare: ' + error.message); return; }
    onChange();
  };

  const copyLink = () => {
    const done = () => { setCopied(true); setTimeout(() => setCopied(false), 2000); };
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(link).then(done).catch(() => {});
    } else {
      const ta = document.createElement('textarea');
      ta.value = link; document.body.appendChild(ta); ta.select();
      try { document.execCommand('copy'); done(); } catch (e) {}
      document.body.removeChild(ta);
    }
  };

  const handleAgencySign = async (dataUrl) => {
    setBusy(true); setErrorMsg('');
    const { error } = await window.sb.from('contracts').update({
      status: 'Semnat',
      agency_signature_data: dataUrl,
      agency_signed_by: profile ? profile.id : null,
      agency_signer_name: profile ? profile.full_name : null,
      agency_signed_at: new Date().toISOString(),
    }).eq('id', contract.id);
    setBusy(false);
    if (error) { setErrorMsg('Eroare: ' + error.message); return; }
    onChange();
  };

  const col = CONTRACT_STATUS_COLORS[contract.status] || {};

  return (
    <React.Fragment>
      <div className="ma-modal-wrap" onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.7)', backdropFilter: 'blur(6px)', padding: 16 }}>
        <div className="ma-modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 820, width: '100%', 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', gap: 12, marginBottom: 6 }}>
            <h2 className="display" style={{ fontSize: 20, margin: 0 }}>{contract.title}</h2>
            <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer' }}>✕</button>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 22, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: col.bg, color: col.color, fontWeight: 500 }}>{contract.status}</span>
            <span style={{ fontSize: 12, color: 'var(--txt-3)' }}>
              {contract.type === 'brand' ? 'Brand' : 'Creator'} · semnează {contract.signer_name}
            </span>
          </div>

          {/* Ce trebuie facut acum */}
          <div style={{ marginBottom: 20, padding: 18, borderRadius: 12, background: 'rgba(63,169,245,.03)', border: '1px solid rgba(63,169,245,.15)' }}>
            <h3 style={{ fontSize: 14, margin: '0 0 12px', color: '#3FA9F5' }}>Ce urmează</h3>

            {contract.status === 'Draft' && (
              <React.Fragment>
                <p style={{ fontSize: 13, color: 'var(--txt-2)', margin: '0 0 14px', lineHeight: 1.6 }}>
                  Contractul e ciornă — linkul nu funcționează încă. Verifică textul, apoi trimite-l spre semnare.
                </p>
                <button onClick={() => setStatus('Trimis', { sent_at: new Date().toISOString() })} disabled={busy} className="btn btn-primary" style={{ width: '100%' }}>
                  {busy ? 'Se pregătește...' : 'Trimite spre semnare'}
                </button>
              </React.Fragment>
            )}

            {contract.status === 'Trimis' && (
              <React.Fragment>
                <p style={{ fontSize: 13, color: 'var(--txt-2)', margin: '0 0 12px', lineHeight: 1.6 }}>
                  Trimite linkul de mai jos lui <strong>{contract.signer_name}</strong>. Semnează el primul; noi semnăm după.
                </p>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <input type="text" readOnly value={link} className="input mono"
                    onFocus={e => e.target.select()}
                    style={{ flex: 1, minWidth: 240, fontSize: 12 }} />
                  <button onClick={copyLink} className="btn btn-glass" style={{ whiteSpace: 'nowrap' }}>
                    {copied ? '✓ Copiat' : 'Copiază link'}
                  </button>
                </div>
                {contract.expires_at && (
                  <div style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 8 }}>
                    Linkul expiră pe {new Date(contract.expires_at).toLocaleDateString('ro-RO')}.
                  </div>
                )}
              </React.Fragment>
            )}

            {contract.status === 'Semnat de client' && (
              <React.Fragment>
                <p style={{ fontSize: 13, color: 'var(--txt-2)', margin: '0 0 14px', lineHeight: 1.6 }}>
                  <strong style={{ color: 'var(--txt-0)' }}>{contract.signer_name}</strong> a semnat pe {new Date(contract.client_signed_at).toLocaleString('ro-RO')}.
                  Acum semnezi tu, iar contractul devine complet.
                </p>
                {!signing ? (
                  <button onClick={() => setSigning(true)} className="btn btn-primary" style={{ width: '100%' }}>
                    Semnează din partea 4U Agency
                  </button>
                ) : (
                  <SignaturePadCT
                    label={'Semnezi ca ' + (profile ? profile.full_name : '—')}
                    busy={busy}
                    onCancel={() => setSigning(false)}
                    onSign={handleAgencySign}
                  />
                )}
              </React.Fragment>
            )}

            {contract.status === 'Semnat' && (
              <React.Fragment>
                <p style={{ fontSize: 13, color: 'var(--txt-2)', margin: '0 0 12px', lineHeight: 1.6 }}>
                  Contract semnat de ambele părți. Trimite-i din nou linkul — acum vede contractul complet — sau salvează PDF-ul.
                </p>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <input type="text" readOnly value={link} className="input mono" onFocus={e => e.target.select()} style={{ flex: 1, minWidth: 240, fontSize: 12 }} />
                  <button onClick={copyLink} className="btn btn-glass" style={{ whiteSpace: 'nowrap' }}>{copied ? '✓ Copiat' : 'Copiază link'}</button>
                </div>
                <button onClick={() => setShowPrint(true)} className="btn btn-primary" style={{ width: '100%', marginTop: 10 }}>
                  Deschide contractul semnat (PDF)
                </button>
              </React.Fragment>
            )}

            {contract.status === 'Anulat' && (
              <p style={{ fontSize: 13, color: 'var(--txt-2)', margin: 0 }}>Contract anulat. Linkul nu mai funcționează.</p>
            )}
          </div>

          {/* Textul contractului */}
          <div style={{ background: '#fff', color: '#18181b', padding: 24, borderRadius: 10, maxHeight: 320, overflowY: 'auto', whiteSpace: 'pre-wrap', fontSize: 13, lineHeight: 1.7, marginBottom: 16 }}>
            {contract.body}
          </div>

          {/* Semnaturi */}
          {(contract.client_signature_data || contract.agency_signature_data) && (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12, marginBottom: 16 }}>
              <SigCardCT title={'Semnat de ' + contract.signer_name} sig={contract.client_signature_data}
                name={contract.client_typed_name} when={contract.client_signed_at} ip={contract.client_ip} />
              <SigCardCT title="Din partea 4U Agency" sig={contract.agency_signature_data}
                name={contract.agency_signer_name} when={contract.agency_signed_at} />
            </div>
          )}

          {/* Jurnal accesari */}
          {accessLog.length > 0 && (
            <details style={{ marginBottom: 16 }}>
              <summary style={{ fontSize: 12, color: 'var(--txt-3)', cursor: 'pointer' }}>
                Linkul a fost deschis de {accessLog.length === 10 ? '10+' : accessLog.length} ori
              </summary>
              <div style={{ marginTop: 8, fontSize: 11, color: 'var(--txt-3)', display: 'flex', flexDirection: 'column', gap: 4 }}>
                {accessLog.map(a => (
                  <div key={a.id} className="mono">
                    {new Date(a.accessed_at).toLocaleString('ro-RO')}{a.ip ? ' · ' + a.ip : ''}
                  </div>
                ))}
              </div>
            </details>
          )}

          {errorMsg && <div style={{ marginBottom: 12, 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>}

          {contract.status !== 'Anulat' && contract.status !== 'Semnat' && (
            <button onClick={() => setStatus('Anulat')} disabled={busy} className="btn btn-glass" style={{ width: '100%', color: '#FF5A5A' }}>
              Anulează contractul
            </button>
          )}
        </div>
      </div>

      {showPrint && <ContractPrintView contract={contract} onClose={() => setShowPrint(false)} />}
    </React.Fragment>
  );
}

function SigCardCT({ title, sig, name, when, ip }) {
  return (
    <div style={{ border: '.5px solid var(--line)', borderRadius: 10, padding: 14, background: sig ? '#fff' : 'rgba(255,255,255,.02)' }}>
      <div style={{ fontSize: 10, color: sig ? '#71717a' : 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '.06em' }}>{title}</div>
      {sig ? (
        <React.Fragment>
          <img src={sig} alt={'Semnătură ' + (name || '')} style={{ maxWidth: '100%', height: 64, objectFit: 'contain', objectPosition: 'left', display: 'block', margin: '8px 0' }} />
          <div style={{ fontSize: 13, fontWeight: 600, color: '#18181b' }}>{name || '—'}</div>
          <div style={{ fontSize: 11, color: '#71717a' }}>
            {when ? new Date(when).toLocaleString('ro-RO') : ''}{ip ? ' · IP ' + ip : ''}
          </div>
        </React.Fragment>
      ) : (
        <div style={{ padding: '20px 0', fontSize: 12, color: 'var(--txt-3)', fontStyle: 'italic' }}>Încă nesemnat</div>
      )}
    </div>
  );
}

// Caseta de semnatura din panou. Aceeasi logica de desen ca pe pagina publica.
function SignaturePadCT({ label, busy, onSign, onCancel }) {
  const canvasRef = useRefCT(null);
  const [hasInk, setHasInk] = useStateCT(false);

  useEffectCT(() => {
    const cv = canvasRef.current;
    if (!cv) return;
    const ratio = window.devicePixelRatio || 1;
    const rect = cv.getBoundingClientRect();
    cv.width = Math.round(rect.width * ratio);
    cv.height = Math.round(rect.height * ratio);
    const ctx = cv.getContext('2d');
    ctx.scale(ratio, ratio);
    ctx.lineWidth = 2.2; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.strokeStyle = '#18181b';

    let drawing = false, lx = 0, ly = 0;
    const pos = (e) => { const r = cv.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top }; };
    const down = (e) => {
      e.preventDefault(); cv.setPointerCapture(e.pointerId); drawing = true;
      const p = pos(e); lx = p.x; ly = p.y;
      ctx.beginPath(); ctx.arc(p.x, p.y, 1.1, 0, Math.PI * 2); ctx.fill();
      setHasInk(true);
    };
    const move = (e) => {
      if (!drawing) return; e.preventDefault();
      const p = pos(e);
      ctx.beginPath(); ctx.moveTo(lx, ly); ctx.lineTo(p.x, p.y); ctx.stroke();
      lx = p.x; ly = p.y;
    };
    const up = () => { drawing = false; };
    cv.addEventListener('pointerdown', down);
    cv.addEventListener('pointermove', move);
    cv.addEventListener('pointerup', up);
    cv.addEventListener('pointercancel', up);
    cv.addEventListener('pointerleave', up);
    return () => {
      cv.removeEventListener('pointerdown', down);
      cv.removeEventListener('pointermove', move);
      cv.removeEventListener('pointerup', up);
      cv.removeEventListener('pointercancel', up);
      cv.removeEventListener('pointerleave', up);
    };
  }, []);

  const clear = () => {
    const cv = canvasRef.current;
    const ctx = cv.getContext('2d');
    const ratio = window.devicePixelRatio || 1;
    ctx.clearRect(0, 0, cv.width / ratio, cv.height / ratio);
    setHasInk(false);
  };

  return (
    <div>
      <div style={{ fontSize: 12, color: 'var(--txt-2)', marginBottom: 8 }}>{label}</div>
      <canvas ref={canvasRef} style={{
        width: '100%', height: 150, display: 'block', background: '#fff',
        border: '2px dashed #c7c7cc', borderRadius: 8, touchAction: 'none', cursor: 'crosshair',
      }} />
      <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
        <button onClick={clear} className="btn btn-glass btn-sm">Șterge</button>
        <button onClick={onCancel} className="btn btn-glass btn-sm">Renunță</button>
        <button
          onClick={() => onSign(canvasRef.current.toDataURL('image/png'))}
          disabled={!hasInk || busy}
          className="btn btn-primary"
          style={{ flex: 1, opacity: (!hasInk || busy) ? .5 : 1 }}
        >{busy ? 'Se salvează...' : 'Confirmă semnătura'}</button>
      </div>
    </div>
  );
}

// Contractul semnat, pe foaie alba, gata de printat. Foloseste aceleasi clase
// ca rapoartele, deci si aceleasi reguli de printare din styles.css.
function ContractPrintView({ contract, onClose }) {
  return ReactDOM.createPortal(
    <div className="report-print-root" style={{ position: 'fixed', inset: 0, zIndex: 400, overflowY: 'auto', background: '#f4f4f5', padding: '24px 16px' }}>
      <div className="report-toolbar" style={{
        position: 'sticky', top: 0, zIndex: 2, maxWidth: 920, margin: '0 auto 16px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
        padding: '12px 16px', borderRadius: 10, background: '#18181b', color: '#fff', flexWrap: 'wrap',
      }}>
        <div style={{ fontSize: 13 }}>Alege „Salvează ca PDF" în fereastra de printare.</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={() => window.print()} style={{ padding: '8px 16px', borderRadius: 8, border: 'none', cursor: 'pointer', background: '#52F20F', color: '#000', fontWeight: 600, fontSize: 13 }}>Printează / Salvează PDF</button>
          <button onClick={onClose} style={{ padding: '8px 16px', borderRadius: 8, border: '1px solid rgba(255,255,255,.2)', background: 'transparent', color: '#fff', cursor: 'pointer', fontSize: 13 }}>Închide</button>
        </div>
      </div>

      <div className="report-sheet" style={{
        maxWidth: 920, margin: '0 auto', background: '#fff', color: '#18181b',
        padding: '40px 44px', borderRadius: 10, boxShadow: '0 2px 24px rgba(0,0,0,.12)',
        fontFamily: "'Geist', system-ui, sans-serif", lineHeight: 1.6,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 20, borderBottom: '2px solid #18181b', paddingBottom: 14, marginBottom: 22 }}>
          <div>
            <div style={{ fontSize: 19, fontWeight: 800 }}>4U Agency</div>
            <div style={{ fontSize: 10, color: '#71717a', letterSpacing: '.08em', textTransform: 'uppercase' }}>Agenție de influencer marketing</div>
          </div>
          <div style={{ fontSize: 10, color: '#71717a', letterSpacing: '.1em', textTransform: 'uppercase', textAlign: 'right' }}>Contract semnat</div>
        </div>

        <h1 style={{ fontSize: 21, margin: '0 0 18px' }}>{contract.title}</h1>
        <div style={{ whiteSpace: 'pre-wrap', fontSize: 13.5, lineHeight: 1.75, borderTop: '1px solid #e4e4e7', borderBottom: '1px solid #e4e4e7', padding: '20px 0', marginBottom: 22 }}>
          {contract.body}
        </div>

        <div className="report-creator" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
          <div style={{ border: '1px solid #e4e4e7', borderRadius: 8, padding: 14 }}>
            <div style={{ fontSize: 10, color: '#71717a', textTransform: 'uppercase', letterSpacing: '.06em' }}>{contract.signer_name}</div>
            {contract.client_signature_data && <img src={contract.client_signature_data} alt="" style={{ maxWidth: '100%', height: 70, objectFit: 'contain', objectPosition: 'left', display: 'block', margin: '8px 0' }} />}
            <div style={{ fontSize: 13, fontWeight: 600 }}>{contract.client_typed_name || '—'}</div>
            <div style={{ fontSize: 11, color: '#71717a' }}>{contract.client_signed_at ? new Date(contract.client_signed_at).toLocaleString('ro-RO') : ''}</div>
          </div>
          <div style={{ border: '1px solid #e4e4e7', borderRadius: 8, padding: 14 }}>
            <div style={{ fontSize: 10, color: '#71717a', textTransform: 'uppercase', letterSpacing: '.06em' }}>4U Agency S.R.L.</div>
            {contract.agency_signature_data && <img src={contract.agency_signature_data} alt="" style={{ maxWidth: '100%', height: 70, objectFit: 'contain', objectPosition: 'left', display: 'block', margin: '8px 0' }} />}
            <div style={{ fontSize: 13, fontWeight: 600 }}>{contract.agency_signer_name || '—'}</div>
            <div style={{ fontSize: 11, color: '#71717a' }}>{contract.agency_signed_at ? new Date(contract.agency_signed_at).toLocaleString('ro-RO') : ''}</div>
          </div>
        </div>

        <div style={{ marginTop: 24, paddingTop: 12, borderTop: '1px solid #e4e4e7', fontSize: 10, color: '#71717a', lineHeight: 1.6 }}>
          Semnături electronice simple, aplicate prin platforma 4U Agency.
          {contract.client_ip && <span> Semnătura clientului a fost înregistrată de la adresa IP {contract.client_ip}.</span>}
        </div>
      </div>
    </div>,
    document.body
  );
}

// ---------------------------------------------------------------------------
// Sabloane
// ---------------------------------------------------------------------------
function TemplatesTab({ templates, profile, onChange }) {
  const [editing, setEditing] = useStateCT(null);
  const [creating, setCreating] = useStateCT(false);

  return (
    <React.Fragment>
      <div className="card-glass" style={{ padding: 20, marginBottom: 16 }}>
        <p style={{ fontSize: 13, color: 'var(--txt-2)', margin: '0 0 8px', lineHeight: 1.6 }}>
          Aici puneți contractul vostru standard, o singură dată. Unde vreți să apară ceva diferit la fiecare
          contract, scrieți <code style={{ color: 'var(--accent-1)' }}>{'{{nume_camp}}'}</code> — la crearea unui
          contract, locurile astea devin câmpuri de completat.
        </p>
        <p style={{ fontSize: 12, color: 'var(--txt-3)', margin: 0, lineHeight: 1.6 }}>
          Câmpuri completate automat dacă le folosiți cu aceste nume: <span className="mono">companie, cui_client,
          reprezentant_client, email_client, telefon_client, sediu_client, nume_creator, handle, email_creator,
          telefon_creator, adresa_creator, campanie, perioada, valoare, data_contract</span>
        </p>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 12 }}>
        <button onClick={() => setCreating(true)} className="btn btn-glass">+ Șablon nou</button>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {templates.length === 0 && (
          <div className="card-glass" style={{ padding: 40, textAlign: 'center', color: 'var(--txt-3)', fontSize: 13 }}>
            Niciun șablon. Adaugă primul.
          </div>
        )}
        {templates.map(t => (
          <div key={t.id} className="card-glass" style={{ padding: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{t.name}</div>
              <div style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 2 }}>
                {t.type === 'brand' ? 'Pentru branduri' : 'Pentru creatori'}
                {' · '}{extractPlaceholders(t.body).length} câmpuri
                {!t.is_active && <span style={{ color: '#FF5A5A' }}> · inactiv</span>}
              </div>
            </div>
            <button onClick={() => setEditing(t)} className="btn btn-glass btn-sm">Editează</button>
          </div>
        ))}
      </div>

      {(editing || creating) && (
        <TemplateEditor
          template={editing}
          profile={profile}
          onClose={() => { setEditing(null); setCreating(false); }}
          onSaved={() => { setEditing(null); setCreating(false); onChange(); }}
        />
      )}
    </React.Fragment>
  );
}

function TemplateEditor({ template, profile, onClose, onSaved }) {
  const [name, setName] = useStateCT(template ? template.name : '');
  const [type, setType] = useStateCT(template ? template.type : 'brand');
  const [body, setBody] = useStateCT(template ? template.body : '');
  const [isActive, setIsActive] = useStateCT(template ? template.is_active : true);
  const [saving, setSaving] = useStateCT(false);
  const [errorMsg, setErrorMsg] = useStateCT('');

  const placeholders = extractPlaceholders(body);

  const save = async () => {
    if (!name.trim()) { setErrorMsg('Dă-i un nume șablonului.'); return; }
    if (!body.trim()) { setErrorMsg('Textul contractului nu poate fi gol.'); return; }
    setSaving(true); setErrorMsg('');
    const payload = { name: name.trim(), type, body, is_active: isActive };
    const { error } = template
      ? await window.sb.from('contract_templates').update(payload).eq('id', template.id)
      : await window.sb.from('contract_templates').insert(Object.assign(payload, { created_by: profile ? profile.id : null }));
    setSaving(false);
    if (error) { setErrorMsg('Eroare: ' + error.message); return; }
    onSaved();
  };

  return (
    <div className="ma-modal-wrap" onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.7)', backdropFilter: 'blur(6px)', padding: 16 }}>
      <div className="ma-modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 820, width: '100%', 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: 20 }}>
          <h2 className="display" style={{ fontSize: 20, margin: 0 }}>{template ? 'Editează șablonul' : 'Șablon nou'}</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer' }}>✕</button>
        </div>

        <EditFieldCT label="Nume șablon">
          <input type="text" value={name} onChange={e => setName(e.target.value)} className="input" style={{ width: '100%' }} placeholder="ex: Contract colaborare brand 2026" />
        </EditFieldCT>

        <EditFieldCT label="Pentru cine">
          <select value={type} onChange={e => setType(e.target.value)} className="input" style={{ width: '100%', color: '#FFFFFF', backgroundColor: '#1a1a1a' }}>
            <option value="brand" style={{ backgroundColor: '#1a1a1a' }}>Branduri</option>
            <option value="creator" style={{ backgroundColor: '#1a1a1a' }}>Creatori</option>
          </select>
        </EditFieldCT>

        <EditFieldCT label="Textul contractului">
          <textarea value={body} onChange={e => setBody(e.target.value)} rows={18} className="input"
            style={{ width: '100%', resize: 'vertical', minHeight: 380, height: 'auto', padding: '14px 16px', fontFamily: 'JetBrains Mono, monospace', fontSize: 12.5, lineHeight: 1.7 }}
            placeholder={'Lipește aici contractul vostru standard.\n\nUnde vrei ceva diferit la fiecare contract, scrie {{nume_camp}}.'} />
        </EditFieldCT>

        {placeholders.length > 0 && (
          <div style={{ marginBottom: 16, padding: 14, borderRadius: 10, background: 'rgba(82,242,15,.03)', border: '.5px solid rgba(82,242,15,.15)' }}>
            <div style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 8 }}>
              {placeholders.length} câmpuri găsite în text:
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {placeholders.map(p => (
                <span key={p} className="mono" style={{ fontSize: 11, padding: '3px 8px', borderRadius: 5, background: 'rgba(82,242,15,.08)', color: 'var(--accent-1)' }}>{p}</span>
              ))}
            </div>
          </div>
        )}

        <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13, color: 'var(--txt-2)', marginBottom: 16 }}>
          <input type="checkbox" checked={isActive} onChange={e => setIsActive(e.target.checked)} style={{ accentColor: 'var(--accent-1)' }} />
          Activ (apare în lista de șabloane la contract nou)
        </label>

        {errorMsg && <div style={{ marginBottom: 12, 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={save} disabled={saving} className="btn btn-primary" style={{ width: '100%', opacity: saving ? .6 : 1 }}>
          {saving ? 'Se salvează...' : 'Salvează șablonul'}
        </button>
      </div>
    </div>
  );
}

function EditFieldCT({ 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>
  );
}
