// rfq.jsx — Teklif İsteme (RFQ) + Tedarikçi Teklif Formu (Faz 4 / Parça 4.3)
// Satınalma onaylı talebe karşı tedarikçilerden (tek tek veya kategori bazlı) teklif ister.
// Her tedarikçiye tek kullanımlık link gider → DMZ'deki teklif formu (KDV'siz fiyat, KDV, stok, vade).
// Teklif karşılaştırma + kazanan seçimi 4.4'te. Ortak stiller admin-approvals.jsx'te global.

const RFQ_DEFAULT_NOTE = 'Ekteki ürün(ler) ile ilgili fiyat teklifinizi rica ederiz.';
const RFQ_PORTAL_HOST = 'https://tedarikci.sirketiniz.com.tr';
function quoteLink(token) { return `${RFQ_PORTAL_HOST}/teklif?davet=${token}`; }

// Kritik belgesi eksik mi (teklif isterken uyarı için — engellemez)
function rfqCriticalMissing(s) {
  const d = s.docs || {};
  return !(d.taxPlate && d.signatureCirc && d.nda);
}

// ─────────── Teklif İsteme Modalı (satınalma) ───────────
function RfqRequestModal({ req, c, onClose, onOpenQuote }) {
  const isMobile = useIsMobile();
  const suppliers = (useSuppliersSnapshot() || []).filter((s) => s.status === 'active');
  const rfqs = useRfqsSnapshot();
  const cats = window.SUPPLIER_CATEGORIES || [];
  const existing = rfqs.find((r) => r.requestId === req.id);
  const alreadyIds = new Set((existing ? existing.invitations : []).map((i) => i.supplierId));

  const [selected, setSelected] = React.useState(() => new Set());
  const [note, setNote] = React.useState(RFQ_DEFAULT_NOTE);
  const [q, setQ] = React.useState('');
  const [done, setDone] = React.useState(false);

  const selectableSuppliers = suppliers.filter((s) => !alreadyIds.has(s.id));
  const term = q.trim().toLowerCase();
  const shown = term ? selectableSuppliers.filter((s) => `${s.company} ${s.city}`.toLowerCase().includes(term)) : selectableSuppliers;

  const toggle = (id) => setSelected((p) => { const n = new Set(p); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const suppliersInCat = (catId) => selectableSuppliers.filter((s) => (s.categories || []).includes(catId)).map((s) => s.id);
  const catAllSelected = (catId) => { const ids = suppliersInCat(catId); return ids.length > 0 && ids.every((id) => selected.has(id)); };
  const toggleCat = (catId) => {
    const ids = suppliersInCat(catId);
    setSelected((p) => {
      const n = new Set(p);
      const all = ids.length > 0 && ids.every((id) => n.has(id));
      ids.forEach((id) => { all ? n.delete(id) : n.add(id); });
      return n;
    });
  };

  const items = (req.items || []).filter((it) => it.state !== 'removed');
  const selectedMissingDocs = suppliers.filter((s) => selected.has(s.id) && rfqCriticalMissing(s));

  function send() {
    if (selected.size === 0) { alert('En az bir tedarikçi seçin.'); return; }
    window.__rfqs.createRFQ({
      requestId: req.id, supplierIds: Array.from(selected), note: note.trim() || RFQ_DEFAULT_NOTE,
      items: items.map((it) => ({ name: it.name, qty: it.qty || 1, priceUnit: it.priceUnit || null })),
      by: (window.__user && window.__user.id), byName: (window.__user && window.__user.name) || 'Satınalma',
    });
    setDone(true);
  }

  // 'done' ekranında güncel RFQ'dan davet linklerini oku
  const justRfq = rfqs.find((r) => r.requestId === req.id);
  const newInvites = justRfq ? justRfq.invitations.filter((i) => selected.has(i.supplierId)) : [];

  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(640px, 100%)', maxHeight: '90vh', overflowY: 'auto', padding: isMobile ? 18 : 26 }}>
        {!done ? (
          <React.Fragment>
            <div style={{ fontSize: 17, fontWeight: 700, color: c.text, marginBottom: 4 }}>Teklif iste</div>
            <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 16 }}>
              Talep <b>{req.id}</b> için tedarikçilerden fiyat teklifi isteyin. Tek tek veya kategori seçerek birden çok firmaya gönderebilirsiniz.
            </div>

            {/* Kategori bazlı hızlı seçim */}
            <div style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>Kategori bazlı seç (tüm aktif firmalar)</div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {cats.map((cat) => {
                  const ids = suppliersInCat(cat.id);
                  if (ids.length === 0) return null;
                  const on = catAllSelected(cat.id);
                  return (
                    <button key={cat.id} type="button" onClick={() => toggleCat(cat.id)} style={{
                      appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', padding: '6px 11px', borderRadius: 999, fontSize: 12, fontWeight: 500,
                      border: `1px solid ${on ? c.primary : c.border}`, background: on ? c.selectedBg : 'transparent', color: on ? c.selectedText : c.muted,
                    }}>{on ? '✓ ' : ''}{cat.label} ({ids.length})</button>
                  );
                })}
              </div>
            </div>

            {/* Firma arama + liste */}
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Firma ara..." style={{ ...inputBox(c), marginBottom: 8 }} />
            <div style={{ maxHeight: 240, overflowY: 'auto', border: `1px solid ${c.border}`, borderRadius: 10, padding: 6, marginBottom: 8 }}>
              {selectableSuppliers.length === 0 && <div style={{ padding: 12, fontSize: 12.5, color: c.muted }}>Davet edilebilecek aktif tedarikçi yok (hepsi zaten davet edilmiş olabilir).</div>}
              {shown.map((s) => {
                const on = selected.has(s.id);
                const warn = rfqCriticalMissing(s);
                return (
                  <button key={s.id} type="button" onClick={() => toggle(s.id)} style={{
                    appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', width: '100%',
                    display: 'flex', alignItems: 'center', gap: 10, padding: '9px 10px', borderRadius: 8,
                    background: on ? c.selectedBg : 'transparent',
                  }}>
                    <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>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500, color: c.text }}>{s.company}</div>
                      <div style={{ fontSize: 11.5, color: c.muted }}>{(s.categories || []).map(window.supplierCategoryLabel).join(', ')} · {s.city || '—'}</div>
                    </div>
                    {warn && <span title="Kritik belgesi eksik" style={{ fontSize: 11, color: '#B45309', whiteSpace: 'nowrap' }}>⚠ belge eksik</span>}
                  </button>
                );
              })}
            </div>

            {/* Zaten davet edilmişler */}
            {alreadyIds.size > 0 && (
              <div style={{ fontSize: 11.5, color: c.subtle, marginBottom: 10 }}>Zaten davet edilmiş: {Array.from(alreadyIds).map((id) => (existing.invitations.find((i) => i.supplierId === id) || {}).supplierName).join(', ')}</div>
            )}

            {/* Belge uyarısı (engellemez) */}
            {selectedMissingDocs.length > 0 && (
              <div style={{ background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.4)', borderRadius: 10, padding: 10, marginBottom: 12, fontSize: 12, color: '#B45309' }}>
                ⚠ Seçtiğiniz {selectedMissingDocs.length} firmada kritik belge (vergi levhası / imza sirküleri / NDA) eksik. Yine de teklif isteyebilirsiniz.
              </div>
            )}

            {/* Not */}
            <div style={{ marginBottom: 8 }}>
              <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6, display: 'block' }}>Tedarikçiye gidecek not</label>
              <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={2} style={{ ...inputBox(c), resize: 'vertical' }} />
            </div>

            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              <button onClick={send} style={solidBtn(c.primary, isMobile)}>{selected.size > 0 ? `${selected.size} firmaya teklif iste` : 'Teklif iste'}</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="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" /></svg>
            </div>
            <div style={{ fontSize: 17, fontWeight: 700, color: c.text, marginBottom: 4 }}>Teklif daveti gönderildi</div>
            <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 16 }}>Aşağıdaki firmalara tek kullanımlık teklif bağlantısı e-posta ile iletildi (prototipte simülasyon).</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {newInvites.map((inv) => (
                <div key={inv.token} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px', border: `1px solid ${c.border}`, borderRadius: 10, flexWrap: 'wrap' }}>
                  <span style={{ flex: 1, minWidth: 120, fontSize: 13, color: c.text }}>{inv.supplierName}</span>
                  <button onClick={() => { if (navigator.clipboard) navigator.clipboard.writeText(quoteLink(inv.token)); }} style={{ ...ghostBtn(c), padding: '6px 10px', fontSize: 12 }}>Linki kopyala</button>
                  <button onClick={() => { onClose(); onOpenQuote(inv.token); }} style={{ ...solidBtn(c.primary, false), padding: '6px 12px', fontSize: 12 }}>Tedarikçi gözüyle aç</button>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
              <button onClick={onClose} style={ghostBtn(c, isMobile)}>Kapat</button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

// ─────────── Tedarikçi Teklif Formu (dış / DMZ — tam ekran) ───────────
function QuoteFormOverlay({ token, onClose }) {
  const c = catalogTheme(false);
  const isMobile = useIsMobile();
  const rfqs = useRfqsSnapshot();
  let rfq = null, inv = null;
  rfqs.forEach((r) => { const f = r.invitations.find((i) => i.token === token); if (f) { rfq = r; inv = f; } });
  const expired = !inv || inv.used;

  const [done, setDone] = React.useState(false);
  const [lines, setLines] = React.useState(() => (rfq ? rfq.items.map((it) => ({ name: it.name, qty: it.qty || 1, priceUnit: it.priceUnit || null, unitNet: '' })) : []));
  const [vatRate, setVatRate] = React.useState('20');
  const [stock, setStock] = React.useState('');
  const [validUntil, setValidUntil] = React.useState('');
  const [paymentTerm, setPaymentTerm] = React.useState('');
  const [note, setNote] = React.useState('');
  const [doc, setDoc] = React.useState(null);

  const setUnit = (i, v) => setLines((p) => p.map((l, idx) => idx === i ? { ...l, unitNet: v } : l));
  const num = (v) => parseFloat(String(v).replace(/[^\d.,]/g, '').replace(',', '.')) || 0;
  const netTotal = lines.reduce((s, l) => s + num(l.unitNet) * (l.qty || 1), 0);
  const vatAmount = netTotal * (num(vatRate) / 100);
  const gross = netTotal + vatAmount;

  function submit() {
    if (lines.some((l) => num(l.unitNet) <= 0)) { alert('Lütfen her kalem için KDV\'siz birim fiyat girin.'); return; }
    if (!stock.trim()) { alert('Stok bilgisi zorunlu.'); return; }
    if (!validUntil) { alert('Teklif geçerlilik tarihi zorunlu.'); return; }
    if (!paymentTerm.trim()) { alert('Ödeme vadesi zorunlu (örn. 30 gün).'); return; }
    if (note.length > 1000) { alert('Not 1000 karakteri geçemez.'); return; }
    window.__rfqs.submitQuote(token, {
      lines: lines.map((l) => ({ name: l.name, qty: l.qty, unitNet: num(l.unitNet) })),
      vatRate: num(vatRate), netTotal, vatAmount, gross,
      stock: stock.trim(), validUntil, paymentTerm: paymentTerm.trim(), note: note.trim(), docFileName: doc && doc.fileName,
    });
    setDone(true);
  }

  const card = { background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, padding: isMobile ? 16 : 22, marginBottom: 16 };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 300, background: c.bg, overflowY: 'auto', fontFamily: 'Inter, system-ui, sans-serif' }}>
      <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 Teklif Portalı · <b>{RFQ_PORTAL_HOST.replace('https://', '')}</b> — DMZ'deki ayrı sunucu, iç sisteme kapalı</span>
      </div>
      <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 }}>₺</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: c.text }}>Fiyat Teklifi Formu</div>
          <div style={{ fontSize: 11.5, color: c.muted }}>{inv ? inv.supplierName : ''}</div>
        </div>
        <button onClick={onClose} style={{ ...ghostBtn(c), padding: '8px 14px' }}>Önizlemeyi kapat</button>
      </div>

      <div style={{ maxWidth: 760, 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 }}>Teklifiniz alındı</div>
            <div style={{ fontSize: 13.5, color: c.muted, maxWidth: 460, margin: '0 auto' }}>Teklifiniz satınalma birimine iletildi. Bu teklif bağlantısı artık <b>geçersizdir</b>.</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 teklif bağlantısı {inv && inv.used ? 'daha önce kullanılmış' : 'bulunamadı'}. Güvenlik gereği bağlantılar yalnızca bir kez kullanılabilir.</div>
            <button onClick={onClose} style={{ ...solidBtn(c.primary, false), marginTop: 20 }}>Kapat</button>
          </div>
        ) : (
          <React.Fragment>
            {/* Talep notu + kalemler */}
            <div style={card}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: c.text, marginBottom: 8 }}>Talep edilen kalemler</div>
              {rfq.note && <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 12, padding: 10, background: c.chipBg, borderRadius: 8 }}>{rfq.note}</div>}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {lines.map((l, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                    <div style={{ flex: 1, minWidth: 160 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: c.text }}>{l.name}</div>
                      <div style={{ fontSize: 12, color: c.muted }}>{l.qty} adet{l.priceUnit ? ` · ${l.priceUnit}` : ''}</div>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                      <label style={{ fontSize: 11, color: c.muted, marginBottom: 4 }}>KDV'siz birim fiyat (₺)</label>
                      <input value={l.unitNet} onChange={(e) => setUnit(i, e.target.value)} style={{ ...inputBox(c), width: 160 }} inputMode="decimal" placeholder="0,00" />
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Teklif detayları */}
            <div style={card}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: c.text, marginBottom: 14 }}>Teklif detayları</div>
              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>KDV oranı (%)</label>
                  <select value={vatRate} onChange={(e) => setVatRate(e.target.value)} style={inputBox(c)}><option value="0">%0</option><option value="1">%1</option><option value="10">%10</option><option value="20">%20</option></select>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>Stok bilgisi *</label>
                  <input value={stock} onChange={(e) => setStock(e.target.value)} style={inputBox(c)} placeholder="örn. Stokta / 2 hafta tedarik" />
                </div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>Teklif geçerlilik tarihi *</label>
                  <input type="date" value={validUntil} onChange={(e) => setValidUntil(e.target.value)} style={inputBox(c)} />
                </div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>Ödeme vadesi *</label>
                  <input value={paymentTerm} onChange={(e) => setPaymentTerm(e.target.value)} style={inputBox(c)} placeholder="örn. 30 gün / peşin" />
                </div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>Teklif dokümanı (ops.)</label>
                  {window.DocUploadRow
                    ? <window.DocUploadRow docKey="quote" label={doc ? doc.fileName : 'Doküman ekle'} c={c} value={doc} onChange={setDoc} />
                    : null}
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gridColumn: isMobile ? 'auto' : '1 / -1' }}>
                  <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>Not (en çok 1000 karakter)</label>
                  <textarea value={note} onChange={(e) => setNote(e.target.value.slice(0, 1000))} rows={3} style={{ ...inputBox(c), resize: 'vertical' }} placeholder="Eklemek istediğiniz açıklama..." />
                  <div style={{ fontSize: 11, color: c.subtle, textAlign: 'right', marginTop: 4 }}>{note.length}/1000</div>
                </div>
              </div>

              {/* Özet */}
              <div style={{ marginTop: 16, padding: 14, background: c.chipBg, borderRadius: 10, display: 'flex', flexDirection: 'column', gap: 6 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}><span style={{ color: c.muted }}>KDV'siz toplam</span><span style={{ color: c.text, fontWeight: 600 }}>{formatTL(Math.round(netTotal))}</span></div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}><span style={{ color: c.muted }}>KDV ({num(vatRate)}%)</span><span style={{ color: c.text }}>{formatTL(Math.round(vatAmount))}</span></div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 15, fontWeight: 700, borderTop: `1px solid ${c.border}`, paddingTop: 6 }}><span style={{ color: c.text }}>KDV dahil toplam</span><span style={{ color: c.text }}>{formatTL(Math.round(gross))}</span></div>
              </div>
            </div>

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

// ─────────── Teklif Durumu kartı (satınalma talep detayında) ───────────
function RfqStatusCard({ req, c }) {
  const rfqs = useRfqsSnapshot();
  const rfq = rfqs.find((r) => r.requestId === req.id);
  if (!rfq) return null;
  const received = rfq.invitations.filter((i) => i.quote).length;
  return (
    <div style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, padding: 18, marginBottom: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: c.text }}>Teklif durumu</div>
        <span style={{ fontSize: 12, color: c.muted }}>{rfq.invitations.length} davet · <b style={{ color: received > 0 ? '#0E9F6E' : c.muted }}>{received} teklif geldi</b></span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {rfq.invitations.map((inv) => (
          <div key={inv.token} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 11px', border: `1px solid ${c.border}`, borderRadius: 10, flexWrap: 'wrap' }}>
            <span style={{ flex: 1, minWidth: 140, fontSize: 13, color: c.text }}>{inv.supplierName}</span>
            {inv.quote ? (
              <React.Fragment>
                <span style={{ fontSize: 13, fontWeight: 600, color: c.text }}>{formatTL(Math.round(inv.quote.netTotal))} <span style={{ fontSize: 11, color: c.muted, fontWeight: 400 }}>+KDV</span></span>
                <span style={{ padding: '2px 9px', borderRadius: 999, fontSize: 11, fontWeight: 600, background: 'rgba(16,185,129,0.14)', color: '#0E9F6E' }}>Teklif geldi</span>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <span style={{ padding: '2px 9px', borderRadius: 999, fontSize: 11, fontWeight: 600, background: 'rgba(245,158,11,0.14)', color: '#B45309' }}>Bekliyor</span>
                <button onClick={() => window.__openQuoteForm && window.__openQuoteForm(inv.token)} style={{ ...ghostBtn(c), padding: '5px 10px', fontSize: 11.5 }}>Tedarikçi gözüyle aç</button>
              </React.Fragment>
            )}
          </div>
        ))}
      </div>
      <div style={{ fontSize: 11.5, color: c.subtle, marginTop: 10 }}>Teklif karşılaştırma ve kazanan seçimi sıradaki adımda (4.4) eklenecek.</div>
    </div>
  );
}

