// depot.jsx — Depo Paneli (Faz 7.2)
// Depo Sorumlusu görünümü: satınalma siparişi tamamlanınca ZİMMETLİ ekipman bu panele "yolda"
// (in_transit) düşer. Sorumlu teslim alır (received) → kullanıcıya "ürünün geldi" bildirimi gider;
// kullanıcı dijital zimmet formunu imzalayınca (Faz 7.3) "kullanımda" (in_use) olur.
// Build'siz proje: import/export yok, window üzerinden paylaşılır.

const DEPOT_STATUS_META = {
  in_transit: { label: 'Teslim bekleniyor', color: '#B45309', bg: 'rgba(245,158,11,0.14)', icon: '🚚' },
  received:   { label: 'Teslim alındı · imza bekliyor', color: '#1D4ED8', bg: 'rgba(37,99,235,0.12)', icon: '📦' },
  in_use:     { label: 'Kullanımda · zimmetli', color: '#047857', bg: 'rgba(16,185,129,0.12)', icon: '✅' },
  in_service: { label: 'Serviste', color: '#C2410C', bg: 'rgba(234,88,12,0.14)', icon: '🔧' },
  return_pending: { label: 'İade sürecinde', color: '#7C3AED', bg: 'rgba(124,58,237,0.12)', icon: '↩️' },
  in_pool:    { label: 'Havuzda · atanabilir', color: '#0369A1', bg: 'rgba(3,105,161,0.12)', icon: '♻️' },
  scrap_pending: { label: 'Hurda onayı bekliyor', color: '#B45309', bg: 'rgba(245,158,11,0.14)', icon: '⏳' },
  scrapped:   { label: 'Hurda', color: '#6B7280', bg: 'rgba(107,114,128,0.16)', icon: '🗑️' },
};
// Bu kullanıcının yönettiği (depo sorumlusu yöneticisi olduğu) depo modülleri — hurda onayı için.
function overseenDepotModules(user) {
  if (!user) return [];
  const users = window.DEMO_USERS || [];
  const mods = new Set();
  users.forEach((u) => {
    if (u.active === false || !u.roles) return;
    const isKeeper = Object.keys(u.roles).some((m) => (u.roles[m] || []).includes('depot_keeper'));
    if (isKeeper && (u.managerId === user.id || user.superAdmin)) {
      Object.keys(u.roles).forEach((m) => { if ((u.roles[m] || []).includes('depot_keeper')) mods.add(m); });
    }
  });
  return Array.from(mods);
}

// Gönderici (şirket) bilgisi — servis/kargo formu varsayılanı (Faz 7.4b). Gerçek üründe ayarlardan gelir.
const COMPANY_INFO = { name: 'Raryum Bilişim Hiz. A.Ş.', address: 'Bahçelievler / İstanbul 34500' };

// Yazdırılabilir servis/kargo formu — ayrı pencerede açıp yazdırır (Faz 7.4b).
function printServiceForm(a, info) {
  const w = window.open('', '_blank', 'width=820,height=940');
  if (!w) { alert('Yazdırma penceresi açılamadı. Lütfen tarayıcı pop-up engelini bu site için kapatın.'); return; }
  const warr = warrantyInfo(a);
  const warrTxt = warr ? (warr.none ? (warr.label || 'Garantisiz') : (warr.until ? (warr.until + (warr.expired ? ' (doldu)' : '')) : (warr.label || '-'))) : '-';
  const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  const cell = (k, v) => `<tr><td style="padding:7px 10px;border:1px solid #cbd5e1;background:#f1f5f9;font-weight:600;width:200px;vertical-align:top">${esc(k)}</td><td style="padding:7px 10px;border:1px solid #cbd5e1">${esc(v) || '&nbsp;'}</td></tr>`;
  const today = new Date().toLocaleDateString('tr-TR');
  const html = `<!doctype html><html lang="tr"><head><meta charset="utf-8"><title>Servis Gönderim Formu · ${esc(a.name)}</title></head>
  <body style="font-family:Arial,Helvetica,sans-serif;color:#0f172a;margin:32px;font-size:13px">
    <div style="display:flex;justify-content:space-between;align-items:flex-start;border-bottom:3px solid #2563EB;padding-bottom:12px;margin-bottom:18px">
      <div><div style="font-size:20px;font-weight:800;color:#2563EB">SERVİS GÖNDERİM / KARGO FORMU</div>
      <div style="color:#64748b;margin-top:2px">${esc(depotModuleLabel(a.module))} · Düzenleme tarihi: ${today}</div></div>
      <div style="text-align:right;font-size:12px;color:#64748b">Form No<br><b style="color:#0f172a;font-size:15px">SRV-${esc(a.id)}</b></div>
    </div>
    <h3 style="margin:16px 0 6px;font-size:14px">📤 Gönderici</h3>
    <table style="border-collapse:collapse;width:100%">${cell('Gönderici', info.sender)}${cell('Adres', info.senderAddr)}${cell('Yetkili / İletişim', info.senderContact)}</table>
    <h3 style="margin:16px 0 6px;font-size:14px">📥 Alıcı (Servis Firması)</h3>
    <table style="border-collapse:collapse;width:100%">${cell('Servis firması', info.receiver)}${cell('Adres', info.receiverAddr)}${cell('Telefon', info.receiverPhone)}</table>
    <h3 style="margin:16px 0 6px;font-size:14px">💻 Ekipman Bilgileri</h3>
    <table style="border-collapse:collapse;width:100%">${cell('Ekipman', a.name)}${cell('Adet', (a.qty || 1) + ' adet')}${cell('Seri No', a.seriNo)}${cell('Fatura / Sipariş', (a.poNo || '') + (a.supplier ? ' · ' + a.supplier : ''))}${cell('Garanti', warrTxt)}${cell('Zimmet sahibi', (a.ownerName || '') + (a.ownerDept ? ' · ' + a.ownerDept : ''))}</table>
    <h3 style="margin:16px 0 6px;font-size:14px">🔧 Arıza / Gönderim Açıklaması</h3>
    <div style="border:1px solid #cbd5e1;border-radius:6px;padding:12px;min-height:60px">${esc(info.faultNote)}</div>
    <div style="display:flex;justify-content:space-between;margin-top:48px;gap:40px">
      <div style="flex:1;border-top:1px solid #94a3b8;padding-top:6px;text-align:center;color:#64748b">Gönderen (İmza / Kaşe)</div>
      <div style="flex:1;border-top:1px solid #94a3b8;padding-top:6px;text-align:center;color:#64748b">Teslim Alan (İmza / Kaşe)</div>
    </div>
    <div style="margin-top:28px;color:#94a3b8;font-size:11px;text-align:center">Bu form IT Talep ve Bütçe Yönetim Sistemi tarafından oluşturulmuştur.</div>
  </body></html>`;
  w.document.write(html); w.document.close(); w.focus();
  setTimeout(() => { try { w.print(); } catch (e) {} }, 350);
}
function depotModuleLabel(mid) {
  const m = (window.MODULES || {})[mid];
  if (m) return m.name + ' Deposu';
  return (mid === 'admin' ? 'İdari' : mid === 'it' ? 'IT' : mid) + ' Deposu';
}

// Garanti süresi seçenekleri (Faz 7.4) — değer = ay. 'custom' → kullanıcı girer. 0 = garantisiz.
const WARRANTY_OPTS = [
  { v: 12, label: '1 yıl' }, { v: 24, label: '2 yıl' }, { v: 36, label: '3 yıl' },
  { v: 60, label: '5 yıl' }, { v: 120, label: '10 yıl' },
  { v: 3, label: '2. el (3 ay)' }, { v: 0, label: 'Garantisiz' }, { v: 'custom', label: 'Özel…' },
];
// Bir varlığın garanti durumu: { until, expired, none, monthsLeft } veya null (bilgi yok).
function warrantyInfo(a) {
  if (!a || a.warrantyMonths == null) return null;
  if (!a.warrantyMonths) return { none: true, label: a.warrantyLabel || 'Garantisiz' };
  const startStr = a.deliveryDate || a.receivedAt || null;
  const start = startStr ? new Date(startStr) : null;
  if (!start || isNaN(start.getTime())) return { label: a.warrantyLabel || (a.warrantyMonths + ' ay'), unknown: true };
  const until = new Date(start); until.setMonth(until.getMonth() + a.warrantyMonths);
  const expired = Date.now() > until.getTime();
  const monthsLeft = Math.round((until.getTime() - Date.now()) / (1000 * 60 * 60 * 24 * 30));
  return { until: until.toLocaleDateString('tr-TR'), expired, monthsLeft, label: a.warrantyLabel };
}
// Kart üstünde garanti rozeti (varsa)
function WarrantyBadge({ a, c }) {
  const w = warrantyInfo(a);
  if (!w) return null;
  if (w.none) return <span style={{ fontSize: 11, fontWeight: 600, color: c.muted, background: c.chipBg, padding: '2px 8px', borderRadius: 999 }}>Garantisiz</span>;
  const col = w.expired ? c.danger : '#047857';
  const bg = w.expired ? 'rgba(239,68,68,0.12)' : 'rgba(16,185,129,0.12)';
  return <span title={w.until ? `Garanti bitişi: ${w.until}` : ''} style={{ fontSize: 11, fontWeight: 600, color: col, background: bg, padding: '2px 8px', borderRadius: 999 }}>
    🛡️ {w.expired ? 'Garanti doldu' : (w.until ? `Garanti: ${w.until}` : w.label)}
  </span>;
}

