// purchasing.jsx — Satınalma Paneli (Faz 3 / Parça 3.5)
// Zincirin sonunda onaylanan talepler buraya düşer. Satınalma uzmanı tedarikçi atayıp
// sipariş oluşturur → talep "Tamamlandı" olur. Yardımcılar (HistoryChain, statusMeta,
// ApproverAvatar, solidBtn/ghostBtn/inputBox) admin-approvals.jsx'te global tanımlı.

function PurchaseCard({ req, c, onOpen, done }) {
  const isMobile = useIsMobile();
  const [hover, setHover] = React.useState(false);
  const itemCount = req.items.filter((x) => x.state !== 'removed').reduce((s, x) => s + (x.qty || 1), 0);
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} onClick={() => onOpen(req.id)}
      style={{
        background: hover ? c.cardHover : c.card, border: `1px solid ${hover ? c.primary : c.border}`,
        borderRadius: 16, padding: isMobile ? 14 : 18, cursor: 'pointer',
        transition: 'border-color 120ms, background 120ms', display: 'flex', flexDirection: 'column', gap: 12,
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <ApproverAvatar initials={req.requesterInitials} c={c} bg="#475569" />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: c.text }}>{req.requester}</div>
          <div style={{ fontSize: 12, color: c.muted }}>{req.department} · {req.date}</div>
        </div>
        {done
          ? <span style={{ padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: 600, background: 'rgba(16,185,129,0.12)', color: '#0E9F6E', whiteSpace: 'nowrap' }}>{req.order ? req.order.poNo : 'Sipariş verildi'}</span>
          : <span style={{ padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: 600, background: c.selectedBg, color: c.selectedText, whiteSpace: 'nowrap' }}>Sipariş bekliyor</span>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: c.muted }}>{req.id}</span>
          <span style={{ fontSize: 12.5, color: c.subtle }}>·</span>
          <span style={{ fontSize: 12.5, color: c.muted }}>{itemCount} kalem</span>
          {done && req.order && req.order.supplier && <span style={{ fontSize: 12, color: c.muted }}>· {req.order.supplier}</span>}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ fontSize: 16, fontWeight: 700, color: c.text, letterSpacing: '-0.01em' }}>{formatTL(req.netSubtotal)}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12.5, fontWeight: 600, color: c.primary }}>
            {done ? 'Görüntüle' : 'Sipariş oluştur'}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6" /></svg>
          </span>
        </div>
      </div>
    </div>
  );
}

