// admin-approvals.jsx — Onay Kutusu (Faz 2 / Parça 2.1)
// Onaycı (ör. Yönetici Mehmet Demir) kendine düşen bekleyen talepleri burada görür.
// Bu parçada: gelen kutusu listesi + talep detayı (salt okunur).
// Onay AKSİYONLARI (onayla / düzenleyerek çıkar / reddet) bir sonraki parçada (2.2)
// eklenecek; şimdilik butonlar demo mesajı gösterir.

// ─────────── Demo gelen kutusu verisi ───────────
// Ekip üyelerinin oluşturduğu, ilk onay (Yöneticim adımı) bekleyen talepler.
// netSubtotal = KDV hariç toplam; hasCapex = yatırım kalemi içeriyor mu (zincir hesabı).
const INBOX_REQUESTS = [
  {
    id: '#IT-2026-00161', requester: 'Emre Şahin', requesterInitials: 'EŞ',
    department: 'Pazarlama', date: '29 May 2026', submittedAt: '29 May 2026, 10:12',
    waitingDays: 1, stage: 'mgr', approverId: 'u-mehmet', hasCapex: true,
    netSubtotal: 62700,
    items: [
      { name: 'MacBook Air M3 13" 16/512', brand: 'Apple', qty: 1, priceNet: 58900,
        justification: 'Video düzenleme ve sosyal medya görselleri için mevcut 2019 cihazım render sırasında kilitleniyor. Ekip kampanya teslimleri gecikiyor.' },
      { name: 'Logitech MX Master 3S', brand: 'Logitech', qty: 1, priceNet: 3800,
        justification: 'Mevcut mouse tekliyor, tasarım programlarında hassas seçim zorlaşıyor.' },
    ],
  },
  {
    id: '#IT-2026-00158', requester: 'Selin Aydın', requesterInitials: 'SA',
    department: 'Satış', date: '28 May 2026', submittedAt: '28 May 2026, 16:40',
    waitingDays: 2, stage: 'mgr', approverId: 'u-mehmet', hasCapex: true,
    netSubtotal: 38900,
    items: [
      { name: 'Dell UltraSharp U2723QE 27" 4K', brand: 'Dell', qty: 2, priceNet: 18500,
        justification: 'Çift ekran kurulumu ile CRM ve teklif ekranlarını aynı anda görüp teklif hazırlama süresini kısaltacağım.' },
      { name: 'Logitech MX Keys S Kablosuz Klavye', brand: 'Logitech', qty: 1, priceNet: 4200,
        justification: 'Mevcut klavyede bazı tuşlar çalışmıyor.' },
    ],
  },
  {
    id: '#IT-2026-00155', requester: 'Burak Yıldız', requesterInitials: 'BY',
    department: 'IT Operasyon', date: '28 May 2026', submittedAt: '28 May 2026, 09:05',
    waitingDays: 2, stage: 'mgr', approverId: 'u-mehmet', hasCapex: false,
    netSubtotal: 24600,
    items: [
      { name: 'Microsoft 365 Business Standard', brand: 'Microsoft', qty: 5, priceNet: 4920, priceUnit: 'yıllık/kullanıcı',
        justification: 'Yeni işe başlayan 5 kişilik ekip için Outlook + Teams + Office lisansı gerekiyor.' },
    ],
  },
  {
    id: '#IT-2026-00150', requester: 'Deniz Acar', requesterInitials: 'DA',
    department: 'Finans', date: '27 May 2026', submittedAt: '27 May 2026, 11:28',
    waitingDays: 3, stage: 'mgr', approverId: 'u-mehmet', hasCapex: false,
    netSubtotal: 4200,
    items: [
      { name: 'Logitech MX Keys S Kablosuz Klavye', brand: 'Logitech', qty: 1, priceNet: 4200,
        justification: 'Mevcut klavyemde W ve E tuşları sıkışıyor, raporlama hızım düştü.' },
    ],
  },
  {
    id: '#IT-2026-00149', requester: 'Canan Öz', requesterInitials: 'CÖ',
    department: 'İnsan Kaynakları', date: '26 May 2026', submittedAt: '26 May 2026, 14:55',
    waitingDays: 4, stage: 'mgr', approverId: 'u-mehmet', hasCapex: true,
    netSubtotal: 45000,
    items: [
      { name: 'Dell Latitude 5550 Business Laptop', brand: 'Dell', qty: 1, priceNet: 45000,
        justification: 'İşe yeni başlayan İK uzmanı için standart dizüstü tahsisi.' },
    ],
  },
];