function DepotPanel({ 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 assets = useAssetsSnapshot();
  const me = useCurrentUser();

  // Depo sorumlusu: rolünde depot_keeper olan modüller (tam depo işlemleri).
  const keeperModules = (me && me.roles)
    ? Object.keys(me.roles).filter((m) => (me.roles[m] || []).includes('depot_keeper'))
    : [];
  const isKeeper = keeperModules.length > 0;
  // IT Müdürü / onaycı: depo sorumlusunun yöneticisi → yalnız HURDA onaylarını görür.
  const overseeModules = overseenDepotModules(me);
  const approverOnly = !isKeeper && overseeModules.length > 0;
  const myModules = isKeeper ? keeperModules : overseeModules;
  const mine = assets.filter((a) => myModules.includes(a.module || 'it'));
  const canApproveScrap = (a) => !!(me && a.scrap && (a.scrap.approverId === me.id || me.superAdmin));
  // Depo sorguları (Faz 10.2): satınalmanın "depodan verilebilir mi?" diye sorduğu bekleyen talepler.
  const approvals = useApprovalsSnapshot();
  const inquiries = (approvals || []).filter((r) => r.poolInquiry && r.poolInquiry.status === 'pending' && keeperModules.includes((r.poolInquiry.moduleId) || 'it'));

  const inTransit = mine.filter((a) => a.status === 'in_transit');
  const received = mine.filter((a) => a.status === 'received');
  const inUse = mine.filter((a) => a.status === 'in_use');
  const inService = mine.filter((a) => a.status === 'in_service');
  const returnPending = mine.filter((a) => a.status === 'return_pending');
  const pool = mine.filter((a) => a.status === 'in_pool');
  const scrapPending = mine.filter((a) => a.status === 'scrap_pending');
  const hurdaList = mine.filter((a) => a.status === 'scrap_pending' || a.status === 'scrapped');
  const [tab, setTab] = React.useState(approverOnly ? 'scrapped' : 'in_transit');
  const [q, setQ] = React.useState('');
  const [receiveTarget, setReceiveTarget] = React.useState(null);
  const [serviceTarget, setServiceTarget] = React.useState(null);
  const [returnTarget, setReturnTarget] = React.useState(null);
  const [returnRecvTarget, setReturnRecvTarget] = React.useState(null);
  const [reassignTarget, setReassignTarget] = React.useState(null);
  const [scrapTarget, setScrapTarget] = React.useState(null);
  const tabList = tab === 'in_transit' ? inTransit : tab === 'received' ? received : tab === 'in_service' ? inService : tab === 'return_pending' ? returnPending : tab === 'in_pool' ? pool : tab === 'scrapped' ? hurdaList : inUse;
  const ql = q.trim().toLowerCase();
  const shown = ql
    ? tabList.filter((a) => [a.name, a.seriNo, a.ownerName, a.ownerDept, a.poNo, a.reqId, a.supplier].filter(Boolean).join(' ').toLowerCase().includes(ql))
    : tabList;

  const tabBtn = (key, label, count) => (
    <button onClick={() => setTab(key)} style={{
      appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
      padding: '9px 14px', borderRadius: 999, border: `1px solid ${tab === key ? c.primary : c.border}`,
      background: tab === key ? c.primary : 'transparent', color: tab === key ? '#fff' : c.muted,
      fontSize: 13, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 7,
    }}>
      {label}
      {count > 0 && <span style={{ fontSize: 11, fontWeight: 700, padding: '1px 7px', borderRadius: 999, background: tab === key ? 'rgba(255,255,255,0.25)' : c.chipBg, color: tab === key ? '#fff' : c.muted }}>{count}</span>}
    </button>
  );

  return (
    <div style={{ minHeight: '100%', background: c.bg, fontFamily: 'Inter, system-ui, sans-serif' }}>
      {receiveTarget && <ReceiveModal a={receiveTarget} c={c} onClose={() => setReceiveTarget(null)} />}
      {serviceTarget && <ServiceFormModal a={serviceTarget} c={c} me={me} onClose={() => setServiceTarget(null)} />}
      {returnTarget && <ServiceReturnModal a={returnTarget} c={c} onClose={() => setReturnTarget(null)} />}
      {returnRecvTarget && <ReturnReceiveModal a={returnRecvTarget} c={c} onScrap={() => { const t = returnRecvTarget; setReturnRecvTarget(null); setScrapTarget(t); }} onClose={() => setReturnRecvTarget(null)} />}
      {reassignTarget && <ReassignModal a={reassignTarget} c={c} onClose={() => setReassignTarget(null)} />}
      {scrapTarget && <ScrapModal a={scrapTarget} c={c} onClose={() => setScrapTarget(null)} />}
      <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' }}>
        <div style={{ marginBottom: 16 }}>
          <h1 style={{ margin: 0, fontSize: isMobile ? 20 : 23, fontWeight: 700, color: c.text, letterSpacing: '-0.015em' }}>{approverOnly ? 'Hurda Onayları' : 'Depo'}</h1>
          <div style={{ fontSize: 13, color: c.muted, marginTop: 4 }}>
            {myModules.map(depotModuleLabel).join(' · ')} · {approverOnly
              ? (scrapPending.length > 0 ? `${scrapPending.length} hurda talebi onayınızda` : 'onay bekleyen hurda yok')
              : (inTransit.length > 0 ? `${inTransit.length} kalem teslim bekliyor` : 'teslim bekleyen yok')}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
          {!approverOnly && tabBtn('in_transit', 'Teslim Bekleyenler', inTransit.length)}
          {!approverOnly && tabBtn('received', 'Teslim Alınanlar', received.length)}
          {!approverOnly && tabBtn('in_use', 'Zimmetlenenler', inUse.length)}
          {!approverOnly && tabBtn('in_service', 'Serviste', inService.length)}
          {!approverOnly && tabBtn('return_pending', 'İade Bekleyenler', returnPending.length)}
          {!approverOnly && tabBtn('in_pool', 'Havuz', pool.length)}
          {!approverOnly && tabBtn('inquiries', 'Depo Sorguları', inquiries.length)}
          {tabBtn('scrapped', approverOnly ? 'Hurda Onayları' : 'Hurda', approverOnly ? scrapPending.length : hurdaList.length)}
        </div>

        {tab === 'inquiries' ? (
          inquiries.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 depo sorgusu yok</div>
              Satınalma, talepteki ürün havuzda mevcutsa "depodan verilebilir mi?" diye sorar; buradan Evet/Hayır yanıtlarsınız.
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {inquiries.map((r) => <PoolInquiryCard key={r.id} r={r} c={c} isMobile={isMobile} />)}
            </div>
          )
        ) : (
        <React.Fragment>
        <div style={{ position: 'relative', marginBottom: 16 }}>
          <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: c.muted, fontSize: 14, pointerEvents: 'none' }}>🔍</span>
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Seri no, zimmet sahibi, ürün veya sipariş no ile ara…"
            style={{ width: '100%', boxSizing: 'border-box', padding: '10px 36px', borderRadius: 10, border: `1px solid ${c.border}`, background: c.inputBg || c.surface, color: c.text, fontSize: 13.5, fontFamily: 'inherit', outline: 'none' }} />
          {q && <button onClick={() => setQ('')} style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', color: c.muted, fontSize: 15, fontWeight: 700 }}>✕</button>}
        </div>

        {tabList.length > 0 && shown.length === 0 ? (
          <div style={{ background: c.card, border: `1px dashed ${c.border}`, borderRadius: 16, padding: 40, textAlign: 'center', color: c.muted }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: c.text, marginBottom: 4 }}>Eşleşen kayıt yok</div>
            “{q}” aramasıyla bu sekmede sonuç bulunamadı.
          </div>
        ) : 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 === 'in_transit' ? 'Teslim bekleyen ekipman yok' : tab === 'received' ? 'Teslim alınan, imza bekleyen ekipman yok' : tab === 'in_service' ? 'Serviste ekipman yok' : tab === 'return_pending' ? 'İade bekleyen ekipman yok' : tab === 'in_pool' ? 'Havuzda ekipman yok' : tab === 'scrapped' ? 'Hurdaya ayrılmış ekipman yok' : 'Zimmetlenmiş ekipman yok'}
            </div>
            {tab === 'in_transit' ? 'Satınalma siparişi tamamlanınca zimmetli ekipmanlar burada listelenir.' : tab === 'received' ? 'Teslim aldıklarınız kullanıcı imzasına kadar burada bekler.' : tab === 'in_service' ? 'Servise gönderdiğiniz ekipmanlar burada takip edilir.' : tab === 'return_pending' ? 'Kullanıcılar ekipman iade ettikçe ya da personel ayrılışında burada listelenir; teslim alıp havuza ya da hurdaya yönlendirin.' : tab === 'in_pool' ? 'İade alınıp havuza eklenen ekipmanlar burada birikir; yeni personele yeniden atayabilir ya da hurdaya gönderebilirsiniz.' : tab === 'scrapped' ? 'Hurdaya ayrılan ekipmanlar burada birikir; İSG & Çevre birimi satış/imha sürecini yürütür.' : 'Kullanıcı zimmet formunu imzaladıkça burada görünür; buradan servise ya da hurdaya gönderebilirsiniz.'}
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {shown.map((a) => <AssetCard key={a.id} a={a} c={c} isMobile={isMobile} onReceive={() => setReceiveTarget(a)} onService={() => setServiceTarget(a)} onReturn={() => setReturnTarget(a)} onReturnReceive={() => setReturnRecvTarget(a)} onReassign={() => setReassignTarget(a)} onScrap={() => setScrapTarget(a)} canApproveScrap={canApproveScrap(a)} />)}
          </div>
        )}
        </React.Fragment>
        )}
      </div>
    </div>
  );
}

// Depo sorgusu kartı (Faz 10.2): satınalmanın "depodan verilebilir mi?" sorusu — Evet/Hayır yanıtı.
function PoolInquiryCard({ r, c, isMobile }) {
  const inq = r.poolInquiry || {};
  const items = inq.items || [];
  const yes = () => {
    if (!window.confirm('Bu ürünü HAVUZDAN vereceğinizi onaylıyor musunuz?\n\nTalep İPTAL edilecek (yeni sipariş açılmaz). Ardından "Havuz" sekmesinden ilgili ekipmanı "Yeniden ata" ile kullanıcıya zimmetleyin.')) return;
    window.__approvals && window.__approvals.answerPool && window.__approvals.answerPool(r.id, 'yes');
  };
  const no = () => {
    const note = window.prompt('Depodan VERİLEMİYOR — satınalma siparişe devam edecek.\n\nGerekçe (opsiyonel, örn. stoktaki cihaz arızalı / model uymuyor):', '');
    if (note === null) return;
    window.__approvals && window.__approvals.answerPool && window.__approvals.answerPool(r.id, 'no', note.trim());
  };
  return (
    <div style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, padding: isMobile ? '14px 16px' : '16px 20px', borderLeft: '4px solid #0369A1' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', alignItems: 'flex-start' }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: c.text }}>♻️ Depodan verilebilir mi?</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>
            {r.requester || 'Talep'} · talep {r.id} · {inq.askedByName || 'Satınalma'} sordu{inq.askedAt ? ` · ${inq.askedAt}` : ''}
          </div>
        </div>
        <span style={{ fontSize: 11, fontWeight: 700, color: '#B45309', background: 'rgba(245,158,11,0.14)', padding: '3px 9px', borderRadius: 999, whiteSpace: 'nowrap' }}>⏳ Yanıt bekleniyor</span>
      </div>

      <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
        {items.map((x, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, background: c.surface, border: `1px solid ${c.borderSoft}`, borderRadius: 10, padding: '9px 13px' }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: c.text }}>{x.name}</span>
            <span style={{ fontSize: 11.5, fontWeight: 700, color: '#0369A1', whiteSpace: 'nowrap' }}>♻️ Havuzda {x.units} adet</span>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', gap: 10, marginTop: 14, flexWrap: 'wrap' }}>
        <button onClick={yes} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: 'none', background: c.success, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 16px', borderRadius: 10 }}>✅ Evet, havuzdan veririz · talep iptal</button>
        <button onClick={no} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.danger, fontSize: 13, fontWeight: 700, padding: '10px 16px', borderRadius: 10 }}>❌ Hayır · siparişe devam</button>
      </div>
    </div>
  );
}