function PurchaseDetail({ req, c, onBack }) {
  const isMobile = useIsMobile();
  const A = window.__approvals || {};
  const ordered = req.status === 'ordered';
  const [rfqOpen, setRfqOpen] = React.useState(false);
  const [supplier, setSupplier] = React.useState('');
  const initialPo = React.useRef(`#PO-2026-${String(Math.floor(40 + Math.random() * 900)).padStart(5, '0')}`).current;
  const [poNo, setPoNo] = React.useState(initialPo);
  const [note, setNote] = React.useState(`${initialPo} bu sipariş numarasını faturaya yazınız`);
  // Kazanan teklif → sipariş tedarikçisini otomatik doldur
  const rfqAll = useRfqsSnapshot();
  const myRfq = rfqAll.find((r) => r.requestId === req.id);
  const winnerInv = myRfq && myRfq.winner ? myRfq.invitations.find((i) => i.supplierId === myRfq.winner.supplierId) : null;
  React.useEffect(() => { if (winnerInv) setSupplier(winnerInv.supplierName); }, [winnerInv && winnerInv.supplierId]);
  const cardStyle = { background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, padding: isMobile ? 16 : 22, marginBottom: 16 };

  function createOrder() {
    if (!supplier.trim()) { alert('Tedarikçi adı zorunlu.'); return; }
    if (A.createOrder) A.createOrder(req.id, { supplier: supplier.trim(), supplierId: winnerInv ? winnerInv.supplierId : null, poNo: poNo.trim(), note: note.trim() });
    alert('Sipariş oluşturuldu. Talebi açan kişiye panel bildirimi ve bilgilendirme e-postası gönderildi.');
  }

  return (
    <div>
      <button onClick={onBack} style={backBtn(c)}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
        Satınalmaya dön
      </button>

      {ordered && req.order && (
        <div style={{ ...cardStyle, borderLeft: `4px solid #0E9F6E` }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#0E9F6E' }}>Sipariş oluşturuldu · {req.order.poNo}</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 4 }}>
            Tedarikçi: <b style={{ color: c.text }}>{req.order.supplier || '—'}</b> · {req.order.at}
          </div>
          {req.order.note && <div style={{ fontSize: 12.5, color: c.muted, marginTop: 4 }}>Not: {req.order.note}</div>}
        </div>
      )}

      {/* Talep başlığı */}
      <div style={cardStyle}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <ApproverAvatar initials={req.requesterInitials} c={c} bg="#475569" size={44} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 600, color: c.text }}>{req.requester}</div>
            <div style={{ fontSize: 12.5, color: c.muted }}>{req.department} · Talep {req.id}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 19, fontWeight: 700, color: c.text, letterSpacing: '-0.01em' }}>{formatTL(req.netSubtotal)}</div>
            <div style={{ fontSize: 11.5, color: c.subtle }}>onaylanan tutar (net)</div>
          </div>
        </div>
      </div>

      {/* Kalemler */}
      <div style={cardStyle}>
        <div style={{ fontSize: 13, fontWeight: 600, color: c.text, marginBottom: 14 }}>Sipariş kalemleri</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {req.items.filter((it) => it.state !== 'removed').map((it, i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center' }}>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: c.text }}>{it.name}</span>
              <span style={{ fontSize: 13, color: c.muted, whiteSpace: 'nowrap' }}>{it.qty} × {formatTL(it.priceNet)}{it.priceUnit ? ` · ${it.priceUnit}` : ''}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Onay akışı */}
      <div style={cardStyle}>
        <div style={{ fontSize: 13, fontWeight: 600, color: c.text, marginBottom: 14 }}>Onay akışı</div>
        <HistoryChain req={req} c={c} />
      </div>

      {/* Teklif toplama (RFQ) — sipariş öncesi */}
      {!ordered && (
        <div style={cardStyle}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: c.text }}>Teklif toplama</div>
              <div style={{ fontSize: 12, color: c.muted, marginTop: 2 }}>Tedarikçilerden fiyat teklifi isteyin (tek tek veya kategori bazlı).</div>
            </div>
            <button onClick={() => setRfqOpen(true)} style={solidBtn(c.primary, isMobile)}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: 6, verticalAlign: 'middle' }}><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" /></svg>
              Teklif iste
            </button>
          </div>
        </div>
      )}
      <RfqStatusCard req={req} c={c} />
      <RfqCompareCard req={req} c={c} />
      {rfqOpen && <RfqRequestModal req={req} c={c} onClose={() => setRfqOpen(false)} onOpenQuote={(t) => window.__openQuoteForm && window.__openQuoteForm(t)} />}

      {/* Sipariş formu — yalnızca henüz sipariş verilmediyse */}
      {!ordered && (
        <div style={cardStyle}>
          <div style={{ fontSize: 13, fontWeight: 600, color: c.text, marginBottom: 12 }}>Sipariş oluştur</div>
          {winnerInv && (
            <div style={{ background: 'rgba(16,185,129,0.08)', border: '1px solid rgba(16,185,129,0.4)', borderRadius: 10, padding: 10, marginBottom: 12, fontSize: 12.5, color: c.text }}>
              Seçilen kazanan teklif: <b>{winnerInv.supplierName}</b> · {formatTL(Math.round(winnerInv.quote.netTotal))} +KDV. Tedarikçi otomatik dolduruldu.
            </div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 12 }}>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>Tedarikçi *</label>
              <input value={supplier} onChange={(e) => setSupplier(e.target.value)} style={inputBox(c)} placeholder="örn. ABC Bilişim A.Ş." />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>Sipariş no</label>
              <input value={poNo} onChange={(e) => setPoNo(e.target.value)} style={inputBox(c)} />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gridColumn: isMobile ? 'auto' : '1 / -1' }}>
              <label style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>Not (opsiyonel)</label>
              <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={2} style={{ ...inputBox(c), resize: 'vertical' }} placeholder="Teslim/fatura notu" />
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <button onClick={createOrder} style={solidBtn(c.success, isMobile)}>Siparişi Oluştur</button>
          </div>
        </div>
      )}
    </div>
  );
}