// ─────────── Atomlar ───────────
function ApproverAvatar({ initials, c, size = 40, bg }) {
  return (
    <span style={{
      width: size, height: size, borderRadius: 999, flexShrink: 0,
      background: bg || c.primary, color: '#fff',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.34, fontWeight: 600, letterSpacing: '0.01em',
    }}>{initials}</span>
  );
}

// Onay zinciri rozeti — talebin kaç aşamadan geçeceğini özetler.
function ChainChip({ net, hasCapex, c }) {
  const chain = window.computeApprovalChain ? window.computeApprovalChain(net, hasCapex) : { steps: [] };
  const n = chain.steps.length;
  return (
    <span title={chain.reason || ''} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '4px 10px', borderRadius: 999,
      background: c.chipBg, color: c.muted,
      fontSize: 11.5, fontWeight: 500, whiteSpace: 'nowrap',
    }}>
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 12h16M4 12l4-4M4 12l4 4" /><circle cx="20" cy="12" r="1.6" />
      </svg>
      {n} aşamalı onay
    </span>
  );
}

// ─────────── Özet şeridi ───────────
function InboxSummary({ list, c }) {
  const isMobile = useIsMobile();
  const total = list.reduce((s, r) => s + (r.netSubtotal || 0), 0);
  const oldest = list.reduce((m, r) => Math.max(m, r.waitingDays || 0), 0);
  const stats = [
    ['Bekleyen talep', String(list.length), c.text],
    ['Toplam tutar (net)', formatTL(total), c.text],
    ['En uzun bekleyen', oldest + ' gün', oldest >= 3 ? '#B45309' : c.text],
  ];
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(3, 1fr)',
      gap: 12, marginBottom: 18,
    }}>
      {stats.map(([label, val, color]) => (
        <div key={label} style={{
          background: c.card, border: `1px solid ${c.border}`, borderRadius: 14,
          padding: isMobile ? '12px 14px' : '14px 18px',
        }}>
          <div style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>{label}</div>
          <div style={{ fontSize: isMobile ? 17 : 20, fontWeight: 700, color, letterSpacing: '-0.01em' }}>{val}</div>
        </div>
      ))}
    </div>
  );
}

function userNameById(id) { const u = (window.DEMO_USERS || []).find((x) => x.id === id); return u ? u.name : '—'; }

// Talebin güncel durumu — rozet + nerede olduğu.
function statusMeta(req, c) {
  if (req.status === 'rejected') return { label: 'Reddedildi', color: '#EF4444', bg: 'rgba(239,68,68,0.12)' };
  if (req.status === 'ordered') return { label: 'Sipariş verildi', color: '#0E9F6E', bg: 'rgba(16,185,129,0.12)' };
  const where = req.stage === 'purchasing' ? 'Satınalmada' : `${userNameById(req.approverId)} onayında`;
  return { label: where, color: c.muted, bg: c.chipBg };
}