function AssetCard({ a, c, isMobile, onReceive, onService, onReturn, onReturnReceive, onReassign, onScrap, canApproveScrap }) {
  const meta = DEPOT_STATUS_META[a.status] || DEPOT_STATUS_META.in_transit;
  const [open, setOpen] = React.useState(false);
  const img = window.productImgSrc ? window.productImgSrc(a) : null;
  const scrapBtn = { appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 600, color: '#6B7280', background: 'transparent', border: 'none' };
  const approveScrap = () => {
    if (!window.confirm(`${a.name} ekipmanının hurdaya ayrılmasını ONAYLIYOR musunuz?\n\nGerekçe: ${(a.scrap && a.scrap.reason) || '—'}`)) return;
    window.__assets && window.__assets.approveScrap && window.__assets.approveScrap(a.id);
  };
  const rejectScrap = () => {
    const note = window.prompt('Hurda talebini REDDET — ekipman tekrar kullanıma döner.\n\nRed gerekçesi (opsiyonel):', '');
    if (note === null) return;
    window.__assets && window.__assets.rejectScrap && window.__assets.rejectScrap(a.id, note);
  };

  return (
    <div style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, overflow: 'hidden' }}>
      <div style={{ padding: isMobile ? '14px 16px' : '16px 20px', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
        <div style={{ width: 56, height: 56, borderRadius: 12, border: `1px solid ${c.border}`, background: c.imgBg, overflow: 'hidden', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {img ? <img src={img} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
               : <span style={{ fontSize: 16, fontWeight: 700, color: c.muted }}>{(a.name || '?').charAt(0)}</span>}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 15, fontWeight: 600, color: c.text }}>{a.name}</span>
            <span style={{ fontSize: 11, fontWeight: 700, color: meta.color, background: meta.bg, padding: '2px 8px', borderRadius: 999 }}>{meta.icon} {meta.label}</span>
            <WarrantyBadge a={a} c={c} />
          </div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 4 }}>
            {a.status === 'in_pool'
              ? <React.Fragment>{a.qty} adet · ♻️ <b style={{ color: c.text }}>departman havuzu</b>{a.pool && a.pool.fromOwnerName ? ` · önceki: ${a.pool.fromOwnerName}` : ''}{a.pool && a.pool.fromOwnerDept ? ` · ${a.pool.fromOwnerDept}` : ''}</React.Fragment>
              : <React.Fragment>{a.qty} adet · zimmet sahibi <b style={{ color: c.text }}>{a.ownerName || '—'}</b>{a.ownerDept ? ` · ${a.ownerDept}` : ''}</React.Fragment>}
          </div>
          <div style={{ fontSize: 12, color: c.subtle, marginTop: 3 }}>
            Sipariş {a.poNo}{a.supplier ? ` · ${a.supplier}` : ''} · talep {a.reqId}
          </div>
          {a.seriNo && <div style={{ fontSize: 12, color: c.subtle, marginTop: 3 }}>Seri No: <b style={{ color: c.text }}>{a.seriNo}</b></div>}
          {a.status === 'in_service' && a.service && (
            <div style={{ fontSize: 12, color: '#C2410C', marginTop: 4, fontWeight: 600 }}>🔧 {a.service.receiver || 'Servis'}{a.service.sentAt ? ` · ${a.service.sentAt}` : ''}{a.service.faultNote ? ` — ${a.service.faultNote}` : ''}</div>
          )}
          {a.status === 'return_pending' && a.return && (
            <div style={{ fontSize: 12, color: '#7C3AED', marginTop: 4, fontWeight: 600 }}>↩️ {a.return.requestedByName} iade · {a.return.requestedAt}{a.return.offboarding ? ' · personel ayrılışı' : ''}{a.return.reason ? ` — ${a.return.reason}` : ''}</div>
          )}
          {a.status === 'in_pool' && a.pool && (
            <div style={{ fontSize: 12, color: '#0369A1', marginTop: 4, fontWeight: 600 }}>♻️ {a.pool.receivedByName} havuza aldı · {a.pool.receivedAt}{a.pool.note ? ` — ${a.pool.note}` : ''}</div>
          )}
          {a.status === 'scrap_pending' && a.scrap && (
            <div style={{ fontSize: 12, color: '#B45309', marginTop: 4, fontWeight: 600 }}>⏳ {a.scrap.requestedByName} hurda talebi · {a.scrap.requestedAt}{a.scrap.reason ? ` — ${a.scrap.reason}` : ''}{a.scrap.approverName ? ` · onay: ${a.scrap.approverName}` : ''}</div>
          )}
          {a.status === 'scrapped' && a.scrap && (
            <div style={{ fontSize: 12, color: '#6B7280', marginTop: 4, fontWeight: 600 }}>🗑️ {a.scrap.at}{a.scrap.reason ? ` — ${a.scrap.reason}` : ''}{a.scrap.sold ? ' · satıldı' : ' · satış bekliyor'}</div>
          )}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end' }}>
          {a.status === 'in_transit' && (
            <button onClick={onReceive} style={{ appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: '#fff', background: c.success, padding: '9px 14px', borderRadius: 10, whiteSpace: 'nowrap' }}>📦 Teslim al</button>
          )}
          {a.status === 'received' && (
            <span style={{ fontSize: 11.5, fontWeight: 600, color: c.muted, textAlign: 'right', maxWidth: 140 }}>Kullanıcının zimmet formu imzası bekleniyor</span>
          )}
          {a.status === 'in_use' && (
            <React.Fragment>
              {onService && <button onClick={onService} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: '#fff', background: '#C2410C', border: 'none', padding: '9px 14px', borderRadius: 10, whiteSpace: 'nowrap' }}>🔧 Servise gönder</button>}
              {onScrap && <button onClick={onScrap} style={scrapBtn}>🗑️ Hurdaya gönder</button>}
            </React.Fragment>
          )}
          {a.status === 'in_service' && (
            <React.Fragment>
              {onReturn && <button onClick={onReturn} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: '#fff', background: c.success, border: 'none', padding: '9px 14px', borderRadius: 10, whiteSpace: 'nowrap' }}>↩️ Servisten döndü</button>}
              <button onClick={() => printServiceForm(a, a.service || {})} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 600, color: c.primary, background: 'transparent', border: 'none' }}>🖨️ Kargo formu</button>
              {onScrap && <button onClick={onScrap} style={scrapBtn}>🗑️ Hurdaya gönder</button>}
            </React.Fragment>
          )}
          {a.status === 'return_pending' && (
            <button onClick={onReturnReceive} style={{ appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: '#fff', background: '#0369A1', padding: '9px 14px', borderRadius: 10, whiteSpace: 'nowrap' }}>📥 İade teslim al</button>
          )}
          {a.status === 'in_pool' && (
            <React.Fragment>
              <button onClick={onReassign} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: '#fff', background: '#0369A1', border: 'none', padding: '9px 14px', borderRadius: 10, whiteSpace: 'nowrap' }}>♻️ Yeniden ata</button>
              {onScrap && <button onClick={onScrap} style={scrapBtn}>🗑️ Hurdaya gönder</button>}
            </React.Fragment>
          )}
          {a.status === 'scrap_pending' && (
            canApproveScrap ? (
              <React.Fragment>
                <button onClick={approveScrap} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: '#fff', background: c.success, border: 'none', padding: '9px 14px', borderRadius: 10, whiteSpace: 'nowrap' }}>✅ Hurdayı onayla</button>
                <button onClick={rejectScrap} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, color: c.danger, background: 'transparent', border: 'none' }}>❌ Reddet · geri sahaya</button>
              </React.Fragment>
            ) : (
              <span style={{ fontSize: 11.5, fontWeight: 600, color: '#B45309', textAlign: 'right', maxWidth: 150 }}>⏳ {a.scrap && a.scrap.approverName ? a.scrap.approverName + ' onayı bekleniyor' : 'Müdür onayı bekleniyor'}</span>
            )
          )}
          {a.docDataUrl && (
            <a href={a.docDataUrl} target="_blank" rel="noreferrer" style={{ fontSize: 11.5, fontWeight: 600, color: c.primary, textDecoration: 'none' }}>📄 Fatura/İrsaliye</a>
          )}
          {a.service && a.service.returnDocDataUrl && (
            <a href={a.service.returnDocDataUrl} target="_blank" rel="noreferrer" style={{ fontSize: 11.5, fontWeight: 600, color: c.primary, textDecoration: 'none' }}>📄 Servis raporu</a>
          )}
          {a.scrap && a.scrap.docDataUrl && (
            <a href={a.scrap.docDataUrl} target="_blank" rel="noreferrer" style={{ fontSize: 11.5, fontWeight: 600, color: c.primary, textDecoration: 'none' }}>📄 Hurda tutanağı</a>
          )}
          <button onClick={() => setOpen((x) => !x)} style={{ appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', color: c.primary, fontSize: 12.5, fontWeight: 600 }}>{open ? '▾ Geçmiş' : '▸ Geçmiş'}</button>
        </div>
      </div>
      {open && (a.timeline || []).length > 0 && (
        <div style={{ borderTop: `1px solid ${c.borderSoft}`, padding: '12px 20px', background: c.surface }}>
          {(a.timeline || []).map((ev, i) => {
            const m = DEPOT_STATUS_META[ev.status] || {};
            return (
              <div key={i} style={{ display: 'flex', gap: 10, fontSize: 12, color: c.muted, padding: '4px 0' }}>
                <span style={{ minWidth: 18 }}>{m.icon || '•'}</span>
                <span style={{ color: c.text, fontWeight: 600, minWidth: 140 }}>{m.label || ev.status}</span>
                <span>{ev.byName}{ev.note ? ` · ${ev.note}` : ''} · {ev.at}</span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// Teslim alma formu (Faz 7.4): seri no + teslim/fatura tarihi + garanti süresi + fatura/irsaliye foto.
function ReceiveModal({ a, c, onClose }) {
  const isMobile = useIsMobile();
  const today = new Date().toISOString().slice(0, 10);
  const [seriNo, setSeriNo] = React.useState('');
  const [deliveryDate, setDeliveryDate] = React.useState(today);
  const [warrantySel, setWarrantySel] = React.useState(12);          // ay (veya 'custom')
  const [customVal, setCustomVal] = React.useState('');
  const [customUnit, setCustomUnit] = React.useState('yil');          // 'yil' | 'ay'
  const [docDataUrl, setDocDataUrl] = React.useState('');
  const [docName, setDocName] = React.useState('');

  const onFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    if (f.size > 4 * 1024 * 1024) { alert('Dosya 4 MB\'tan küçük olmalı.'); return; }
    const r = new FileReader();
    r.onload = () => { setDocDataUrl(r.result); setDocName(f.name); };
    r.readAsDataURL(f);
  };

  const resolveWarranty = () => {
    if (warrantySel === 'custom') {
      const n = parseInt(customVal, 10) || 0;
      const months = customUnit === 'yil' ? n * 12 : n;
      return { months, label: n ? `${n} ${customUnit === 'yil' ? 'yıl' : 'ay'}` : 'Garantisiz' };
    }
    const opt = WARRANTY_OPTS.find((o) => o.v === warrantySel) || {};
    return { months: warrantySel, label: opt.label || '' };
  };

  const submit = () => {
    const w = resolveWarranty();
    window.__assets && window.__assets.receive && window.__assets.receive(a.id, {
      seriNo: seriNo.trim(), deliveryDate, warrantyMonths: w.months, warrantyLabel: w.label, docDataUrl,
    });
    onClose();
  };

  const lbl = { fontSize: 12, fontWeight: 600, color: c.muted, display: 'block', marginBottom: 6 };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: `1px solid ${c.border}`, background: c.input || c.surface, color: c.text, fontSize: 13.5, fontFamily: 'inherit' };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 540, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>Teslim Al · {a.name}</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>{a.qty} adet · zimmet sahibi {a.ownerName} · sipariş {a.poNo}</div>
        </div>
        <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <label style={lbl}>Seri numarası <span style={{ color: c.subtle, fontWeight: 400 }}>(garanti takibi için)</span></label>
            <input value={seriNo} onChange={(e) => setSeriNo(e.target.value)} style={inp} placeholder="örn. SN-5CG1234ABC" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
            <div>
              <label style={lbl}>Teslim / fatura tarihi</label>
              <input type="date" value={deliveryDate} onChange={(e) => setDeliveryDate(e.target.value)} style={inp} />
            </div>
            <div>
              <label style={lbl}>Garanti süresi</label>
              <select value={warrantySel} onChange={(e) => setWarrantySel(e.target.value === 'custom' ? 'custom' : parseInt(e.target.value, 10))} style={inp}>
                {WARRANTY_OPTS.map((o) => <option key={String(o.v)} value={o.v}>{o.label}</option>)}
              </select>
            </div>
          </div>
          {warrantySel === 'custom' && (
            <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end' }}>
              <div style={{ flex: 1 }}>
                <label style={lbl}>Özel garanti süresi</label>
                <input value={customVal} onChange={(e) => setCustomVal(e.target.value)} inputMode="numeric" style={inp} placeholder="örn. 10" />
              </div>
              <select value={customUnit} onChange={(e) => setCustomUnit(e.target.value)} style={{ ...inp, width: 110, flex: 'none' }}>
                <option value="yil">Yıl</option>
                <option value="ay">Ay</option>
              </select>
            </div>
          )}
          <div>
            <label style={lbl}>Fatura / irsaliye fotoğrafı <span style={{ color: c.subtle, fontWeight: 400 }}>(opsiyonel)</span></label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <label style={{ cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: c.primary, border: `1px solid ${c.border}`, borderRadius: 10, padding: '9px 14px' }}>
                📎 Dosya seç
                <input type="file" accept="image/*,.pdf" onChange={onFile} style={{ display: 'none' }} />
              </label>
              {docName && <span style={{ fontSize: 12, color: c.muted }}>{docName} <button onClick={() => { setDocDataUrl(''); setDocName(''); }} style={{ appearance: 'none', border: 'none', background: 'transparent', color: c.danger, cursor: 'pointer', fontWeight: 700 }}>✕</button></span>}
            </div>
            <div style={{ fontSize: 11, color: c.subtle, marginTop: 6 }}>İrsaliye/fatura yoksa yalnızca teslim tarihini girmeniz yeterli (garanti o tarihten başlar).</div>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}` }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>Vazgeç</button>
          <button onClick={submit} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: 'none', background: c.success, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10 }}>📦 Teslim aldım</button>
        </div>
      </div>
    </div>
  );
}

// Servise gönderim formu (Faz 7.4b): gönderici/alıcı/arıza → in_service + yazdırılabilir kargo formu.
function ServiceFormModal({ a, c, me, onClose }) {
  const isMobile = useIsMobile();
  const suppliers = (typeof useSuppliersSnapshot === 'function' ? useSuppliersSnapshot() : ((window.__suppliers && window.__suppliers.items) || [])).filter((s) => s.status === 'active');
  const supplierOpts = suppliers.map((s) => ({ value: s.id, label: s.company || s.shortName, sub: [s.city, s.phone || s.gsm].filter(Boolean).join(' · ') }));

  const [sender, setSender] = React.useState(COMPANY_INFO.name);
  const [senderAddr, setSenderAddr] = React.useState(COMPANY_INFO.address);
  const [senderContact, setSenderContact] = React.useState(me ? `${me.name}${me.phone ? ' · ' + me.phone : ''}` : '');
  const [supplierId, setSupplierId] = React.useState('');
  const [manualFirm, setManualFirm] = React.useState(false);
  const [receiver, setReceiver] = React.useState('');
  const [receiverAddr, setReceiverAddr] = React.useState('');
  const [receiverPhone, setReceiverPhone] = React.useState('');
  const [faultNote, setFaultNote] = React.useState('');

  // Tedarikçi seçilince firma adı + adres + telefon otomatik dolar
  const pickSupplier = (id) => {
    setSupplierId(id);
    const s = suppliers.find((x) => x.id === id);
    if (s) {
      setReceiver(s.company || s.shortName || '');
      setReceiverAddr([s.address, s.city, s.country].filter(Boolean).join(', '));
      setReceiverPhone(s.phone || s.gsm || '');
    }
  };

  const info = () => ({ sender, senderAddr, senderContact, receiver, receiverAddr, receiverPhone, faultNote });
  const valid = receiver.trim() && faultNote.trim();
  const submit = () => {
    if (!valid) { alert('Servis firması ve arıza açıklaması zorunludur.'); return; }
    window.__assets && window.__assets.sendToService && window.__assets.sendToService(a.id, info());
    printServiceForm(a, info());
    onClose();
  };

  const lbl = { fontSize: 12, fontWeight: 600, color: c.muted, display: 'block', marginBottom: 6 };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: `1px solid ${c.border}`, background: c.inputBg || c.input || c.surface, color: c.text, fontSize: 13.5, fontFamily: 'inherit' };
  const linkBtn = { appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', color: c.primary, fontSize: 11.5, fontWeight: 600 };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 560, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>Servise Gönder · {a.name}</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>Seri No: {a.seriNo || '—'} · zimmet sahibi {a.ownerName}</div>
        </div>
        <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: c.text, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Gönderici</div>
          <div><label style={lbl}>Gönderici firma</label><input value={sender} onChange={(e) => setSender(e.target.value)} style={inp} /></div>
          <div><label style={lbl}>Gönderici adresi</label><textarea value={senderAddr} onChange={(e) => setSenderAddr(e.target.value)} rows={2} style={{ ...inp, resize: 'vertical' }} /></div>
          <div><label style={lbl}>Yetkili / iletişim</label><input value={senderContact} onChange={(e) => setSenderContact(e.target.value)} style={inp} /></div>

          <div style={{ fontSize: 12, fontWeight: 700, color: c.text, textTransform: 'uppercase', letterSpacing: '0.04em', marginTop: 4 }}>Alıcı (Servis Firması)</div>
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <label style={lbl}>Servis firması *</label>
              <button type="button" onClick={() => setManualFirm((m) => !m)} style={linkBtn}>{manualFirm ? '↩ Tedarikçiden seç' : '✏️ Listede yok? elle gir'}</button>
            </div>
            {manualFirm
              ? <input value={receiver} onChange={(e) => setReceiver(e.target.value)} style={inp} placeholder="örn. Dell Yetkili Teknik Servis" />
              : <SearchPicker c={c} options={supplierOpts} value={supplierId} onChange={pickSupplier} placeholder="Tedarikçi ara / seç…" />}
          </div>
          <div><label style={lbl}>Adres</label><textarea value={receiverAddr} onChange={(e) => setReceiverAddr(e.target.value)} rows={2} style={{ ...inp, resize: 'vertical' }} placeholder="Servis firması teslim adresi" /></div>
          <div><label style={lbl}>Telefon</label><input value={receiverPhone} onChange={(e) => setReceiverPhone(e.target.value)} style={inp} placeholder="+90 ..." /></div>

          <div><label style={lbl}>Arıza / gönderim açıklaması *</label><textarea value={faultNote} onChange={(e) => setFaultNote(e.target.value)} rows={3} style={{ ...inp, resize: 'vertical' }} placeholder="örn. Açılmıyor, şarj tutmuyor; garanti kapsamında onarım." /></div>
          <div style={{ fontSize: 11.5, color: c.subtle }}>Seri No, fatura/sipariş ve garanti bilgisi kargo formuna otomatik eklenir.</div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}` }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>Vazgeç</button>
          <button onClick={submit} disabled={!valid} style={{ appearance: 'none', cursor: valid ? 'pointer' : 'default', fontFamily: 'inherit', border: 'none', background: valid ? '#C2410C' : c.border, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10, opacity: valid ? 1 : 0.7 }}>🖨️ Servise gönder ve yazdır</button>
        </div>
      </div>
    </div>
  );
}

// Servisten dönüş formu (Faz 7.4b eki): onarım notu + servis raporu/formu dosya yükleme.
function ServiceReturnModal({ a, c, onClose }) {
  const isMobile = useIsMobile();
  const [note, setNote] = React.useState('');
  const [docDataUrl, setDocDataUrl] = React.useState('');
  const [docName, setDocName] = React.useState('');
  const onFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    if (f.size > 4 * 1024 * 1024) { alert('Dosya 4 MB\'tan küçük olmalı.'); return; }
    const r = new FileReader();
    r.onload = () => { setDocDataUrl(r.result); setDocName(f.name); };
    r.readAsDataURL(f);
  };
  const submit = () => {
    window.__assets && window.__assets.returnFromService && window.__assets.returnFromService(a.id, { note: note.trim(), docDataUrl });
    onClose();
  };
  const lbl = { fontSize: 12, fontWeight: 600, color: c.muted, display: 'block', marginBottom: 6 };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: `1px solid ${c.border}`, background: c.inputBg || c.surface, color: c.text, fontSize: 13.5, fontFamily: 'inherit' };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 500, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>Servisten Döndü · {a.name}</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>{(a.service && a.service.receiver) || 'Servis'} · Seri No: {a.seriNo || '—'}</div>
        </div>
        <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div><label style={lbl}>Onarım özeti / not</label><textarea value={note} onChange={(e) => setNote(e.target.value)} rows={3} style={{ ...inp, resize: 'vertical' }} placeholder="örn. Anakart değişti, garanti kapsamında onarıldı." /></div>
          <div>
            <label style={lbl}>Servis formu / raporu <span style={{ color: c.subtle, fontWeight: 400 }}>(opsiyonel)</span></label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <label style={{ cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: c.primary, border: `1px solid ${c.border}`, borderRadius: 10, padding: '9px 14px' }}>
                📎 Dosya seç
                <input type="file" accept="image/*,.pdf" onChange={onFile} style={{ display: 'none' }} />
              </label>
              {docName && <span style={{ fontSize: 12, color: c.muted }}>{docName} <button onClick={() => { setDocDataUrl(''); setDocName(''); }} style={{ appearance: 'none', border: 'none', background: 'transparent', color: c.danger, cursor: 'pointer', fontWeight: 700 }}>✕</button></span>}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}` }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>Vazgeç</button>
          <button onClick={submit} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: 'none', background: c.success, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10 }}>↩️ Servisten döndü olarak işaretle</button>
        </div>
      </div>
    </div>
  );
}

// Hurdaya ayırma formu (Faz 9): gerekçe (zorunlu) + opsiyonel tutanak/foto.
function ScrapModal({ a, c, onClose }) {
  const isMobile = useIsMobile();
  const [reason, setReason] = React.useState('');
  const [docDataUrl, setDocDataUrl] = React.useState('');
  const [docName, setDocName] = React.useState('');
  const onFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    if (f.size > 4 * 1024 * 1024) { alert('Dosya 4 MB\'tan küçük olmalı.'); return; }
    const r = new FileReader();
    r.onload = () => { setDocDataUrl(r.result); setDocName(f.name); };
    r.readAsDataURL(f);
  };
  const valid = reason.trim();
  const submit = () => {
    if (!valid) { alert('Hurda gerekçesi zorunludur.'); return; }
    window.__assets && window.__assets.scrap && window.__assets.scrap(a.id, { reason: reason.trim(), docDataUrl });
    onClose();
  };
  const lbl = { fontSize: 12, fontWeight: 600, color: c.muted, display: 'block', marginBottom: 6 };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: `1px solid ${c.border}`, background: c.inputBg || c.surface, color: c.text, fontSize: 13.5, fontFamily: 'inherit' };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 500, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>Hurdaya Gönder · {a.name}</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>Seri No: {a.seriNo || '—'} · zimmet sahibi {a.ownerName}</div>
        </div>
        <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ fontSize: 12.5, color: '#B45309', background: 'rgba(245,158,11,0.10)', border: '1px solid rgba(245,158,11,0.30)', borderRadius: 10, padding: '10px 12px' }}>
            Tamir edilemeyen / kullanım dışı ekipman hurdaya ayrılır. Hurda kalemi, İSG & Çevre biriminin satış/imha sürecine düşer.
          </div>
          <div><label style={lbl}>Hurda gerekçesi *</label><textarea value={reason} onChange={(e) => setReason(e.target.value)} rows={3} style={{ ...inp, resize: 'vertical' }} placeholder="örn. Tamir edilemiyor, ekonomik ömrü doldu, fiziksel hasar." /></div>
          <div>
            <label style={lbl}>Tutanak / fotoğraf <span style={{ color: c.subtle, fontWeight: 400 }}>(opsiyonel)</span></label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <label style={{ cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: c.primary, border: `1px solid ${c.border}`, borderRadius: 10, padding: '9px 14px' }}>
                📎 Dosya seç
                <input type="file" accept="image/*,.pdf" onChange={onFile} style={{ display: 'none' }} />
              </label>
              {docName && <span style={{ fontSize: 12, color: c.muted }}>{docName} <button onClick={() => { setDocDataUrl(''); setDocName(''); }} style={{ appearance: 'none', border: 'none', background: 'transparent', color: c.danger, cursor: 'pointer', fontWeight: 700 }}>✕</button></span>}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}` }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>Vazgeç</button>
          <button onClick={submit} disabled={!valid} style={{ appearance: 'none', cursor: valid ? 'pointer' : 'default', fontFamily: 'inherit', border: 'none', background: valid ? '#6B7280' : c.border, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10, opacity: valid ? 1 : 0.7 }}>🗑️ Hurdaya gönder</button>
        </div>
      </div>
    </div>
  );
}