function PurchasingPanel({ initialDark = false, user }) {
  const [dark, setDark] = React.useState(initialDark);
  React.useEffect(() => { setDark(initialDark); }, [initialDark]);
  const c = catalogTheme(dark);
  const isMobile = useIsMobile();
  const cart = useCartSnapshot();
  const all = useApprovalsSnapshot();
  const suppliers = useSuppliersSnapshot();

  const pendingOrders = all.filter((r) => r.status === 'pending' && r.stage === 'purchasing');
  const doneOrders = all.filter((r) => r.status === 'ordered');
  const [tab, setTab] = React.useState('pending');
  const [openId, setOpenId] = React.useState(null);
  const [openSupplierId, setOpenSupplierId] = React.useState(null);
  // Tedarikçi kayıt overlay'i (dış/DMZ önizleme) — davet modalı veya tedarikçi kartından tetiklenir
  const [reg, setReg] = React.useState(null); // { token, mode }
  const [quoteToken, setQuoteToken] = React.useState(null); // teklif formu (RFQ)
  React.useEffect(() => {
    window.__openSupplierRegister = (token, mode = 'register') => setReg({ token, mode });
    window.__openQuoteForm = (token) => setQuoteToken(token);
    return () => { delete window.__openSupplierRegister; delete window.__openQuoteForm; };
  }, []);
  const openReq = openId ? all.find((r) => r.id === openId) : null;
  const openSupplier = openSupplierId ? suppliers.find((s) => s.id === openSupplierId) : null;
  const shown = tab === 'pending' ? pendingOrders : doneOrders;

  // Sekme değişince açık detayları kapat
  const switchTab = (t) => { setTab(t); setOpenId(null); setOpenSupplierId(null); };

  // Tedarikçi sekmesi daha geniş alan ister (kategoriye gruplu 2 kolon)
  const wide = tab === 'suppliers' && !openSupplier;

  return (
    <div style={{ minHeight: '100%', background: c.bg, fontFamily: 'Inter, system-ui, sans-serif' }}>
      {reg && <SupplierRegisterOverlay token={reg.token} mode={reg.mode} onClose={() => setReg(null)} />}
      {quoteToken && <QuoteFormOverlay token={quoteToken} onClose={() => setQuoteToken(null)} />}
      <CatalogHeader c={c} dark={dark} onToggleDark={() => setDark((x) => !x)} cartCount={cart.length} notifCount={0} />

      <div style={{ maxWidth: wide ? 1040 : 880, margin: '0 auto', padding: isMobile ? '18px 16px 40px' : '28px 28px 56px' }}>
        {openReq ? (
          <PurchaseDetail req={openReq} c={c} onBack={() => setOpenId(null)} />
        ) : openSupplier ? (
          <SupplierDetail s={openSupplier} c={c} onBack={() => setOpenSupplierId(null)} />
        ) : (
          <React.Fragment>
            <div style={{ marginBottom: 16 }}>
              <h1 style={{ margin: 0, fontSize: isMobile ? 20 : 23, fontWeight: 700, color: c.text, letterSpacing: '-0.015em' }}>Satınalma</h1>
              <div style={{ fontSize: 13, color: c.muted, marginTop: 4 }}>
                {tab === 'suppliers'
                  ? 'Kayıtlı tedarikçiler — kategoriye göre gruplu'
                  : (pendingOrders.length > 0 ? `${pendingOrders.length} onaylı talep sipariş bekliyor` : 'Sipariş bekleyen talep yok')}
              </div>
            </div>

            <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
              <InboxTab label="Sipariş Bekleyenler" count={pendingOrders.length} active={tab === 'pending'} onClick={() => switchTab('pending')} c={c} />
              <InboxTab label="Tamamlananlar" count={doneOrders.length} active={tab === 'done'} onClick={() => switchTab('done')} c={c} />
              <InboxTab label="Tedarikçiler" count={suppliers.length} active={tab === 'suppliers'} onClick={() => switchTab('suppliers')} c={c} />
            </div>

            {tab === 'suppliers' ? (
              <SuppliersView c={c} onOpen={setOpenSupplierId} />
            ) : shown.length === 0 ? (
              <div style={{ background: c.card, border: `1px dashed ${c.border}`, borderRadius: 16, padding: 48, textAlign: 'center', color: c.muted }}>
                <div style={{ fontSize: 15, fontWeight: 600, color: c.text, marginBottom: 6 }}>{tab === 'pending' ? 'Sipariş bekleyen yok' : 'Henüz tamamlanan sipariş yok'}</div>
                {tab === 'pending' ? 'Onay zincirini tamamlayan talepler burada listelenir.' : 'Oluşturduğunuz siparişler burada görünür.'}
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {shown.map((req) => <PurchaseCard key={req.id} req={req} c={c} onOpen={setOpenId} done={tab === 'done'} />)}
              </div>
            )}
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PurchasingPanel });