// Onay geçmişi zinciri — kim onayladı → şu an nerede (gerçek hiyerarşi akışı).
function HistoryChain({ req, c }) {
  const steps = [{ name: req.requester, sub: 'Talebi oluşturdu', kind: 'done' }];
  (req.history || []).forEach((h) => steps.push({
    name: h.byName, kind: h.action === 'rejected' ? 'rejected' : 'done',
    sub: h.action === 'rejected' ? 'Reddetti' : (h.action === 'ordered' ? 'Sipariş oluşturdu' : (h.action === 'edited' ? 'Düzenleyerek onayladı' : 'Onayladı')),
  }));
  if (req.status === 'pending') steps.push({ name: userNameById(req.approverId), sub: req.stage === 'purchasing' ? 'Satınalma · bekliyor' : 'Şu an burada', kind: 'current' });
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
      {steps.map((s, i) => (
        <React.Fragment key={i}>
          <span style={{
            display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            padding: '8px 12px', borderRadius: 10, minWidth: 86,
            background: s.kind === 'current' ? c.selectedBg : (s.kind === 'rejected' ? 'rgba(239,68,68,0.12)' : 'rgba(16,185,129,0.12)'),
            color: s.kind === 'current' ? c.selectedText : (s.kind === 'rejected' ? '#EF4444' : '#0E9F6E'),
          }}>
            <span style={{ fontSize: 12, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              {s.kind === 'done' && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>}
              {s.name}
            </span>
            <span style={{ fontSize: 10.5, opacity: 0.85 }}>{s.sub}</span>
          </span>
          {i < steps.length - 1 && (
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={c.subtle} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6" /></svg>
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

// ─────────── Liste kartı ───────────
function InboxCard({ req, c, onOpen, tab, myId }) {
  const isMobile = useIsMobile();
  const [hover, setHover] = React.useState(false);
  const activeItems = req.items.filter((x) => x.state !== 'removed');
  const itemCount = activeItems.reduce((s, x) => s + (x.qty || 1), 0);
  const sm = tab === 'processed' ? statusMeta(req, c) : null;        // İşlediklerim → nerede olduğu
  const myH = (req.history || []).filter((h) => h.by === myId);
  const myActed = myH.length ? myH[myH.length - 1].action : null;
  const myActedLabel = myActed === 'rejected' ? 'Reddettiniz' : myActed === 'ordered' ? 'Sipariş oluşturdunuz' : myActed === 'edited' ? 'Düzenleyerek onayladınız' : myActed === 'approved' ? 'Onayladınız' : null;
  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>
        {sm ? (
          <span style={{
            padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: 600,
            background: sm.bg, color: sm.color, whiteSpace: 'nowrap',
          }}>{sm.label}</span>
        ) : req.waitingDays >= 3 ? (
          <span style={{
            padding: '3px 9px', borderRadius: 999, fontSize: 11, fontWeight: 600,
            background: 'rgba(245,158,11,0.14)', color: '#B45309', whiteSpace: 'nowrap',
          }}>{req.waitingDays} gündür bekliyor</span>
        ) : null}
      </div>

      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 12, flexWrap: 'wrap',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: c.muted, fontVariantNumeric: 'tabular-nums' }}>{req.id}</span>
          <span style={{ fontSize: 12.5, color: c.subtle }}>·</span>
          <span style={{ fontSize: 12.5, color: c.muted }}>{itemCount} kalem</span>
          {myActedLabel && <span style={{ fontSize: 12, color: c.muted }}>· {myActedLabel}</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,
          }}>
            {tab === 'processed' ? 'Görüntüle' : 'İncele'}
            <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>
  );
}

// ─────────── Buton/giriş stil yardımcıları ───────────
function backBtn(c) {
  return { appearance: 'none', cursor: 'pointer', background: 'transparent', border: 'none', color: c.muted, fontSize: 13, fontWeight: 500, fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 6, padding: 0, marginBottom: 16 };
}
function solidBtn(bg, isMobile) {
  return { appearance: 'none', cursor: 'pointer', border: 'none', borderRadius: 10, padding: '12px 18px', background: bg, color: '#fff', fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit', flex: isMobile ? '1 1 100%' : '0 0 auto' };
}
function ghostBtn(c, isMobile, color) {
  return { appearance: 'none', cursor: 'pointer', borderRadius: 10, padding: '12px 18px', background: 'transparent', color: color || c.text, border: `1px solid ${color || c.border}`, fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit', flex: isMobile ? '1 1 100%' : '0 0 auto' };
}
function inputBox(c) {
  return { width: '100%', boxSizing: 'border-box', padding: '10px 12px', background: c.inputBg, color: c.text, border: `1px solid ${c.border}`, borderRadius: 10, fontSize: 13, fontFamily: 'inherit', outline: 'none' };
}
function qtyBtn(c) {
  return { appearance: 'none', cursor: 'pointer', border: 'none', background: 'transparent', color: c.text, width: 30, height: 30, fontSize: 16, fontWeight: 600, fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' };
}

// ─────────── Detay + onay aksiyonları ───────────
function InboxDetail({ req, c, onBack }) {
  const isMobile = useIsMobile();
  const myId = window.__user && window.__user.id;
  // Karar verebilir mi: talep şu an bu kullanıcının onayında mı?
  const actionable = req.status === 'pending' && req.stage === 'approval' && req.approverId === myId;
  const sm = statusMeta(req, c);
  const [mode, setMode] = React.useState('view');     // view | edit | reject
  const [removed, setRemoved] = React.useState({});     // {index: true}
  const [reasons, setReasons] = React.useState({});     // {index: reason}
  const [qtys, setQtys] = React.useState(() => { const m = {}; req.items.forEach((it, i) => { m[i] = it.qty || 1; }); return m; });
  const [editNote, setEditNote] = React.useState('');
  const [rejectReason, setRejectReason] = React.useState('');
  const A = window.__approvals || {};
  const editing = actionable && mode === 'edit';     // yalnızca karar verebilecekken düzenleme arayüzü
  const activeCount = req.items.filter((it) => it.state !== 'removed').length;
  const cardStyle = { background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, padding: isMobile ? 16 : 22, marginBottom: 16 };

  function doApproveAll() {
    if (A.approveAll) A.approveAll(req.id, '');   // snapshot güncellenince detay "işlenmiş" görünüme döner
  }
  function doApproveEdited() {
    const edits = req.items.map((it, i) => ({
      remove: !!removed[i],
      qty: Math.max(1, Math.min(it.qty || 1, parseInt(qtys[i], 10) || (it.qty || 1))),
      reason: (reasons[i] || '').trim(),
    }));
    const removedIdx = edits.map((e, i) => (e.remove ? i : -1)).filter((i) => i >= 0);
    const changed = edits.some((e, i) => e.remove || e.qty !== (req.items[i].qty || 1));
    if (!changed) { alert('Bir değişiklik yapın (adet düşürün veya kalem çıkarın) ya da "Tümünü Onayla" kullanın.'); return; }
    if (removedIdx.length >= activeCount) { alert('Tüm kalemleri çıkaramazsınız. Tümden reddetmek için "Reddet" kullanın.'); return; }
    for (const i of removedIdx) {
      if (!edits[i].reason) { alert('Çıkardığınız her kalem için gerekçe yazın.'); return; }
    }
    // Değişiklik özetini karar notuna ekle (hem onaycı banner'ı hem talep edenin timeline'ı görsün)
    const changes = [];
    edits.forEach((e, i) => {
      const it = req.items[i];
      if (e.remove) changes.push(`${it.name} çıkarıldı`);
      else if (e.qty !== (it.qty || 1)) changes.push(`${it.name} adet ${it.qty}→${e.qty}`);
    });
    const noteFull = [editNote.trim(), changes.length ? ('Düzeltme: ' + changes.join(', ')) : ''].filter(Boolean).join(' · ');
    if (A.approveEdited) A.approveEdited(req.id, edits, noteFull);
  }
  function doReject() {
    if (!rejectReason.trim()) { alert('Reddetme gerekçesi zorunludur.'); return; }
    if (A.reject) A.reject(req.id, rejectReason.trim());
  }

  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>
        Onay kutusuna dön
      </button>

      {/* Durum bandı — bu talep bu kullanıcının onayında DEĞİLSE (işlenmiş/akmış) */}
      {!actionable && (
        <div style={{ ...cardStyle, borderLeft: `4px solid ${sm.color === c.muted ? c.primary : sm.color}` }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: sm.color === c.muted ? c.text : sm.color }}>
            {req.status === 'pending' ? `Şu an: ${sm.label}` : sm.label}
          </div>
          {(() => {
            const last = (req.history || [])[(req.history || []).length - 1];
            return last ? (
              <div style={{ fontSize: 12.5, color: c.muted, marginTop: 4 }}>
                Son işlem: <b style={{ color: c.text }}>{last.byName}</b> · {last.time}
                {last.note && <> — {last.note}</>}
              </div>
            ) : null;
          })()}
        </div>
      )}

      {/* Talep başlığı */}
      <div style={cardStyle}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
          <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 }}>KDV hariç toplam</div>
          </div>
        </div>
        <div style={{ fontSize: 12.5, color: c.muted }}>Gönderim: {req.submittedAt}</div>
      </div>

      {/* Kalemler + gerekçeler (+ düzenleme modunda çıkarma) */}
      <div style={cardStyle}>
        <div style={{ fontSize: 13, fontWeight: 600, color: c.text, marginBottom: 14 }}>
          Talep kalemleri ({req.items.length})
          {editing && <span style={{ fontWeight: 500, color: c.muted }}> — çıkarmak istediklerinizi işaretleyip gerekçe yazın</span>}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {req.items.map((it, i) => {
            const isRemovedFinal = it.state === 'removed';
            const isMarked = !!removed[i];
            const dim = isRemovedFinal || (editing && isMarked);
            return (
              <div key={i} style={{ display: 'flex', gap: 12, paddingBottom: 14, borderBottom: i < req.items.length - 1 ? `1px solid ${c.borderSoft}` : 'none', opacity: dim ? 0.6 : 1 }}>
                <span style={{
                  width: 36, height: 36, borderRadius: 9, flexShrink: 0,
                  background: c.chipBg, color: c.muted,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 14, fontWeight: 600,
                }}>{it.name.charAt(0)}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 13.5, fontWeight: 600, color: c.text, textDecoration: dim ? 'line-through' : 'none' }}>{it.name}</span>
                    <span style={{ fontSize: 13, color: c.muted, whiteSpace: 'nowrap' }}>
                      {it.qty} × {formatTL(it.priceNet)}{it.priceUnit ? ` · ${it.priceUnit}` : ''}
                    </span>
                  </div>
                  <div style={{
                    marginTop: 8, padding: '9px 12px', borderRadius: 10,
                    background: c.chipBg, borderLeft: `3px solid ${c.primary}`,
                    fontSize: 12.5, color: c.muted, lineHeight: 1.5,
                  }}>
                    <span style={{ fontWeight: 600, color: c.text }}>İhtiyaç gerekçesi: </span>
                    {it.justification}
                  </div>
                  {isRemovedFinal && it.removalReason && (
                    <div style={{ marginTop: 6, fontSize: 12, color: '#B45309' }}>
                      <b>Çıkarıldı:</b> {it.removalReason}
                    </div>
                  )}
                  {editing && !isRemovedFinal && (
                    <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
                      {!isMarked && (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                          <span style={{ fontSize: 12.5, color: c.muted }}>Onaylanan adet:</span>
                          <div style={{ display: 'inline-flex', alignItems: 'center', border: `1px solid ${c.border}`, borderRadius: 9, overflow: 'hidden' }}>
                            <button type="button" onClick={() => setQtys((p) => ({ ...p, [i]: Math.max(1, (p[i] || it.qty) - 1) }))} style={qtyBtn(c)}>−</button>
                            <span style={{ minWidth: 34, textAlign: 'center', fontSize: 13, fontWeight: 600, color: c.text }}>{qtys[i] || it.qty}</span>
                            <button type="button" onClick={() => setQtys((p) => ({ ...p, [i]: Math.min(it.qty, (p[i] || it.qty) + 1) }))} style={qtyBtn(c)}>+</button>
                          </div>
                          <span style={{ fontSize: 11.5, color: c.subtle }}>talep edilen: {it.qty}</span>
                          {(qtys[i] || it.qty) !== it.qty && (
                            <span style={{ fontSize: 11.5, fontWeight: 600, color: '#B45309' }}>{it.qty} → {qtys[i]} adet</span>
                          )}
                        </div>
                      )}
                      <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: c.text, cursor: 'pointer' }}>
                        <input type="checkbox" checked={isMarked} onChange={(e) => setRemoved((p) => ({ ...p, [i]: e.target.checked }))} />
                        Bu kalemi tamamen çıkar
                      </label>
                      {isMarked && (
                        <input type="text" value={reasons[i] || ''} onChange={(e) => setReasons((p) => ({ ...p, [i]: e.target.value }))}
                          placeholder="Çıkarma gerekçesi (zorunlu)" style={{ ...inputBox(c) }} />
                      )}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Onay zinciri — gerçek hiyerarşi akışı (kim onayladı → şu an nerede) */}
      <div style={cardStyle}>
        <div style={{ fontSize: 13, fontWeight: 600, color: c.text, marginBottom: 14 }}>Onay akışı</div>
        <HistoryChain req={req} c={c} />
      </div>

      {/* Aksiyonlar — yalnızca talep bu kullanıcının onayındayken */}
      {actionable && mode === 'view' && (
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button onClick={doApproveAll} style={solidBtn(c.success, isMobile)}>Tümünü Onayla</button>
          <button onClick={() => setMode('edit')} style={ghostBtn(c, isMobile)}>Düzenleyerek Onayla</button>
          <button onClick={() => setMode('reject')} style={ghostBtn(c, isMobile, c.danger)}>Reddet</button>
        </div>
      )}

      {actionable && mode === 'edit' && (
        <div style={cardStyle}>
          <div style={{ fontSize: 13, fontWeight: 600, color: c.text, marginBottom: 10 }}>Düzenleyerek onayla</div>
          <textarea value={editNote} onChange={(e) => setEditNote(e.target.value)} placeholder="Genel not (opsiyonel) — talep edene iletilir" rows={2} style={{ ...inputBox(c), resize: 'vertical' }} />
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginTop: 12 }}>
            <button onClick={doApproveEdited} style={solidBtn(c.success, isMobile)}>Onayla ve ilet</button>
            <button onClick={() => { setMode('view'); setRemoved({}); setReasons({}); }} style={ghostBtn(c, isMobile)}>Vazgeç</button>
          </div>
        </div>
      )}

      {actionable && mode === 'reject' && (
        <div style={cardStyle}>
          <div style={{ fontSize: 13, fontWeight: 600, color: c.text, marginBottom: 10 }}>Talebi reddet</div>
          <textarea value={rejectReason} onChange={(e) => setRejectReason(e.target.value)} placeholder="Reddetme gerekçesi (zorunlu) — talep edene iletilecek" rows={3} style={{ ...inputBox(c), resize: 'vertical' }} />
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginTop: 12 }}>
            <button onClick={doReject} style={solidBtn('#EF4444', isMobile)}>Talebi reddet</button>
            <button onClick={() => setMode('view')} style={ghostBtn(c, isMobile)}>Vazgeç</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─────────── Sekme düğmesi ───────────
function InboxTab({ label, count, active, onClick, c }) {
  return (
    <button onClick={onClick} style={{
      appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
      padding: '8px 14px', borderRadius: 999, border: `1px solid ${active ? c.primary : c.border}`,
      background: active ? c.selectedBg : 'transparent',
      color: active ? c.selectedText : c.muted,
      fontSize: 13, fontWeight: 600,
      display: 'inline-flex', alignItems: 'center', gap: 7,
    }}>
      {label}
      <span style={{
        minWidth: 18, height: 18, padding: '0 5px', boxSizing: 'border-box', borderRadius: 999,
        background: active ? c.primary : c.chipBg, color: active ? '#fff' : c.muted,
        fontSize: 11, fontWeight: 700, lineHeight: '18px', textAlign: 'center',
      }}>{count}</span>
    </button>
  );
}

// ─────────── Sayfa ───────────
function ApprovalInbox({ 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 me = useCurrentUser();
  const myId = me && me.id;

  // Bekleyenler: şu an bu kullanıcının onayında. İşlediklerim: geçmişinde bu kullanıcının kararı olanlar.
  const pending = all.filter((r) => r.status === 'pending' && r.stage === 'approval' && r.approverId === myId);
  const processed = all.filter((r) => (r.history || []).some((h) => h.by === myId));
  // Tedarikçi kartı değişiklikleri — satınalmanın yöneticisi (veya süper admin) onaylar
  const supChanges = suppliers.filter((s) => s.pendingEdit && s.pendingEdit.status === 'pending' && (s.pendingEdit.approverId === myId || (me && me.superAdmin)));
  const approveSupEdit = (id) => window.__suppliers && window.__suppliers.approveEdit(id);
  const rejectSupEdit = (id) => { const note = window.prompt('Red gerekçesi (opsiyonel):'); if (note !== null && window.__suppliers) window.__suppliers.rejectEdit(id, note || ''); };
  // Profil değişiklikleri — kullanıcının yöneticisi (veya süper admin) onaylar
  const usersAll = useUsersSnapshot();
  const profChanges = usersAll.filter((u) => u.pendingProfileEdit && u.pendingProfileEdit.status === 'pending' && (u.pendingProfileEdit.approverId === myId || (me && me.superAdmin)));
  const approveProfEdit = (id) => window.__users && window.__users.approveProfileEdit(id);
  const rejectProfEdit = (id) => { const note = window.prompt('Red gerekçesi (opsiyonel):'); if (note !== null && window.__users) window.__users.rejectProfileEdit(id, note || ''); };
  // Değerlendirmeler — talebi açanın yöneticisi tedarikçiyi puanlar (4.5)
  const ratingsAll = window.useRatingsSnapshot ? window.useRatingsSnapshot() : [];
  const myRatingTasks = ratingsAll.filter((r) => r.managerId === myId || (me && me.superAdmin));
  const pendingRatings = myRatingTasks.filter((r) => !r.supplier);
  // Katalog silme talepleri — IT (Süper Admin) onaylar (Faz 5.2c)
  const catalogDels = (window.useCatalogDelSnapshot ? window.useCatalogDelSnapshot() : [])
    .filter((r) => r.approverId === myId || (me && me.superAdmin));
  const CD = window.__catalogDel || {};
  const CD_KIND = { category: 'Kategori', subcategory: 'Alt kategori', product: 'Ürün', 'category-edit': 'Kategori' };
  const approveCatDel = (id) => { if (window.confirm('Bu talep onaylansın mı? (Öğe değişikliği/silme kalıcıdır)') && CD.approve) CD.approve(id); };
  const rejectCatDel = (id) => { const note = window.prompt('Red gerekçesi (opsiyonel):'); if (note !== null && CD.reject) CD.reject(id, note || ''); };
  const [ratingTarget, setRatingTarget] = React.useState(null);
  const [tab, setTab] = React.useState('pending');     // pending | processed | supchanges
  const [openId, setOpenId] = React.useState(null);
  const openReq = openId ? all.find((r) => r.id === openId) : null;
  const shown = tab === 'pending' ? pending : processed;

  return (
    <div style={{ minHeight: '100%', background: c.bg, fontFamily: 'Inter, system-ui, sans-serif' }}>
      {/* Onaycı da tam kabuğu kullanır: ortak header (hamburger → kategoriler, sepet,
          taleplerim, profil) + onaycıya özel "Onay Kutusu" linki burada görünür. */}
      <CatalogHeader
        c={c}
        dark={dark}
        onToggleDark={() => setDark((x) => !x)}
        cartCount={cart.length}
        notifCount={0}
      />

      <div style={{ maxWidth: 880, margin: '0 auto', padding: isMobile ? '18px 16px 40px' : '28px 28px 56px' }}>
        {openReq ? (
          <InboxDetail req={openReq} c={c} onBack={() => setOpenId(null)} />
        ) : (
          <React.Fragment>
            <div style={{ marginBottom: 16 }}>
              <h1 style={{ margin: 0, fontSize: isMobile ? 20 : 23, fontWeight: 700, color: c.text, letterSpacing: '-0.015em' }}>
                Onay Kutusu
              </h1>
              <div style={{ fontSize: 13, color: c.muted, marginTop: 4 }}>
                {pending.length > 0
                  ? `${pending.length} talep onayınızı bekliyor`
                  : 'Onayınızı bekleyen talep yok'}
              </div>
            </div>

            {/* Sekmeler */}
            <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
              <InboxTab label="Bekleyenler" count={pending.length} active={tab === 'pending'} onClick={() => setTab('pending')} c={c} />
              <InboxTab label="İşlediklerim" count={processed.length} active={tab === 'processed'} onClick={() => setTab('processed')} c={c} />
              {supChanges.length > 0 && <InboxTab label="Tedarikçi Değişiklikleri" count={supChanges.length} active={tab === 'supchanges'} onClick={() => setTab('supchanges')} c={c} />}
              {profChanges.length > 0 && <InboxTab label="Profil Değişiklikleri" count={profChanges.length} active={tab === 'profchanges'} onClick={() => setTab('profchanges')} c={c} />}
              {myRatingTasks.length > 0 && <InboxTab label="Değerlendirmeler" count={pendingRatings.length} active={tab === 'ratings'} onClick={() => setTab('ratings')} c={c} />}
              {catalogDels.length > 0 && <InboxTab label="Katalog Silme" count={catalogDels.length} active={tab === 'catdel'} onClick={() => setTab('catdel')} c={c} />}
            </div>

            {ratingTarget && <window.SupplierRatingModal rating={ratingTarget} c={c} onClose={() => setRatingTarget(null)} />}

            {tab === 'supchanges' ? (
              supChanges.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 }}>Bekleyen tedarikçi değişikliği yok</div>
                  Satınalmanın yaptığı kart değişiklikleri burada onayınıza düşer.
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {supChanges.map((s) => <window.SupplierChangeCard key={s.id} s={s} c={c} onApprove={approveSupEdit} onReject={rejectSupEdit} />)}
                </div>
              )
            ) : tab === 'ratings' ? (
              myRatingTasks.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 }}>Değerlendirme yok</div>
                  Ekibinizin tamamlanan siparişlerinde tedarikçi değerlendirmesi burada açılır.
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {myRatingTasks.map((r) => <window.ManagerRatingCard key={r.requestId} r={r} c={c} onRate={setRatingTarget} />)}
                </div>
              )
            ) : tab === 'profchanges' ? (
              profChanges.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 }}>Bekleyen profil değişikliği yok</div>
                  Ekibinizin profil güncellemeleri burada onayınıza düşer.
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {profChanges.map((u) => <window.ProfileChangeCard key={u.id} u={u} c={c} onApprove={approveProfEdit} onReject={rejectProfEdit} />)}
                </div>
              )
            ) : tab === 'catdel' ? (
              catalogDels.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 }}>Bekleyen katalog silme talebi yok</div>
                  Katalog yöneticilerinin kategori/alt-kategori/ürün silme talepleri buraya düşer.
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {catalogDels.map((r) => {
                    const m = (window.MODULES || {})[r.module] || {};
                    const isEdit = r.kind === 'category-edit';
                    const accent = isEdit ? '#B45309' : '#DC2626';
                    const accentBg = isEdit ? 'rgba(245,158,11,0.14)' : 'rgba(239,68,68,0.14)';
                    return (
                      <div key={r.id} style={{ background: c.card, border: `1px solid ${isEdit ? 'rgba(245,158,11,0.4)' : 'rgba(239,68,68,0.4)'}`, borderRadius: 16, padding: 18 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10, flexWrap: 'wrap' }}>
                          <span style={{ padding: '3px 10px', borderRadius: 999, fontSize: 11.5, fontWeight: 700, background: accentBg, color: accent }}>{CD_KIND[r.kind] || 'Öğe'} {isEdit ? 'düzenleme' : 'silme'}</span>
                          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: m.color || c.muted }}>
                            <span style={{ width: 8, height: 8, borderRadius: 999, background: m.color || c.muted }} />{m.name || r.module}
                          </span>
                          <span style={{ marginLeft: 'auto', fontSize: 12, color: c.muted }}>{r.byName} · {r.at}</span>
                        </div>
                        <div style={{ fontSize: 13, color: c.text, marginBottom: 14 }}>
                          {isEdit ? (
                            <span>
                              <b>{r.targetName}</b> kategorisinin adı/ikonu değiştirilmek isteniyor:
                              {r.changes && r.changes.name && r.changes.name !== r.targetName
                                ? <span> <span style={{ textDecoration: 'line-through', color: c.muted }}>{r.targetName}</span> → <b>{r.changes.name}</b></span>
                                : <span> (ad aynı, ikon güncellemesi)</span>}
                            </span>
                          ) : (
                            <span><b>{r.targetName}</b> {(CD_KIND[r.kind] || '').toLowerCase()} kalıcı olarak silinmek isteniyor. Onaylarsanız geri alınamaz.</span>
                          )}
                        </div>
                        <div style={{ display: 'flex', gap: 8 }}>
                          <button onClick={() => approveCatDel(r.id)} style={solidBtn(isEdit ? c.success : c.danger, isMobile)}>{isEdit ? 'Düzenlemeyi onayla' : 'Silmeyi onayla'}</button>
                          <button onClick={() => rejectCatDel(r.id)} style={{ ...ghostBtn(c, isMobile) }}>Reddet</button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )
            ) : (
            <React.Fragment>
            {tab === 'pending' && <InboxSummary list={pending} c={c} />}

            {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' ? 'Onay kutunuz boş' : 'Henüz işlediğiniz talep yok'}
                </div>
                {tab === 'pending' ? 'Onayınızı bekleyen talep yok.' : 'Onayladığınız veya reddettiğiniz talepler burada listelenir.'}
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {shown.map((req) => (
                  <InboxCard key={req.id} req={req} c={c} onOpen={setOpenId} tab={tab} myId={myId} />
                ))}
              </div>
            )}
            </React.Fragment>
            )}
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ApprovalInbox, INBOX_REQUESTS });