// İade teslim alma (Faz 8.2): depo sorumlusu iadeyi teslim alır → durumunu değerlendirip
// HAVUZA ekler (yeniden kullanılabilir) ya da doğrudan HURDAYA yönlendirir (bozuk/eski).
function ReturnReceiveModal({ a, c, onScrap, onClose }) {
  const isMobile = useIsMobile();
  const [note, setNote] = React.useState('');
  const r = a.return || {};
  const toPool = () => {
    window.__assets && window.__assets.receiveReturn && window.__assets.receiveReturn(a.id, { note: note.trim() });
    onClose();
  };
  const row = (k, v) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 13, padding: '6px 0' }}>
      <span style={{ color: c.muted }}>{k}</span>
      <span style={{ color: c.text, fontWeight: 600, textAlign: 'right' }}>{v}</span>
    </div>
  );
  const lbl = { fontSize: 12, fontWeight: 600, color: c.muted, display: 'block', marginBottom: 6 };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: `1px solid ${c.border}`, background: c.inputBg || c.surface, color: c.text, fontSize: 13.5, fontFamily: 'inherit', resize: 'vertical' };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 520, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>İade Teslim Al · {a.name}</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>Ekipmanın durumunu değerlendirip havuza ekleyin ya da hurdaya yönlendirin.</div>
        </div>
        <div style={{ padding: 22 }}>
          <div style={{ background: c.surface, border: `1px solid ${c.borderSoft}`, borderRadius: 12, padding: '12px 16px', marginBottom: 16 }}>
            {row('Ekipman', a.name)}
            {row('Adet', a.qty + ' adet')}
            {a.seriNo && row('Seri No', a.seriNo)}
            {row('İade eden', (r.fromOwnerName || a.ownerName || '—') + (r.fromOwnerDept ? ' · ' + r.fromOwnerDept : ''))}
            {r.offboarding && row('Sebep', 'Personel ayrılışı')}
            {r.reason && row('Not', r.reason)}
          </div>
          <label style={lbl}>Durum / teslim notu <span style={{ color: c.subtle, fontWeight: 400 }}>(opsiyonel)</span></label>
          <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={2} style={inp} placeholder="örn. çalışır durumda, kutusuyla teslim alındı / küçük çizik var" />
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}`, flexWrap: 'wrap' }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>Vazgeç</button>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <button onClick={onScrap} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: '#6B7280', fontSize: 13, fontWeight: 700, padding: '10px 16px', borderRadius: 10 }}>🗑️ Hurdaya yönlendir</button>
            <button onClick={toPool} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: 'none', background: '#0369A1', color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10 }}>♻️ Havuza al</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Yeniden atama (Faz 8.3): depo sorumlusu havuzdaki ekipmanı yeni personele atar → 'received'.
// Yeni sahip Zimmetlerim'den dijital zimmet formunu imzalayınca tekrar kullanıma geçer.
function ReassignModal({ a, c, onClose }) {
  const isMobile = useIsMobile();
  const users = (typeof useUsersSnapshot === 'function' ? useUsersSnapshot() : ((window.__users && window.__users.items) || (window.DEMO_USERS || [])));
  const options = users.filter((u) => u.active !== false).map((u) => ({ value: u.id, label: u.name, sub: [u.department, u.email].filter(Boolean).join(' · ') }));
  const [sel, setSel] = React.useState('');
  const Picker = window.SearchPicker;
  const submit = () => {
    const u = users.find((x) => x.id === sel);
    if (!u) { alert('Lütfen ekipmanı atayacağınız personeli seçin.'); return; }
    window.__assets && window.__assets.reassign && window.__assets.reassign(a.id, { id: u.id, name: u.name, dept: u.department || '' });
    onClose();
  };
  const row = (k, v) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 13, padding: '6px 0' }}>
      <span style={{ color: c.muted }}>{k}</span>
      <span style={{ color: c.text, fontWeight: 600, textAlign: 'right' }}>{v}</span>
    </div>
  );
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 520, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>Havuzdan Yeniden Ata · {a.name}</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>Ekipmanı yeni personele atayın; kişi Zimmetlerim'den imzalayınca kullanıma geçer.</div>
        </div>
        <div style={{ padding: 22 }}>
          <div style={{ background: c.surface, border: `1px solid ${c.borderSoft}`, borderRadius: 12, padding: '12px 16px', marginBottom: 16 }}>
            {row('Ekipman', a.name)}
            {row('Adet', a.qty + ' adet')}
            {a.seriNo && row('Seri No', a.seriNo)}
            {a.pool && a.pool.fromOwnerName && row('Önceki sahip', a.pool.fromOwnerName + (a.pool.fromOwnerDept ? ' · ' + a.pool.fromOwnerDept : ''))}
          </div>
          <label style={{ fontSize: 12, fontWeight: 600, color: c.muted, display: 'block', marginBottom: 6 }}>Yeni personel *</label>
          {Picker
            ? <Picker c={c} options={options} value={sel} onChange={setSel} placeholder="Personel arayın…" />
            : <select value={sel} onChange={(e) => setSel(e.target.value)} style={{ width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: `1px solid ${c.border}`, background: c.surface, color: c.text, fontSize: 13.5, fontFamily: 'inherit' }}>
                <option value="">Personel seçin…</option>
                {options.map((o) => <option key={o.value} value={o.value}>{o.label}{o.sub ? ` — ${o.sub}` : ''}</option>)}
              </select>}
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}` }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>Vazgeç</button>
          <button onClick={submit} disabled={!sel} style={{ appearance: 'none', cursor: sel ? 'pointer' : 'default', fontFamily: 'inherit', border: 'none', background: sel ? '#0369A1' : c.border, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10, opacity: sel ? 1 : 0.7 }}>♻️ Ata ve imzaya gönder</button>
        </div>
      </div>
    </div>
  );
}

