// supplier-register.jsx — Tedarikçi davet + tek kullanımlık link + kayıt formu (Faz 4 / Parça 4.2)
// Güvenlik modeli (prototipte simüle): Satınalma davet eder → tedarikçiye tek kullanımlık link gider →
// tedarikçi DMZ'deki AYRI sunucuda kayıt formunu doldurur → kayıt sonrası link ölür (inviteUsed).
// Kayıt sayfası login gerektirmez ve "dış sunucu" banner'ı taşır (iç sisteme kapalı).

// ─────────── Matbu Gizlilik Sözleşmesi (NDA) ───────────
// Tedarikçi indirir, imzalar/kaşeler, tarayıp sisteme yükler. Yazdırılabilir HTML üretir.
function ndaHtml(supplierCompany) {
  const today = new Date().toLocaleDateString('tr-TR');
  const sup = supplierCompany && supplierCompany.trim() ? supplierCompany.trim() : '............................................';
  return `<!DOCTYPE html><html lang="tr"><head><meta charset="utf-8"><title>Gizlilik Sözleşmesi (NDA)</title>
<style>
  body{font-family:'Times New Roman',Georgia,serif;color:#111;max-width:780px;margin:32px auto;padding:0 28px;line-height:1.6;font-size:14px}
  h1{text-align:center;font-size:19px;letter-spacing:.02em;margin-bottom:4px}
  .sub{text-align:center;color:#444;font-size:12px;margin-bottom:26px}
  h2{font-size:14px;margin:20px 0 6px;border-bottom:1px solid #ccc;padding-bottom:3px}
  p{margin:8px 0;text-align:justify}
  .parties{background:#f6f6f6;border:1px solid #ddd;padding:12px 16px;border-radius:6px;margin:14px 0}
  .sign{display:flex;justify-content:space-between;margin-top:48px;gap:40px}
  .sign div{flex:1;border-top:1px solid #333;padding-top:6px;font-size:12px}
  .small{font-size:11px;color:#666}
  @media print{body{margin:0}.noprint{display:none}}
  .noprint{text-align:center;margin:24px 0}
  .btn{font-family:Arial,sans-serif;background:#2563EB;color:#fff;border:none;padding:10px 18px;border-radius:8px;font-size:13px;cursor:pointer}
</style></head><body>
<div class="noprint"><button class="btn" onclick="window.print()">Yazdır / PDF olarak kaydet</button></div>
<h1>GİZLİLİK SÖZLEŞMESİ</h1>
<div class="sub">(Karşılıklı Gizlilik ve Sır Saklama Taahhütnamesi)</div>

<div class="parties">
  <p><b>İşbu Sözleşme</b> aşağıda bilgileri yer alan taraflar arasında ${today} tarihinde akdedilmiştir:</p>
  <p><b>1. Alıcı Taraf (Şirket):</b> ......................................................... ("Şirket")</p>
  <p><b>2. Tedarikçi Taraf:</b> ${sup} ("Tedarikçi")</p>
</div>

<h2>1. Amaç</h2>
<p>İşbu Sözleşme'nin amacı; Taraflar arasında kurulacak ticari ilişki, teklif süreçleri ve tedarik faaliyetleri kapsamında karşılıklı olarak paylaşılacak her türlü gizli bilginin korunması, üçüncü kişilere açıklanmaması ve yalnızca belirlenen amaçla kullanılmasına ilişkin esasları düzenlemektir.</p>

<h2>2. Gizli Bilginin Tanımı</h2>
<p>Gizli Bilgi; sözlü, yazılı, elektronik veya başka herhangi bir biçimde paylaşılan; ticari, mali, teknik, hukuki bilgiler, fiyat teklifleri, ürün ve hizmet detayları, müşteri ve çalışan bilgileri, iş süreçleri, yazılım, ağ mimarisi ve güvenlik yapılandırmaları dahil ancak bunlarla sınırlı olmamak üzere tüm bilgileri kapsar.</p>

<h2>3. Tarafların Yükümlülükleri</h2>
<p>3.1. Taraflar, Gizli Bilgi'yi en az kendi gizli bilgilerine gösterdikleri özeni göstererek korumayı taahhüt eder.</p>
<p>3.2. Gizli Bilgi, karşı tarafın yazılı izni olmaksızın üçüncü kişilerle paylaşılamaz, çoğaltılamaz ve işbu Sözleşme'nin amacı dışında kullanılamaz.</p>
<p>3.3. Gizli Bilgi'ye yalnızca işin gereği bilmesi gereken çalışanların erişmesi sağlanır ve bu kişiler de aynı gizlilik yükümlülüğüne tabi tutulur.</p>

<h2>4. İstisnalar</h2>
<p>Kamuya mal olmuş, karşı taraftan bağımsız olarak edinilmiş veya yasal bir merci tarafından açıklanması zorunlu kılınan bilgiler gizlilik yükümlülüğünün dışındadır.</p>

<h2>5. Kişisel Verilerin Korunması (KVKK)</h2>
<p>Taraflar, paylaşılan kişisel verileri 6698 sayılı Kişisel Verilerin Korunması Kanunu ve ilgili mevzuata uygun olarak işlemeyi, saklamayı ve korumayı taahhüt eder.</p>

<h2>6. Süre ve Sona Erme</h2>
<p>İşbu Sözleşme imza tarihinde yürürlüğe girer. Gizlilik yükümlülükleri, ticari ilişki sona erse dahi <b>5 (beş) yıl</b> süreyle devam eder.</p>

<h2>7. Sorumluluk ve İhlal</h2>
<p>Gizlilik yükümlülüğünü ihlal eden Taraf, karşı tarafın bu nedenle uğrayacağı her türlü doğrudan zararı tazmin etmekle yükümlüdür.</p>

<h2>8. Uyuşmazlıkların Çözümü</h2>
<p>İşbu Sözleşme'den doğacak uyuşmazlıkların çözümünde Türkiye Cumhuriyeti hukuku uygulanır ve ........................ Mahkemeleri ile İcra Daireleri yetkilidir.</p>

<div class="sign">
  <div><b>ALICI (Şirket)</b><br>Ad-Soyad / Ünvan: ....................<br>Tarih: ....................<br>İmza / Kaşe:</div>
  <div><b>TEDARİKÇİ</b><br>${sup}<br>Ad-Soyad / Ünvan: ....................<br>Tarih: ....................<br>İmza / Kaşe:</div>
</div>
<p class="small" style="margin-top:34px">Bu belge örnek (matbu) bir gizlilik sözleşmesidir. Şirketinizin hukuk birimi tarafından nihai metin onaylanmalıdır.</p>
</body></html>`;
}