// ─────────── Teklif Karşılaştırma + Kazanan Seçimi (Faz 4 / Parça 4.4) ───────────
function RfqCompareCard({ req, c }) {
  const isMobile = useIsMobile();
  const rfqs = useRfqsSnapshot();
  const rfq = rfqs.find((r) => r.requestId === req.id);
  const [expanded, setExpanded] = React.useState(null);
  const [picking, setPicking] = React.useState(null);
  const [reason, setReason] = React.useState('');
  if (!rfq) return null;
  const quotes = rfq.invitations.filter((i) => i.quote).slice().sort((a, b) => a.quote.netTotal - b.quote.netTotal);
  if (quotes.length === 0) return null;
  const winner = rfq.winner;
  const winnerName = winner ? (rfq.invitations.find((i) => i.supplierId === winner.supplierId) || {}).supplierName : null;

  function confirmWinner() {
    if (!reason.trim()) { alert('Seçim gerekçesi zorunlu.'); return; }
    window.__rfqs.selectWinner(rfq.id, picking.supplierId, reason.trim(), { by: window.__user && window.__user.id, byName: (window.__user && window.__user.name) || 'Satınalma' });
    setPicking(null); setReason('');
  }

  const cell = { padding: '10px 10px', fontSize: 12.5, textAlign: 'left', verticalAlign: 'top' };
  const th = { ...cell, color: c.muted, fontWeight: 600, borderBottom: `1px solid ${c.border}`, whiteSpace: 'nowrap' };
  const winBadge = { padding: '1px 7px', borderRadius: 999, fontSize: 10, fontWeight: 700, background: 'rgba(16,185,129,0.16)', color: '#0E9F6E' };

  return (
    <div style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, padding: 18, marginBottom: 16 }}>
      <div style={{ fontSize: 13, fontWeight: 700, color: c.text, marginBottom: 4 }}>Teklif karşılaştırma</div>
      <div style={{ fontSize: 12, color: c.muted, marginBottom: 12 }}>{quotes.length} teklif · düşükten yükseğe sıralı. Detay (doküman + not) için satıra tıklayın.</div>

      {winner && (
        <div style={{ background: 'rgba(16,185,129,0.08)', border: '1px solid rgba(16,185,129,0.4)', borderRadius: 10, padding: 12, marginBottom: 12 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: '#0E9F6E' }}>Kazanan: {winnerName}</div>
          {winner.reason && <div style={{ fontSize: 12, color: c.muted, marginTop: 4 }}>Gerekçe: {winner.reason}</div>}
          <div style={{ fontSize: 11.5, color: c.subtle, marginTop: 2 }}>{winner.byName} · {winner.at}</div>
        </div>
      )}

      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 580 }}>
          <thead><tr>
            <th style={th}>Firma</th>
            <th style={{ ...th, textAlign: 'right' }}>KDV'siz</th>
            <th style={{ ...th, textAlign: 'right' }}>KDV</th>
            <th style={{ ...th, textAlign: 'right' }}>KDV dahil</th>
            <th style={th}>Stok</th>
            <th style={th}>Vade</th>
            <th style={th}></th>
          </tr></thead>
          <tbody>
            {quotes.map((inv, idx) => {
              const q = inv.quote;
              const isWin = winner && winner.supplierId === inv.supplierId;
              const open = expanded === inv.token;
              return (
                <React.Fragment key={inv.token}>
                  <tr onClick={() => setExpanded(open ? null : inv.token)} style={{ cursor: 'pointer', background: isWin ? 'rgba(16,185,129,0.06)' : (open ? c.chipBg : 'transparent'), borderBottom: `1px solid ${c.borderSoft}` }}>
                    <td style={cell}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                        {idx === 0 && <span style={winBadge}>En düşük</span>}
                        <span style={{ fontWeight: 600, color: c.text }}>{inv.supplierName}</span>
                        {isWin && <span style={{ ...winBadge, background: '#0E9F6E', color: '#fff' }}>Seçildi</span>}
                      </div>
                    </td>
                    <td style={{ ...cell, textAlign: 'right', fontWeight: 700, color: c.text, whiteSpace: 'nowrap' }}>{formatTL(Math.round(q.netTotal))}</td>
                    <td style={{ ...cell, textAlign: 'right', color: c.muted, whiteSpace: 'nowrap' }}>%{q.vatRate}</td>
                    <td style={{ ...cell, textAlign: 'right', color: c.text, whiteSpace: 'nowrap' }}>{formatTL(Math.round(q.gross))}</td>
                    <td style={{ ...cell, color: c.muted }}>{q.stock}</td>
                    <td style={{ ...cell, color: c.muted, whiteSpace: 'nowrap' }}>{q.paymentTerm || q.validUntil || '—'}</td>
                    <td style={{ ...cell, textAlign: 'right' }}>
                      <button onClick={(e) => { e.stopPropagation(); setPicking(inv); setReason(''); }} style={{ ...solidBtn(isWin ? c.muted : c.primary, false), padding: '6px 12px', fontSize: 12 }}>{isWin ? 'Seçili' : 'Seç'}</button>
                    </td>
                  </tr>
                  {open && (
                    <tr><td colSpan={7} style={{ padding: '0 10px 12px' }}>
                      <div style={{ background: c.chipBg, borderRadius: 10, padding: 12 }}>
                        <div style={{ fontSize: 12, fontWeight: 600, color: c.text, marginBottom: 6 }}>Kalem bazlı fiyat</div>
                        {(q.lines || []).map((l, i) => (
                          <div key={i} style={{ fontSize: 12, display: 'flex', justifyContent: 'space-between', color: c.muted, padding: '2px 0' }}>
                            <span>{l.name} × {l.qty}</span><span>{formatTL(l.unitNet)} / adet</span>
                          </div>
                        ))}
                        <div style={{ marginTop: 8, fontSize: 12, color: c.muted }}><b style={{ color: c.text }}>Ödeme vadesi:</b> {q.paymentTerm || '—'} · <b style={{ color: c.text }}>Teklif geçerlilik:</b> {q.validUntil || '—'}</div>
                        <div style={{ marginTop: 4, fontSize: 12, color: c.muted }}><b style={{ color: c.text }}>Not:</b> {q.note || '—'}</div>
                        <div style={{ marginTop: 4, fontSize: 12, color: c.muted }}><b style={{ color: c.text }}>Doküman:</b> {q.docFileName || '—'}</div>
                        <div style={{ marginTop: 4, fontSize: 11.5, color: c.subtle }}>Gönderim: {q.submittedAt}</div>
                      </div>
                    </td></tr>
                  )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>

      {picking && (
        <div onClick={() => setPicking(null)} style={{ position: 'fixed', inset: 0, zIndex: 260, 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(460px, 100%)', padding: 22 }}>
            <div style={{ fontSize: 16, fontWeight: 700, color: c.text, marginBottom: 4 }}>Kazanan firmayı seç</div>
            <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 14 }}><b>{picking.supplierName}</b> · {formatTL(Math.round(picking.quote.netTotal))} +KDV. Bu firmanın neden seçildiğini belirtin (kayda geçer).</div>
            <textarea value={reason} onChange={(e) => setReason(e.target.value)} rows={3} style={{ ...inputBox(c), resize: 'vertical' }} placeholder="Seçim gerekçesi (örn. en düşük fiyat + en kısa teslim süresi)" />
            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              <button onClick={confirmWinner} style={solidBtn(c.success, false)}>Kazanan olarak seç</button>
              <button onClick={() => setPicking(null)} style={ghostBtn(c)}>Vazgeç</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { RfqRequestModal, QuoteFormOverlay, RfqStatusCard, RfqCompareCard, RFQ_DEFAULT_NOTE, quoteLink });