// ─────────── Zimmetlerim / Sanal Depom (Faz 7.3) — kullanıcı tarafı ───────────
// Kullanıcı deposundaki (received) ekipmanı dijital zimmet formuyla imzalayıp teslim alır
// (in_use). Üzerindeki tüm zimmetli ekipmanı burada görür.
function MyAssetsPage({ 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 assets = useAssetsSnapshot();
  const me = useCurrentUser();

  const mine = assets.filter((a) => me && a.ownerId === me.id);
  const awaiting = mine.filter((a) => a.status === 'received');   // imza bekleyen
  const inUse = mine.filter((a) => a.status === 'in_use' || a.status === 'in_service' || a.status === 'scrap_pending' || a.status === 'return_pending');  // üzerimde (serviste/hurda/iade sürecinde dahil)
  const [tab, setTab] = React.useState('awaiting');
  const [signTarget, setSignTarget] = React.useState(null);
  const [returnTarget, setReturnTarget] = React.useState(null);
  React.useEffect(() => { if (awaiting.length === 0 && tab === 'awaiting') setTab('mine'); }, [awaiting.length]);  // imza biterse otomatik geç
  const shown = tab === 'awaiting' ? awaiting : inUse;

  const tabBtn = (key, label, count) => (
    <button onClick={() => setTab(key)} style={{
      appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
      padding: '9px 14px', borderRadius: 999, border: `1px solid ${tab === key ? c.primary : c.border}`,
      background: tab === key ? c.primary : 'transparent', color: tab === key ? '#fff' : c.muted,
      fontSize: 13, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 7,
    }}>
      {label}
      {count > 0 && <span style={{ fontSize: 11, fontWeight: 700, padding: '1px 7px', borderRadius: 999, background: tab === key ? 'rgba(255,255,255,0.25)' : c.chipBg, color: tab === key ? '#fff' : c.muted }}>{count}</span>}
    </button>
  );

  return (
    <div style={{ minHeight: '100%', background: c.bg, fontFamily: 'Inter, system-ui, sans-serif' }}>
      {signTarget && <HandoverModal a={signTarget} c={c} me={me} onClose={() => setSignTarget(null)} />}
      {returnTarget && <ReturnModal a={returnTarget} c={c} me={me} onClose={() => setReturnTarget(null)} />}
      <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' }}>
        <div style={{ marginBottom: 16 }}>
          <h1 style={{ margin: 0, fontSize: isMobile ? 20 : 23, fontWeight: 700, color: c.text, letterSpacing: '-0.015em' }}>Zimmetlerim</h1>
          <div style={{ fontSize: 13, color: c.muted, marginTop: 4 }}>
            Üzerinize zimmetli ekipman · {awaiting.length > 0 ? `${awaiting.length} kalem imzanızı bekliyor` : 'imza bekleyen yok'}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
          {tabBtn('awaiting', 'İmza Bekleyenler', awaiting.length)}
          {tabBtn('mine', 'Zimmetimdekiler', inUse.length)}
        </div>

        {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 === 'awaiting' ? 'İmza bekleyen ekipman yok' : 'Üzerinize zimmetli ekipman yok'}
            </div>
            {tab === 'awaiting' ? 'Depo ekipmanı teslim alıp size haber verdiğinde burada imzalayabilirsiniz.' : 'Zimmet formunu imzaladığınız ekipmanlar burada listelenir.'}
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {shown.map((a) => <MyAssetCard key={a.id} a={a} c={c} isMobile={isMobile} onSign={() => setSignTarget(a)} onReturn={() => setReturnTarget(a)} />)}
          </div>
        )}
      </div>
    </div>
  );
}