function downloadNda(supplierCompany) {
  const blob = new Blob([ndaHtml(supplierCompany)], { type: 'text/html;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'Gizlilik_Sozlesmesi_NDA.html';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1500);
}

// Sahte DMZ alan adı — üretimde tedarikçi ön-yüzü ayrı sunucuda
const SUPPLIER_PORTAL_HOST = 'https://tedarikci.sirketiniz.com.tr';
function inviteLink(token) { return `${SUPPLIER_PORTAL_HOST}/kayit?davet=${token}`; }

// ─────────── Küçük form yardımcıları ───────────
function regLabel(c) { return { fontSize: 11.5, color: c.muted, marginBottom: 6, display: 'block' }; }
function RegField({ label, required, children, c, full }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gridColumn: full ? '1 / -1' : 'auto' }}>
      <label style={regLabel(c)}>{label}{required ? ' *' : ''}</label>
      {children}
    </div>
  );
}

// ─────────── Aramalı çoklu-seçim (binlerce kategori için) ───────────
// Seçili olanlar chip olarak kutuda; tıklayınca arama kutulu açılır liste. Ölçeklenir.
function CategoryMultiSelect({ options, selected, onToggle, c, placeholder }) {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState('');
  const ref = React.useRef(null);
  React.useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);
  const sel = options.filter((o) => selected.has(o.id));
  const term = q.trim().toLowerCase();
  const filtered = term ? options.filter((o) => o.label.toLowerCase().includes(term)) : options;

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <div onClick={() => setOpen(true)} style={{ ...inputBox(c), minHeight: 44, display: 'flex', flexWrap: 'wrap', gap: 6, cursor: 'text', alignItems: 'center', padding: '7px 10px' }}>
        {sel.length === 0 && <span style={{ color: c.subtle, fontSize: 13 }}>{placeholder || 'Kategori arayın ve seçin...'}</span>}
        {sel.map((o) => (
          <span key={o.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 6px 3px 10px', borderRadius: 999, background: c.selectedBg, color: c.selectedText, fontSize: 12.5, fontWeight: 500 }}>
            {o.label}
            <span onClick={(e) => { e.stopPropagation(); onToggle(o.id); }} title="Kaldır" style={{ cursor: 'pointer', display: 'flex', color: c.selectedText, opacity: 0.7 }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
            </span>
          </span>
        ))}
        <span style={{ marginLeft: 'auto', color: c.muted, display: 'flex' }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6" /></svg>
        </span>
      </div>
      {open && (
        <div style={{ position: 'absolute', top: 'calc(100% + 4px)', left: 0, right: 0, zIndex: 30, background: c.surface, border: `1px solid ${c.border}`, borderRadius: 12, boxShadow: '0 12px 32px -8px rgba(15,23,42,0.22)', padding: 8 }}>
          <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Kategori ara..." style={{ ...inputBox(c), marginBottom: 6 }} />
          <div style={{ maxHeight: 240, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 2 }}>
            {filtered.length === 0 && <div style={{ padding: '10px 12px', fontSize: 12.5, color: c.muted }}>Sonuç yok</div>}
            {filtered.map((o) => {
              const on = selected.has(o.id);
              return (
                <button key={o.id} type="button" onClick={() => onToggle(o.id)} style={{
                  appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
                  display: 'flex', alignItems: 'center', gap: 9, padding: '9px 11px', borderRadius: 8,
                  background: on ? c.selectedBg : 'transparent', color: on ? c.selectedText : c.text, fontSize: 13, fontWeight: on ? 600 : 500,
                }}>
                  <span style={{ width: 17, height: 17, borderRadius: 5, flexShrink: 0, border: `1.5px solid ${on ? c.primary : c.border}`, background: on ? c.primary : 'transparent', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                    {on && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>}
                  </span>
                  {o.label}
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

// ─────────── Davet modalı (Satınalma tarafı) ───────────
function SupplierInviteModal({ c, onClose, onOpenRegister }) {
  const isMobile = useIsMobile();
  const cats = window.SUPPLIER_CATEGORIES || [];
  const [company, setCompany] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [picked, setPicked] = React.useState(() => new Set());
  const [created, setCreated] = React.useState(null); // {id, token}
  const [copied, setCopied] = React.useState(false);

  const toggle = (id) => setPicked((p) => { const n = new Set(p); n.has(id) ? n.delete(id) : n.add(id); return n; });

  function create() {
    if (!company.trim()) { alert('Firma adı zorunlu.'); return; }
    if (!email.trim() || !/.+@.+\..+/.test(email)) { alert('Geçerli bir e-posta girin.'); return; }
    const res = window.__suppliers.invite({ company: company.trim(), email: email.trim(), categories: Array.from(picked) });
    setCreated(res);
  }
  function copyLink() {
    const link = inviteLink(created.token);
    if (navigator.clipboard) navigator.clipboard.writeText(link).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1800); });
  }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(2,6,23,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.surface, border: `1px solid ${c.border}`, borderRadius: 18, width: 'min(560px, 100%)', maxHeight: '90vh', overflowY: 'auto', padding: isMobile ? 18 : 26 }}>
        {!created ? (
          <React.Fragment>
            <div style={{ fontSize: 17, fontWeight: 700, color: c.text, marginBottom: 4 }}>Tedarikçi davet et</div>
            <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 18 }}>
              Firmaya e-posta ile <b>tek kullanımlık</b> kayıt bağlantısı gönderilir. Tedarikçi kendi bilgilerini girer; bağlantı kayıt sonrası geçersiz olur.
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <RegField label="Firma adı" required c={c}>
                <input value={company} onChange={(e) => setCompany(e.target.value)} style={inputBox(c)} placeholder="örn. Yıldız Bilişim Ltd. Şti." autoFocus />
              </RegField>
              <RegField label="Davet e-postası" required c={c}>
                <input value={email} onChange={(e) => setEmail(e.target.value)} style={inputBox(c)} placeholder="satis@firma.com" />
              </RegField>
              <div>
                <label style={regLabel(c)}>Hizmet kategorileri (öneri — tedarikçi düzenleyebilir)</label>
                <CategoryMultiSelect options={cats} selected={picked} onToggle={toggle} c={c} placeholder="Kategori arayın ve seçin..." />
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 22 }}>
              <button onClick={create} style={solidBtn(c.primary, isMobile)}>Davet bağlantısı oluştur</button>
              <button onClick={onClose} style={ghostBtn(c, isMobile)}>Vazgeç</button>
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div style={{ width: 46, height: 46, borderRadius: 12, background: 'rgba(16,185,129,0.14)', color: '#0E9F6E', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
            </div>
            <div style={{ fontSize: 17, fontWeight: 700, color: c.text, marginBottom: 4 }}>Davet oluşturuldu</div>
            <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 16 }}>
              <b>{company}</b> firmasına aşağıdaki tek kullanımlık bağlantı <b>{email}</b> adresine e-posta ile gönderilir (prototipte e-posta gönderimi simülasyondur).
            </div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
              <input readOnly value={inviteLink(created.token)} style={{ ...inputBox(c), fontSize: 12 }} onFocus={(e) => e.target.select()} />
              <button onClick={copyLink} style={ghostBtn(c)}>{copied ? 'Kopyalandı ✓' : 'Kopyala'}</button>
            </div>
            <div style={{ fontSize: 11.5, color: c.subtle, marginBottom: 18 }}>🔒 Bu bağlantı DMZ'deki tedarikçi sunucusunda açılır; bir kez kullanılınca geçersiz olur.</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => { onClose(); onOpenRegister(created.token); }} style={solidBtn(c.primary, isMobile)}>Tedarikçi gözüyle aç</button>
              <button onClick={onClose} style={ghostBtn(c, isMobile)}>Kapat</button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

// ─────────── Eksik belge talebi modalı (Satınalma → tedarikçiye link) ───────────
function SupplierDocsRequestModal({ s, c, onClose, onOpenDocs }) {
  const isMobile = useIsMobile();
  const docLabels = window.SUPPLIER_DOC_LABELS || {};
  const missing = Object.keys(docLabels).filter((k) => !(s.docs && s.docs[k]));
  const [created, setCreated] = React.useState(null);
  const [copied, setCopied] = React.useState(false);

  function create() {
    const res = window.__suppliers.requestDocs(s.id);
    setCreated(res);
  }
  function copyLink() {
    const link = inviteLink(created.token);
    if (navigator.clipboard) navigator.clipboard.writeText(link).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1800); });
  }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 250, background: 'rgba(2,6,23,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.surface, border: `1px solid ${c.border}`, borderRadius: 18, width: 'min(520px, 100%)', maxHeight: '90vh', overflowY: 'auto', padding: isMobile ? 18 : 26 }}>
        {!created ? (
          <React.Fragment>
            <div style={{ fontSize: 17, fontWeight: 700, color: c.text, marginBottom: 4 }}>Eksik belge talep et</div>
            <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 16 }}>
              <b>{s.company}</b> firmasına eksik belgeleri yüklemesi için <b>tek kullanımlık</b> bir bağlantı gönderilir. Tedarikçi DMZ portalında yalnızca eksik belgeleri yükler.
            </div>
            {missing.length === 0 ? (
              <div style={{ fontSize: 13, color: '#0E9F6E', marginBottom: 16 }}>Bu tedarikçinin eksik belgesi yok.</div>
            ) : (
              <div style={{ marginBottom: 18 }}>
                <div style={{ fontSize: 11.5, color: c.muted, marginBottom: 8 }}>Talep edilecek eksik belgeler:</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {missing.map((k) => <span key={k} style={{ padding: '4px 10px', borderRadius: 999, background: c.chipBg, color: c.text, fontSize: 12 }}>{docLabels[k]}</span>)}
                </div>
              </div>
            )}
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={create} disabled={missing.length === 0} style={{ ...solidBtn(c.primary, isMobile), opacity: missing.length === 0 ? 0.5 : 1 }}>Belge talebi bağlantısı oluştur</button>
              <button onClick={onClose} style={ghostBtn(c, isMobile)}>Vazgeç</button>
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div style={{ fontSize: 17, fontWeight: 700, color: c.text, marginBottom: 4 }}>Belge talebi oluşturuldu</div>
            <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 14 }}>
              Bağlantı <b>{s.email || 'tedarikçi e-postası'}</b> adresine gönderilir (prototipte simülasyon).
            </div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
              <input readOnly value={inviteLink(created.token)} style={{ ...inputBox(c), fontSize: 12 }} onFocus={(e) => e.target.select()} />
              <button onClick={copyLink} style={ghostBtn(c)}>{copied ? 'Kopyalandı ✓' : 'Kopyala'}</button>
            </div>
            <div style={{ fontSize: 11.5, color: c.subtle, marginBottom: 18 }}>🔒 DMZ portalında açılır; yükleme sonrası geçersiz olur.</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => { onClose(); onOpenDocs(created.token); }} style={solidBtn(c.primary, isMobile)}>Tedarikçi gözüyle aç</button>
              <button onClick={onClose} style={ghostBtn(c, isMobile)}>Kapat</button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

// ─────────── Belge yükleme satırı (simüle) ───────────
function DocUploadRow({ docKey, label, c, value, onChange, accent }) {
  const onFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    if (f.size > 5 * 1024 * 1024) { alert('Dosya 5 MB\'tan küçük olmalı.'); return; }
    onChange({ uploaded: true, fileName: f.name });
  };
  const up = value && value.uploaded;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 11px', border: `1px solid ${up ? '#0E9F6E55' : c.border}`, borderRadius: 10, background: up ? 'rgba(16,185,129,0.06)' : c.inputBg }}>
      <span style={{ width: 20, height: 20, borderRadius: 6, flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: up ? 'rgba(16,185,129,0.16)' : c.chipBg, color: up ? '#0E9F6E' : c.subtle }}>
        {up
          ? <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
          : <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /></svg>}
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 500, color: c.text }}>{label}{accent ? ' *' : ''}</div>
        {up && <div style={{ fontSize: 11, color: c.muted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value.fileName}</div>}
      </div>
      <label style={{ ...ghostBtn(c), padding: '7px 12px', fontSize: 12, cursor: 'pointer', whiteSpace: 'nowrap' }}>
        {up ? 'Değiştir' : 'Dosya seç'}
        <input type="file" accept=".pdf,.jpg,.jpeg,.png" onChange={onFile} style={{ display: 'none' }} />
      </label>
    </div>
  );
}