function MyAssetCard({ a, c, isMobile, onSign, onReturn }) {
  const meta = DEPOT_STATUS_META[a.status] || {};
  const [open, setOpen] = React.useState(false);
  const img = window.productImgSrc ? window.productImgSrc(a) : null;
  return (
    <div style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, overflow: 'hidden' }}>
      <div style={{ padding: isMobile ? '14px 16px' : '16px 20px', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
        <div style={{ width: 56, height: 56, borderRadius: 12, border: `1px solid ${c.border}`, background: c.imgBg, overflow: 'hidden', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {img ? <img src={img} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
               : <span style={{ fontSize: 16, fontWeight: 700, color: c.muted }}>{(a.name || '?').charAt(0)}</span>}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 15, fontWeight: 600, color: c.text }}>{a.name}</span>
            <span style={{ fontSize: 11, fontWeight: 700, color: meta.color, background: meta.bg, padding: '2px 8px', borderRadius: 999 }}>{meta.icon} {meta.label}</span>
            <WarrantyBadge a={a} c={c} />
          </div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 4 }}>
            {a.qty} adet · {depotModuleLabel(a.module)}{a.signedAt ? ` · zimmet tarihi ${a.signedAt}` : ''}
          </div>
          <div style={{ fontSize: 12, color: c.subtle, marginTop: 3 }}>
            Sipariş {a.poNo}{a.supplier ? ` · ${a.supplier}` : ''} · talep {a.reqId}
          </div>
          {a.seriNo && <div style={{ fontSize: 12, color: c.subtle, marginTop: 3 }}>Seri No: <b style={{ color: c.text }}>{a.seriNo}</b></div>}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end' }}>
          {a.status === 'received' && (
            <button onClick={onSign} style={{ appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: '#fff', background: c.primary, padding: '9px 14px', borderRadius: 10, whiteSpace: 'nowrap' }}>✍️ Zimmet formunu imzala</button>
          )}
          {a.status === 'in_use' && (
            <React.Fragment>
              <span style={{ fontSize: 11.5, fontWeight: 600, color: c.success }}>✓ Üzerinizde</span>
              <button onClick={onReturn} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, color: '#7C3AED', background: 'transparent', border: `1px solid #7C3AED55`, padding: '7px 12px', borderRadius: 10, whiteSpace: 'nowrap' }}>↩️ İade et</button>
            </React.Fragment>
          )}
          {a.status === 'return_pending' && (
            <span style={{ fontSize: 11.5, fontWeight: 600, color: '#7C3AED', textAlign: 'right', maxWidth: 150 }}>↩️ İade sürecinde{a.return && a.return.offboarding ? ' · ayrılış' : ''}</span>
          )}
          {a.status === 'in_service' && (
            <span style={{ fontSize: 11.5, fontWeight: 600, color: '#C2410C', textAlign: 'right', maxWidth: 150 }}>🔧 Serviste{a.service && a.service.receiver ? ` · ${a.service.receiver}` : ''}</span>
          )}
          {a.status === 'scrap_pending' && (
            <span style={{ fontSize: 11.5, fontWeight: 600, color: '#B45309', textAlign: 'right', maxWidth: 150 }}>⏳ Hurda onayında</span>
          )}
          <button onClick={() => setOpen((x) => !x)} style={{ appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', color: c.primary, fontSize: 12.5, fontWeight: 600 }}>{open ? '▾ Geçmiş' : '▸ Geçmiş'}</button>
        </div>
      </div>
      {open && (a.timeline || []).length > 0 && (
        <div style={{ borderTop: `1px solid ${c.borderSoft}`, padding: '12px 20px', background: c.surface }}>
          {(a.timeline || []).map((ev, i) => {
            const m = DEPOT_STATUS_META[ev.status] || {};
            return (
              <div key={i} style={{ display: 'flex', gap: 10, fontSize: 12, color: c.muted, padding: '4px 0' }}>
                <span style={{ minWidth: 18 }}>{m.icon || '•'}</span>
                <span style={{ color: c.text, fontWeight: 600, minWidth: 140 }}>{m.label || ev.status}</span>
                <span>{ev.byName}{ev.note ? ` · ${ev.note}` : ''} · {ev.at}</span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// Dijital zimmet/teslim formu — kullanıcı onay kutusunu işaretleyip imzalar (in_use'a geçer).
function HandoverModal({ a, c, me, onClose }) {
  const isMobile = useIsMobile();
  const [accepted, setAccepted] = React.useState(false);
  const sign = () => {
    if (!accepted) return;
    window.__assets && window.__assets.sign && window.__assets.sign(a.id, me ? me.name : a.ownerName);
    onClose();
  };
  const row = (k, v) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 13, padding: '6px 0' }}>
      <span style={{ color: c.muted }}>{k}</span>
      <span style={{ color: c.text, fontWeight: 600, textAlign: 'right' }}>{v}</span>
    </div>
  );
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 520, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>Dijital Zimmet / Teslim Formu</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>Ekipmanı teslim aldığınızı onaylıyorsunuz; sorumluluğu üzerinize geçer.</div>
        </div>
        <div style={{ padding: 22 }}>
          <div style={{ background: c.surface, border: `1px solid ${c.borderSoft}`, borderRadius: 12, padding: '12px 16px', marginBottom: 16 }}>
            {row('Ekipman', a.name)}
            {row('Adet', a.qty + ' adet')}
            {a.seriNo && row('Seri No', a.seriNo)}
            {(() => { const w = warrantyInfo(a); if (!w) return null; return row('Garanti', w.none ? (w.label || 'Garantisiz') : (w.until ? `${w.until}${w.expired ? ' · doldu' : ''}` : (w.label || '—'))); })()}
            {row('Zimmet sahibi', (me ? me.name : a.ownerName) + (a.ownerDept ? ' · ' + a.ownerDept : ''))}
            {row('Depo', depotModuleLabel(a.module))}
            {row('Sipariş', a.poNo + (a.supplier ? ' · ' + a.supplier : ''))}
            {row('Teslim eden', a.receivedBy || '—')}
          </div>
          <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', fontSize: 13, color: c.text, lineHeight: 1.5 }}>
            <input type="checkbox" checked={accepted} onChange={(e) => setAccepted(e.target.checked)} style={{ marginTop: 3, width: 16, height: 16, accentColor: c.primary }} />
            <span><b>{a.name}</b> ekipmanını eksiksiz ve çalışır durumda teslim aldığımı, korunması ve iadesinden sorumlu olduğumu kabul ederim. (Elektronik imza · {me ? me.name : a.ownerName} · {new Date().toLocaleDateString('tr-TR')})</span>
          </label>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}` }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>Vazgeç</button>
          <button onClick={sign} disabled={!accepted} style={{ appearance: 'none', cursor: accepted ? 'pointer' : 'default', fontFamily: 'inherit', border: 'none', background: accepted ? c.success : c.border, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10, opacity: accepted ? 1 : 0.7 }}>✍️ İmzala ve teslim al</button>
        </div>
      </div>
    </div>
  );
}

// İADE formu (Faz 8.1) — kullanıcı kendi zimmetini iade eder (in_use → return_pending).
// Ekipman, ürünün modülünün deposuna döner; depo teslim alıp havuza/hurdaya yönlendirir (F8.2).
function ReturnModal({ a, c, me, onClose }) {
  const isMobile = useIsMobile();
  const [reason, setReason] = React.useState('');
  const [accepted, setAccepted] = React.useState(false);
  const submit = () => {
    if (!accepted) return;
    window.__assets && window.__assets.initiateReturn && window.__assets.initiateReturn(a.id, { reason: reason.trim() });
    onClose();
  };
  const row = (k, v) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 13, padding: '6px 0' }}>
      <span style={{ color: c.muted }}>{k}</span>
      <span style={{ color: c.text, fontWeight: 600, textAlign: 'right' }}>{v}</span>
    </div>
  );
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 520, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>Ekipman İadesi</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>Ekipman ilgili depoya iade edilecek; teslim alınınca zimmetinizden düşer.</div>
        </div>
        <div style={{ padding: 22 }}>
          <div style={{ background: c.surface, border: `1px solid ${c.borderSoft}`, borderRadius: 12, padding: '12px 16px', marginBottom: 16 }}>
            {row('Ekipman', a.name)}
            {row('Adet', a.qty + ' adet')}
            {a.seriNo && row('Seri No', a.seriNo)}
            {row('İade edilecek depo', depotModuleLabel(a.module))}
            {row('Zimmet sahibi', (me ? me.name : a.ownerName))}
          </div>
          <label style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: c.muted, marginBottom: 6 }}>İade gerekçesi (opsiyonel)</label>
          <textarea value={reason} onChange={(e) => setReason(e.target.value)} rows={3} placeholder="Örn. yenisiyle değiştirildi, arızalı, artık kullanılmıyor…" style={{ width: '100%', boxSizing: 'border-box', resize: 'vertical', fontFamily: 'inherit', fontSize: 13, color: c.text, background: c.surface, border: `1px solid ${c.border}`, borderRadius: 10, padding: '10px 12px', marginBottom: 16 }} />
          <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', fontSize: 13, color: c.text, lineHeight: 1.5 }}>
            <input type="checkbox" checked={accepted} onChange={(e) => setAccepted(e.target.checked)} style={{ marginTop: 3, width: 16, height: 16, accentColor: '#7C3AED' }} />
            <span><b>{a.name}</b> ekipmanını iade etmek istediğimi onaylıyorum. (Elektronik onay · {me ? me.name : a.ownerName} · {new Date().toLocaleDateString('tr-TR')})</span>
          </label>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}` }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>Vazgeç</button>
          <button onClick={submit} disabled={!accepted} style={{ appearance: 'none', cursor: accepted ? 'pointer' : 'default', fontFamily: 'inherit', border: 'none', background: accepted ? '#7C3AED' : c.border, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10, opacity: accepted ? 1 : 0.7 }}>↩️ İade et</button>
        </div>
      </div>
    </div>
  );
}

// PERSONEL AYRILIŞI / TOPLU İADE (Faz 8.1) — yönetici/İK bir kişinin TÜM zimmetlerini tek seferde
// iadeye çıkarır. Admin panel kullanıcı listesinden açılır. user: { id, name, department }
function OffboardModal({ user, c, me, onClose }) {
  const isMobile = useIsMobile();
  const assets = (typeof useAssetsSnapshot === 'function' ? useAssetsSnapshot() : ((window.__assets && window.__assets.items) || []));
  const mine = assets.filter((a) => a.ownerId === user.id && a.status === 'in_use');
  const [reason, setReason] = React.useState('');
  const [confirmed, setConfirmed] = React.useState(false);
  const submit = () => {
    if (!mine.length || !confirmed) return;
    window.__assets && window.__assets.offboardUser && window.__assets.offboardUser(user.id, { reason: reason.trim() || 'Personel ayrılışı' });
    onClose();
  };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 560, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>Personel Ayrılışı · Zimmet İadesi</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}><b>{user.name}</b>{user.department ? ` · ${user.department}` : ''} üzerindeki tüm zimmetler iadeye çıkarılır.</div>
        </div>
        <div style={{ padding: 22 }}>
          {mine.length === 0 ? (
            <div style={{ background: c.surface, border: `1px dashed ${c.border}`, borderRadius: 12, padding: 28, textAlign: 'center', color: c.muted, fontSize: 13 }}>
              Bu kullanıcının üzerinde kullanımda (zimmetli) ekipman bulunmuyor.
            </div>
          ) : (
            <React.Fragment>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: c.muted, marginBottom: 8 }}>{mine.length} ekipman iadeye çıkarılacak:</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
                {mine.map((a) => (
                  <div key={a.id} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center', background: c.surface, border: `1px solid ${c.borderSoft}`, borderRadius: 10, padding: '9px 13px' }}>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: c.text }}>{a.name}</div>
                      <div style={{ fontSize: 11.5, color: c.subtle }}>{a.qty} adet · {depotModuleLabel(a.module)}{a.seriNo ? ` · Seri ${a.seriNo}` : ''}</div>
                    </div>
                    <span style={{ fontSize: 11, fontWeight: 700, color: '#7C3AED', background: 'rgba(124,58,237,0.12)', padding: '2px 8px', borderRadius: 999, whiteSpace: 'nowrap' }}>↩️ İade</span>
                  </div>
                ))}
              </div>
              <label style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: c.muted, marginBottom: 6 }}>Ayrılış gerekçesi / not (opsiyonel)</label>
              <textarea value={reason} onChange={(e) => setReason(e.target.value)} rows={2} placeholder="Örn. istifa, sözleşme bitişi…" style={{ width: '100%', boxSizing: 'border-box', resize: 'vertical', fontFamily: 'inherit', fontSize: 13, color: c.text, background: c.surface, border: `1px solid ${c.border}`, borderRadius: 10, padding: '10px 12px', marginBottom: 16 }} />
              <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', fontSize: 13, color: c.text, lineHeight: 1.5 }}>
                <input type="checkbox" checked={confirmed} onChange={(e) => setConfirmed(e.target.checked)} style={{ marginTop: 3, width: 16, height: 16, accentColor: '#7C3AED' }} />
                <span><b>{user.name}</b> ayrılıyor; yukarıdaki {mine.length} ekipmanı iadeye çıkardığımı onaylıyorum.</span>
              </label>
            </React.Fragment>
          )}
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}` }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>{mine.length === 0 ? 'Kapat' : 'Vazgeç'}</button>
          {mine.length > 0 && <button onClick={submit} disabled={!confirmed} style={{ appearance: 'none', cursor: confirmed ? 'pointer' : 'default', fontFamily: 'inherit', border: 'none', background: confirmed ? '#7C3AED' : c.border, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10, opacity: confirmed ? 1 : 0.7 }}>↩️ {mine.length} ekipmanı iadeye çıkar</button>}
        </div>
      </div>
    </div>
  );
}

// ─────────── İSG & Çevre · Hurda Yönetimi (Faz 9) ───────────
// Onaylı hurdalar (scrapped) burada birikir; İSG & Çevre görevlisi belirli dönemlerde hurdacıya
// toptan satar (sold:true + alıcı + tutar + tutanak → arşiv). Org genelinde (modüle bağlı değil).
const fmtTRY = (n) => (Number(n) || 0).toLocaleString('tr-TR') + ' ₺';

function HsePanel({ initialDark = false, user }) {
  const [dark, setDark] = React.useState(initialDark);
  React.useEffect(() => { setDark(initialDark); }, [initialDark]);
  const c = catalogTheme(dark);
  const isMobile = useIsMobile();
  const assets = useAssetsSnapshot();
  const scrapped = assets.filter((a) => a.status === 'scrapped');
  const unsold = scrapped.filter((a) => !(a.scrap && a.scrap.sold));
  const sold = scrapped.filter((a) => a.scrap && a.scrap.sold);
  const [tab, setTab] = React.useState('pending');
  const [sel, setSel] = React.useState(() => new Set());
  const [q, setQ] = React.useState('');
  const [saleOpen, setSaleOpen] = React.useState(false);

  const ql = q.trim().toLowerCase();
  const match = (a) => !ql || [a.name, a.seriNo, a.pool && a.pool.fromOwnerName, a.ownerName, a.poNo, depotModuleLabel(a.module)].filter(Boolean).join(' ').toLowerCase().includes(ql);
  const shownPending = unsold.filter(match);
  const shownSold = sold.filter(match);

  const toggle = (id) => setSel((prev) => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const allShownIds = shownPending.map((a) => a.id);
  const allSelected = allShownIds.length > 0 && allShownIds.every((id) => sel.has(id));
  const toggleAll = () => setSel(() => allSelected ? new Set() : new Set(allShownIds));
  const selectedAssets = unsold.filter((a) => sel.has(a.id));

  // Arşiv: satış (saleId) bazında grupla
  const sales = {};
  sold.forEach((a) => { const sid = (a.scrap.sale && a.scrap.sale.saleId) || 'tek'; (sales[sid] = sales[sid] || { sale: a.scrap.sale || {}, items: [] }).items.push(a); });
  const filteredSales = Object.keys(sales).map((sid) => sales[sid]).filter((g) => g.items.some(match)).sort((a, b) => (b.sale.soldAt || '').localeCompare(a.sale.soldAt || ''));

  const tabBtn = (key, label, count) => (
    <button onClick={() => setTab(key)} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', padding: '9px 14px', borderRadius: 999, border: `1px solid ${tab === key ? c.primary : c.border}`, background: tab === key ? c.primary : 'transparent', color: tab === key ? '#fff' : c.muted, fontSize: 13, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 7 }}>
      {label}{count > 0 && <span style={{ fontSize: 11, fontWeight: 700, padding: '1px 7px', borderRadius: 999, background: tab === key ? 'rgba(255,255,255,0.25)' : c.chipBg, color: tab === key ? '#fff' : c.muted }}>{count}</span>}
    </button>
  );

  const archiveSum = Object.keys(sales).reduce((s, sid) => s + (Number(sales[sid].sale.amount) || 0), 0);

  return (
    <div style={{ minHeight: '100%', background: c.bg, fontFamily: 'Inter, system-ui, sans-serif' }}>
      {saleOpen && <ScrapSaleModal ids={selectedAssets.map((a) => a.id)} items={selectedAssets} c={c} onClose={() => { setSaleOpen(false); setSel(new Set()); }} />}
      <CatalogHeader c={c} dark={dark} onToggleDark={() => setDark((x) => !x)} cartCount={0} notifCount={0} />

      <div style={{ maxWidth: 920, margin: '0 auto', padding: isMobile ? '18px 16px 40px' : '28px 28px 56px' }}>
        <div style={{ marginBottom: 16 }}>
          <h1 style={{ margin: 0, fontSize: isMobile ? 20 : 23, fontWeight: 700, color: c.text, letterSpacing: '-0.015em' }}>İSG & Çevre · Hurda Yönetimi</h1>
          <div style={{ fontSize: 13, color: c.muted, marginTop: 4 }}>
            Onaylı hurda ekipmanın hurdacıya satış / imha sürecini yürütün · {unsold.length > 0 ? `${unsold.length} kalem satış bekliyor` : 'satış bekleyen hurda yok'}
          </div>
        </div>

        {/* Özet kartları */}
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(3, 1fr)', gap: 12, marginBottom: 18 }}>
          <StatCardLite c={c} label="Satış bekleyen" value={unsold.length} sub="kalem" color="#6B7280" />
          <StatCardLite c={c} label="Satılan / arşiv" value={sold.length} sub="kalem" color="#047857" />
          <StatCardLite c={c} label="Toplam satış geliri" value={fmtTRY(archiveSum)} sub={`${Object.keys(sales).length} satış`} color="#0369A1" />
        </div>

        <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
          {tabBtn('pending', 'Satış Bekleyenler', unsold.length)}
          {tabBtn('archive', 'Arşiv · Satılanlar', sold.length)}
        </div>

        <div style={{ position: 'relative', marginBottom: 14 }}>
          <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: c.muted, fontSize: 14, pointerEvents: 'none' }}>🔍</span>
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Seri no, ürün, önceki sahip, alıcı ile ara…" style={{ width: '100%', boxSizing: 'border-box', padding: '10px 36px', borderRadius: 10, border: `1px solid ${c.border}`, background: c.inputBg || c.surface, color: c.text, fontSize: 13.5, fontFamily: 'inherit', outline: 'none' }} />
          {q && <button onClick={() => setQ('')} style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', color: c.muted, fontSize: 15, fontWeight: 700 }}>✕</button>}
        </div>

        {tab === 'pending' ? (
          shownPending.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 }}>Satış bekleyen hurda yok</div>
              IT Müdürü hurda talebini onayladıkça ekipmanlar burada birikir; toplu olarak hurdacıya satabilirsiniz.
            </div>
          ) : (
            <React.Fragment>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, marginBottom: 12, flexWrap: 'wrap' }}>
                <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, color: c.muted, cursor: 'pointer' }}>
                  <input type="checkbox" checked={allSelected} onChange={toggleAll} style={{ width: 16, height: 16, accentColor: c.primary }} />
                  Tümünü seç ({allShownIds.length})
                </label>
                <button onClick={() => setSaleOpen(true)} disabled={sel.size === 0} style={{ appearance: 'none', cursor: sel.size ? 'pointer' : 'default', fontFamily: 'inherit', border: 'none', background: sel.size ? '#0369A1' : c.border, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 16px', borderRadius: 10, opacity: sel.size ? 1 : 0.7 }}>🤝 Hurdacıya sat ({sel.size})</button>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {shownPending.map((a) => <HseScrapCard key={a.id} a={a} c={c} isMobile={isMobile} selectable checked={sel.has(a.id)} onToggle={() => toggle(a.id)} />)}
              </div>
            </React.Fragment>
          )
        ) : (
          filteredSales.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 }}>Arşivde satış kaydı yok</div>
              Hurdacıya yapılan satışlar (alıcı, tutar, tarih) burada arşivlenir.
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {filteredSales.map((g, gi) => (
                <div key={gi} style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, overflow: 'hidden' }}>
                  <div style={{ padding: isMobile ? '14px 16px' : '16px 20px', borderBottom: `1px solid ${c.borderSoft}`, background: c.surface }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
                      <div>
                        <div style={{ fontSize: 15, fontWeight: 700, color: c.text }}>🤝 {g.sale.buyer || 'Hurdacı'}</div>
                        <div style={{ fontSize: 12, color: c.muted, marginTop: 2 }}>{g.items.length} kalem · {g.sale.soldDate || g.sale.soldAt || '—'}{g.sale.soldByName ? ` · ${g.sale.soldByName}` : ''}</div>
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <div style={{ fontSize: 18, fontWeight: 800, color: '#047857' }}>{fmtTRY(g.sale.amount)}</div>
                        <div style={{ fontSize: 11, color: c.subtle }}>toptan satış bedeli</div>
                      </div>
                    </div>
                    {g.sale.note && <div style={{ fontSize: 12, color: c.muted, marginTop: 8 }}>Not: {g.sale.note}</div>}
                    {g.sale.docDataUrl && <a href={g.sale.docDataUrl} target="_blank" rel="noreferrer" style={{ fontSize: 12, fontWeight: 600, color: c.primary, textDecoration: 'none', display: 'inline-block', marginTop: 6 }}>📄 Satış tutanağı</a>}
                  </div>
                  <div style={{ padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {g.items.map((a) => <HseScrapCard key={a.id} a={a} c={c} isMobile={isMobile} compact />)}
                  </div>
                </div>
              ))}
            </div>
          )
        )}
      </div>
    </div>
  );
}

function StatCardLite({ c, label, value, sub, color }) {
  return (
    <div style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 14, padding: '14px 16px' }}>
      <div style={{ fontSize: 11.5, fontWeight: 600, color: c.muted, textTransform: 'uppercase', letterSpacing: '0.03em' }}>{label}</div>
      <div style={{ fontSize: 22, fontWeight: 800, color: color || c.text, marginTop: 4 }}>{value}</div>
      {sub && <div style={{ fontSize: 11.5, color: c.subtle, marginTop: 1 }}>{sub}</div>}
    </div>
  );
}

function HseScrapCard({ a, c, isMobile, selectable, checked, onToggle, compact }) {
  const img = window.productImgSrc ? window.productImgSrc(a) : null;
  const from = (a.pool && a.pool.fromOwnerName) || a.ownerName || '—';
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'center', background: compact ? 'transparent' : c.card, border: compact ? 'none' : `1px solid ${c.border}`, borderRadius: compact ? 0 : 14, padding: compact ? '6px 4px' : (isMobile ? '12px 14px' : '14px 16px') }}>
      {selectable && <input type="checkbox" checked={checked} onChange={onToggle} style={{ width: 17, height: 17, accentColor: c.primary, flexShrink: 0 }} />}
      <div style={{ width: compact ? 36 : 48, height: compact ? 36 : 48, borderRadius: 10, border: `1px solid ${c.border}`, background: c.imgBg, overflow: 'hidden', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {img ? <img src={img} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain' }} /> : <span style={{ fontSize: 14, fontWeight: 700, color: c.muted }}>{(a.name || '?').charAt(0)}</span>}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: compact ? 13 : 14, fontWeight: 600, color: c.text }}>{a.name}</div>
        <div style={{ fontSize: 11.5, color: c.muted, marginTop: 2 }}>
          {a.qty} adet · {depotModuleLabel(a.module)}{a.seriNo ? ` · Seri ${a.seriNo}` : ''} · önceki: {from}
        </div>
        {!compact && a.scrap && a.scrap.reason && <div style={{ fontSize: 11.5, color: '#B45309', marginTop: 2 }}>🗑️ {a.scrap.reason}</div>}
      </div>
      {!compact && a.scrap && a.scrap.docDataUrl && (
        <a href={a.scrap.docDataUrl} target="_blank" rel="noreferrer" style={{ fontSize: 11.5, fontWeight: 600, color: c.primary, textDecoration: 'none', flexShrink: 0 }}>📄 Tutanak</a>
      )}
    </div>
  );
}

// Hurdacıya toptan satış formu (Faz 9): seçili hurdaları tek alıcıya, toplu bedelle satar.
function ScrapSaleModal({ ids, items, c, onClose }) {
  const isMobile = useIsMobile();
  const today = new Date().toISOString().slice(0, 10);
  const [buyer, setBuyer] = React.useState('');
  const [amount, setAmount] = React.useState('');
  const [soldDate, setSoldDate] = React.useState(today);
  const [note, setNote] = React.useState('');
  const [docDataUrl, setDocDataUrl] = React.useState('');
  const [docName, setDocName] = React.useState('');
  const onFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    if (f.size > 4 * 1024 * 1024) { alert('Dosya 4 MB\'tan küçük olmalı.'); return; }
    const r = new FileReader();
    r.onload = () => { setDocDataUrl(r.result); setDocName(f.name); };
    r.readAsDataURL(f);
  };
  const valid = buyer.trim() && (Number(amount) || 0) > 0;
  const submit = () => {
    if (!valid) { alert('Alıcı (hurdacı) ve satış bedeli zorunludur.'); return; }
    window.__assets && window.__assets.sellScrap && window.__assets.sellScrap(ids, { buyer: buyer.trim(), amount: Number(amount) || 0, soldDate, docDataUrl, note: note.trim() });
    onClose();
  };
  const lbl = { fontSize: 12, fontWeight: 600, color: c.muted, display: 'block', marginBottom: 6 };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 10, border: `1px solid ${c.border}`, background: c.inputBg || c.surface, color: c.text, fontSize: 13.5, fontFamily: 'inherit' };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: c.card, borderRadius: 16, width: isMobile ? '100%' : 560, maxWidth: '100%', maxHeight: '92vh', overflowY: 'auto', border: `1px solid ${c.border}` }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: c.text }}>Hurdacıya Toptan Satış</div>
          <div style={{ fontSize: 12.5, color: c.muted, marginTop: 3 }}>{(items || []).length} hurda kalemi tek alıcıya, toplu bedelle satılır ve arşivlenir.</div>
        </div>
        <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ background: c.surface, border: `1px solid ${c.borderSoft}`, borderRadius: 12, padding: '10px 12px', maxHeight: 160, overflowY: 'auto' }}>
            {(items || []).map((a) => (
              <div key={a.id} style={{ fontSize: 12.5, color: c.text, padding: '4px 0', display: 'flex', justifyContent: 'space-between', gap: 10 }}>
                <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.name}{a.seriNo ? ` · ${a.seriNo}` : ''}</span>
                <span style={{ color: c.muted, flexShrink: 0 }}>{depotModuleLabel(a.module)}</span>
              </div>
            ))}
          </div>
          <div><label style={lbl}>Alıcı · hurdacı firma *</label><input value={buyer} onChange={(e) => setBuyer(e.target.value)} style={inp} placeholder="örn. Öz Geri Dönüşüm Ltd. Şti." /></div>
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
            <div><label style={lbl}>Toptan satış bedeli (₺) *</label><input value={amount} onChange={(e) => setAmount(e.target.value)} inputMode="numeric" style={inp} placeholder="örn. 4500" /></div>
            <div><label style={lbl}>Satış tarihi</label><input type="date" value={soldDate} onChange={(e) => setSoldDate(e.target.value)} style={inp} /></div>
          </div>
          <div><label style={lbl}>Not <span style={{ color: c.subtle, fontWeight: 400 }}>(opsiyonel)</span></label><textarea value={note} onChange={(e) => setNote(e.target.value)} rows={2} style={{ ...inp, resize: 'vertical' }} placeholder="örn. kg üzerinden, tartı fişi ektedir." /></div>
          <div>
            <label style={lbl}>Satış tutanağı / fiş <span style={{ color: c.subtle, fontWeight: 400 }}>(opsiyonel)</span></label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <label style={{ cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: c.primary, border: `1px solid ${c.border}`, borderRadius: 10, padding: '9px 14px' }}>📎 Dosya seç<input type="file" accept="image/*,.pdf" onChange={onFile} style={{ display: 'none' }} /></label>
              {docName && <span style={{ fontSize: 12, color: c.muted }}>{docName} <button onClick={() => { setDocDataUrl(''); setDocName(''); }} style={{ appearance: 'none', border: 'none', background: 'transparent', color: c.danger, cursor: 'pointer', fontWeight: 700 }}>✕</button></span>}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 22px', borderTop: `1px solid ${c.border}` }}>
          <button onClick={onClose} style={{ appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted, fontSize: 13, fontWeight: 600, padding: '10px 16px', borderRadius: 10 }}>Vazgeç</button>
          <button onClick={submit} disabled={!valid} style={{ appearance: 'none', cursor: valid ? 'pointer' : 'default', fontFamily: 'inherit', border: 'none', background: valid ? '#047857' : c.border, color: '#fff', fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 10, opacity: valid ? 1 : 0.7 }}>🤝 Satışı kaydet</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DepotPanel, AssetCard, ReceiveModal, ServiceFormModal, ServiceReturnModal, ScrapModal, printServiceForm, COMPANY_INFO, WarrantyBadge, warrantyInfo, WARRANTY_OPTS, DEPOT_STATUS_META, depotModuleLabel, overseenDepotModules, MyAssetsPage, MyAssetCard, HandoverModal, ReturnModal, OffboardModal, ReturnReceiveModal, ReassignModal, HsePanel, ScrapSaleModal, HseScrapCard, StatCardLite, PoolInquiryCard });