// ─────────── Tedarikçi kayıt sayfası (dış / DMZ — tam ekran overlay) ───────────
function SupplierRegisterOverlay({ token, mode = 'register', onClose }) {
  const c = catalogTheme(false); // dış yüz her zaman açık tema
  const isMobile = useIsMobile();
  const all = useSuppliersSnapshot();
  const docsMode = mode === 'docs';
  const rec = docsMode ? all.find((s) => s.docToken === token) : all.find((s) => s.inviteToken === token);
  const cats = window.SUPPLIER_CATEGORIES || [];
  const docLabels = window.SUPPLIER_DOC_LABELS || {};

  const [done, setDone] = React.useState(false);
  // Form state
  const [f, setF] = React.useState(() => ({
    company: (rec && rec.company) || '', type: 'ltd',
    taxOffice: '', taxNo: '', mersisNo: '', tradeRegNo: '', website: '',
    address: '', city: '', country: 'Türkiye',
    phone: '', gsm: '', email: (rec && rec.email) || '',
    contactName: '', contactTitle: '', contactPhone: '', contactEmail: '',
    paymentTermDays: '', currency: 'TRY', supplyType: '', iban: '', bankName: '',
  }));
  const [picked, setPicked] = React.useState(() => new Set((rec && rec.categories) || []));
  const [docs, setDocs] = React.useState({});       // {key:{uploaded,fileName}}
  const [kvkk, setKvkk] = React.useState(false);
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const toggleCat = (id) => setPicked((p) => { const n = new Set(p); n.has(id) ? n.delete(id) : n.add(id); return n; });

  // Token durumu
  const expired = !rec || (docsMode ? rec.docTokenUsed : rec.inviteUsed);

  // Belge tamamlama (self-servis) — yalnızca eksik belgeler yüklenir, docToken ölür
  function submitDocs() {
    const keys = Object.keys(docs).filter((k) => docs[k] && docs[k].uploaded);
    if (keys.length === 0) { alert('Lütfen en az bir belge yükleyin.'); return; }
    const docBool = {}; const docFiles = {};
    keys.forEach((k) => { docBool[k] = true; if (docs[k].fileName) docFiles[k] = docs[k].fileName; });
    window.__suppliers.completeDocs(rec.id, { docs: docBool, docFiles });
    setDone(true);
  }

  function submit() {
    if (!f.company.trim()) { alert('Firma ünvanı zorunlu.'); return; }
    if (!f.taxOffice.trim() || !f.taxNo.trim()) { alert('Vergi dairesi ve vergi no zorunlu.'); return; }
    if (!f.address.trim() || !f.city.trim()) { alert('Adres ve şehir zorunlu.'); return; }
    if (!f.email.trim() || !/.+@.+\..+/.test(f.email)) { alert('Geçerli bir e-posta girin.'); return; }
    if (!f.contactName.trim()) { alert('Muhatap kişi adı zorunlu.'); return; }
    if (picked.size === 0) { alert('En az bir hizmet kategorisi seçin.'); return; }
    if (!String(f.paymentTermDays).trim() || (parseInt(String(f.paymentTermDays).replace(/[^\d]/g, ''), 10) || 0) <= 0) { alert('Vade süresi (gün) zorunlu — geçerli bir gün sayısı girin.'); return; }
    if (!f.currency) { alert('Para birimi zorunlu.'); return; }
    if (!f.supplyType) { alert('Çalışma şekli seçimi zorunlu.'); return; }
    if (!f.bankName.trim()) { alert('Banka zorunlu.'); return; }
    if (!f.iban.trim()) { alert('IBAN zorunlu.'); return; }
    if (!docs.nda || !docs.nda.uploaded) { alert('İmzalı Gizlilik Sözleşmesi (NDA) yüklemek zorunludur.'); return; }
    if (!kvkk) { alert('Devam etmek için KVKK aydınlatma metnini onaylamalısınız.'); return; }
    const docBool = {}; const docFiles = {};
    Object.keys(docs).forEach((k) => { docBool[k] = !!(docs[k] && docs[k].uploaded); if (docs[k] && docs[k].fileName) docFiles[k] = docs[k].fileName; });
    window.__suppliers.completeRegistration(rec.id, {
      ...f, shortName: f.company.trim(),
      paymentTermDays: parseInt(String(f.paymentTermDays).replace(/[^\d]/g, ''), 10) || 0,
      categories: Array.from(picked), docs: docBool, docFiles, kvkkAccepted: true,
    });
    setDone(true);
  }

  const banner = (
    <div style={{ background: '#0F172A', color: '#E2E8F0', padding: '10px 16px', display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5, justifyContent: 'center', textAlign: 'center' }}>
      <span style={{ display: 'flex' }}><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#34D399" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg></span>
      <span>Tedarikçi Kayıt Portalı · <b>{SUPPLIER_PORTAL_HOST.replace('https://', '')}</b> — bu sayfa DMZ'deki ayrı sunucuda çalışır, iç sisteme kapalıdır</span>
    </div>
  );

  const card = { background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, padding: isMobile ? 16 : 22, marginBottom: 16 };
  const grid = { display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 300, background: c.bg, overflowY: 'auto', fontFamily: 'Inter, system-ui, sans-serif' }}>
      {banner}
      {/* Üst bar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: isMobile ? '14px 16px' : '16px 28px', borderBottom: `1px solid ${c.border}`, background: c.surface }}>
        <div style={{ width: 34, height: 34, borderRadius: 9, background: c.primary, color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>T</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: c.text }}>{docsMode ? 'Eksik Belgeleri Tamamla' : 'Tedarikçi Kayıt Formu'}</div>
          <div style={{ fontSize: 11.5, color: c.muted }}>{docsMode ? (rec ? rec.company : '') : 'Bilgilerinizi eksiksiz doldurun'}</div>
        </div>
        <button onClick={onClose} style={{ ...ghostBtn(c), padding: '8px 14px' }} title="Önizlemeyi kapat (Satınalma görünümüne dön)">Önizlemeyi kapat</button>
      </div>

      <div style={{ maxWidth: 860, margin: '0 auto', padding: isMobile ? '20px 16px 48px' : '28px 24px 64px' }}>
        {done ? (
          <div style={{ ...card, textAlign: 'center', padding: 48 }}>
            <div style={{ width: 52, height: 52, borderRadius: 14, background: 'rgba(16,185,129,0.14)', color: '#0E9F6E', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
            </div>
            <div style={{ fontSize: 18, fontWeight: 700, color: c.text, marginBottom: 8 }}>{docsMode ? 'Belgeleriniz alındı' : 'Kaydınız alındı'}</div>
            <div style={{ fontSize: 13.5, color: c.muted, maxWidth: 480, margin: '0 auto' }}>
              {docsMode
                ? <span>Yüklediğiniz belgeler satınalma birimine iletildi. Bu belge tamamlama bağlantısı artık <b>geçersizdir</b>.</span>
                : <span><b>{f.company}</b> tedarikçi kaydı tamamlandı. Satınalma birimi bilgilerinizi inceleyecek. Bu kayıt bağlantısı artık <b>geçersizdir</b>.</span>}
            </div>
            <button onClick={onClose} style={{ ...solidBtn(c.primary, false), marginTop: 20 }}>Kapat</button>
          </div>
        ) : expired ? (
          <div style={{ ...card, textAlign: 'center', padding: 48 }}>
            <div style={{ width: 52, height: 52, borderRadius: 14, background: 'rgba(239,68,68,0.12)', color: c.danger, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9" /><path d="M15 9l-6 6M9 9l6 6" /></svg>
            </div>
            <div style={{ fontSize: 17, fontWeight: 700, color: c.text, marginBottom: 8 }}>Bağlantı geçersiz</div>
            <div style={{ fontSize: 13.5, color: c.muted, maxWidth: 460, margin: '0 auto' }}>
              Bu kayıt bağlantısı {rec && rec.inviteUsed ? 'daha önce kullanılmış' : 'bulunamadı veya süresi dolmuş'}. Güvenlik gereği davet bağlantıları yalnızca <b>bir kez</b> kullanılabilir. Lütfen satınalma birimi ile iletişime geçin.
            </div>
            <button onClick={onClose} style={{ ...solidBtn(c.primary, false), marginTop: 20 }}>Kapat</button>
          </div>
        ) : docsMode ? (
          <React.Fragment>
            <div style={card}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: c.text, marginBottom: 4 }}>Eksik belgelerinizi yükleyin</div>
              <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 16 }}>
                Satınalma birimi aşağıdaki belgeleri talep etti. Yükledikten sonra bu bağlantı geçersiz olur. PDF/JPG/PNG, dosya başına en çok 5 MB.
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {Object.keys(docLabels).map((k) => {
                  const already = rec && rec.docs && rec.docs[k];
                  if (already) return null; // yüklü olanları gösterme
                  return (
                    <div key={k}>
                      {k === 'nda' && (
                        <div style={{ marginBottom: 6 }}>
                          <button onClick={() => downloadNda(rec ? rec.company : '')} style={{ ...ghostBtn(c), padding: '7px 12px', fontSize: 12 }}>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: 6 }}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="M7 10l5 5 5-5M12 15V3" /></svg>
                            Gizlilik Sözleşmesini indir
                          </button>
                        </div>
                      )}
                      <DocUploadRow docKey={k} label={docLabels[k]} c={c} value={docs[k]} onChange={(v) => setDocs((p) => ({ ...p, [k]: v }))} />
                    </div>
                  );
                })}
                {Object.keys(docLabels).every((k) => rec && rec.docs && rec.docs[k]) && (
                  <div style={{ fontSize: 13, color: '#0E9F6E', padding: '8px 0' }}>Tüm belgeleriniz zaten yüklü — eksik belge yok.</div>
                )}
              </div>
            </div>
            <button onClick={submitDocs} style={{ ...solidBtn('#0E9F6E', isMobile), width: isMobile ? '100%' : 'auto', padding: '13px 26px' }}>Belgeleri Gönder</button>
            <div style={{ fontSize: 11.5, color: c.subtle, marginTop: 10 }}>Gönderdiğinizde bu bağlantı geçersiz hale gelir.</div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            {/* Firma kimliği */}
            <div style={card}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: c.text, marginBottom: 14 }}>Firma Kimliği</div>
              <div style={grid}>
                <RegField label="Resmi ünvan" required c={c} full><input value={f.company} onChange={(e) => set('company', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="Firma tipi" c={c}>
                  <select value={f.type} onChange={(e) => set('type', e.target.value)} style={inputBox(c)}>
                    {Object.keys(window.SUPPLIER_TYPE_LABEL || {}).map((k) => <option key={k} value={k}>{window.SUPPLIER_TYPE_LABEL[k]}</option>)}
                  </select>
                </RegField>
                <RegField label="Web sitesi" c={c}><input value={f.website} onChange={(e) => set('website', e.target.value)} style={inputBox(c)} placeholder="firma.com" /></RegField>
                <RegField label="Vergi dairesi" required c={c}><input value={f.taxOffice} onChange={(e) => set('taxOffice', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="Vergi no" required c={c}><input value={f.taxNo} onChange={(e) => set('taxNo', e.target.value)} style={inputBox(c)} inputMode="numeric" /></RegField>
                <RegField label="MERSİS no" c={c}><input value={f.mersisNo} onChange={(e) => set('mersisNo', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="Ticaret sicil no" c={c}><input value={f.tradeRegNo} onChange={(e) => set('tradeRegNo', e.target.value)} style={inputBox(c)} /></RegField>
              </div>
            </div>

            {/* İletişim */}
            <div style={card}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: c.text, marginBottom: 14 }}>İletişim</div>
              <div style={grid}>
                <RegField label="Adres" required c={c} full><input value={f.address} onChange={(e) => set('address', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="Şehir" required c={c}><input value={f.city} onChange={(e) => set('city', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="Ülke" c={c}><input value={f.country} onChange={(e) => set('country', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="Telefon" c={c}><input value={f.phone} onChange={(e) => set('phone', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="GSM" c={c}><input value={f.gsm} onChange={(e) => set('gsm', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="Genel e-posta" required c={c}><input value={f.email} onChange={(e) => set('email', e.target.value)} style={inputBox(c)} /></RegField>
                <div style={{ gridColumn: isMobile ? 'auto' : '1 / -1', height: 1, background: c.borderSoft, margin: '4px 0' }} />
                <RegField label="Muhatap kişi" required c={c}><input value={f.contactName} onChange={(e) => set('contactName', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="Muhatap ünvanı" c={c}><input value={f.contactTitle} onChange={(e) => set('contactTitle', e.target.value)} style={inputBox(c)} placeholder="örn. Satış Müdürü" /></RegField>
                <RegField label="Muhatap telefon" c={c}><input value={f.contactPhone} onChange={(e) => set('contactPhone', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="Muhatap e-posta" c={c}><input value={f.contactEmail} onChange={(e) => set('contactEmail', e.target.value)} style={inputBox(c)} /></RegField>
              </div>
            </div>

            {/* Ticari */}
            <div style={card}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: c.text, marginBottom: 14 }}>Ticari Bilgiler</div>
              <label style={regLabel(c)}>Hizmet / ürün kategorileri *</label>
              <div style={{ marginBottom: 16 }}>
                <CategoryMultiSelect options={cats} selected={picked} onToggle={toggleCat} c={c} placeholder="Hizmet verdiğiniz kategorileri arayın ve seçin..." />
              </div>
              <div style={grid}>
                <RegField label="Vade süresi (gün)" required c={c}><input value={f.paymentTermDays} onChange={(e) => set('paymentTermDays', e.target.value)} style={inputBox(c)} inputMode="numeric" placeholder="örn. 30" /></RegField>
                <RegField label="Para birimi" required c={c}>
                  <select value={f.currency} onChange={(e) => set('currency', e.target.value)} style={inputBox(c)}><option>TRY</option><option>USD</option><option>EUR</option></select>
                </RegField>
                <RegField label="Çalışma şekli" required c={c}>
                  <select value={f.supplyType} onChange={(e) => set('supplyType', e.target.value)} style={{ ...inputBox(c), color: f.supplyType ? c.text : c.subtle }}>
                    <option value="">Çalışma şeklinizi seçiniz</option>
                    {Object.keys(window.SUPPLY_TYPE_LABEL || {}).map((k) => <option key={k} value={k}>{window.SUPPLY_TYPE_LABEL[k]}</option>)}
                  </select>
                </RegField>
                <RegField label="Banka" required c={c}><input value={f.bankName} onChange={(e) => set('bankName', e.target.value)} style={inputBox(c)} /></RegField>
                <RegField label="IBAN" required c={c} full><input value={f.iban} onChange={(e) => set('iban', e.target.value)} style={inputBox(c)} placeholder="TR.. .... .... .... .... .... .." /></RegField>
              </div>
            </div>

            {/* Belgeler + NDA */}
            <div style={card}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: c.text, marginBottom: 4 }}>Belgeler</div>
              <div style={{ fontSize: 12, color: c.muted, marginBottom: 14 }}>PDF/JPG/PNG, dosya başına en çok 5 MB.</div>

              {/* NDA özel kutusu */}
              <div style={{ border: `1px solid ${c.primary}`, borderRadius: 12, padding: 14, marginBottom: 14, background: c.selectedBg }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: c.text, marginBottom: 4 }}>Gizlilik Sözleşmesi (NDA) — zorunlu</div>
                <div style={{ fontSize: 12, color: c.muted, marginBottom: 10 }}>Matbu sözleşmeyi indirin, yetkili imza/kaşe ile imzalayıp tarayın ve buraya yükleyin.</div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 10 }}>
                  <button onClick={() => downloadNda(f.company)} style={ghostBtn(c)}>
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: 6 }}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="M7 10l5 5 5-5M12 15V3" /></svg>
                    Gizlilik Sözleşmesini indir
                  </button>
                </div>
                <DocUploadRow docKey="nda" label="İmzalı NDA" accent c={c} value={docs.nda} onChange={(v) => setDocs((p) => ({ ...p, nda: v }))} />
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {Object.keys(docLabels).filter((k) => k !== 'nda').map((k) => (
                  <DocUploadRow key={k} docKey={k} label={docLabels[k]} c={c} value={docs[k]} onChange={(v) => setDocs((p) => ({ ...p, [k]: v }))} />
                ))}
              </div>
            </div>

            {/* KVKK + gönder */}
            <div style={card}>
              <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', fontSize: 12.5, color: c.text }}>
                <input type="checkbox" checked={kvkk} onChange={(e) => setKvkk(e.target.checked)} style={{ marginTop: 2 }} />
                <span>Paylaştığım bilgilerin 6698 sayılı <b>KVKK</b> kapsamında işlenmesine ilişkin aydınlatma metnini okudum, onaylıyorum.</span>
              </label>
            </div>

            <button onClick={submit} style={{ ...solidBtn('#0E9F6E', isMobile), width: isMobile ? '100%' : 'auto', padding: '13px 26px' }}>Kaydı Tamamla</button>
            <div style={{ fontSize: 11.5, color: c.subtle, marginTop: 10 }}>Gönderdiğinizde bu davet bağlantısı geçersiz hale gelir.</div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SupplierInviteModal, SupplierDocsRequestModal, SupplierRegisterOverlay, DocUploadRow, CategoryMultiSelect, downloadNda, ndaHtml, inviteLink });
