// admin-panel.jsx — Süper Admin Yönetim Paneli (Faz 3 / Parça 3.1: temel iskelet)
// Ayrı kurumsal layout: sol menü + bölümler. Bu parçada Genel Bakış gerçek özet gösterir;
// diğer bölümler (Kategoriler, Ürünler, Kullanıcılar, Raporlar, Sistem/LDAP) sonraki
// parçalarda doldurulacak placeholder'lardır.

const ADMIN_ICONS = {
  overview: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="9" rx="1.5" /><rect x="14" y="3" width="7" height="5" rx="1.5" /><rect x="14" y="12" width="7" height="9" rx="1.5" /><rect x="3" y="16" width="7" height="5" rx="1.5" /></svg>,
  categories: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /></svg>,
  products: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.7l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.7l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /><path d="M3.3 7 12 12l8.7-5M12 22V12" /></svg>,
  users: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="8" r="3.5" /><path d="M3 20a6 6 0 0 1 12 0" /><path d="M16 5.5a3 3 0 0 1 0 5M18 20a6 6 0 0 0-3-5.2" /></svg>,
  reports: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18" /><path d="M7 14l3-3 3 3 5-6" /></svg>,
  system: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3" /><path d="M19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4 1a7 7 0 0 0-2-1.2L14 2h-4l-.5 2.6a7 7 0 0 0-2 1.2l-2.4-1-2 3.4 2 1.6A7 7 0 0 0 5 12a7 7 0 0 0 .1 1.2l-2 1.6 2 3.4 2.4-1a7 7 0 0 0 2 1.2L10 22h4l.5-2.6a7 7 0 0 0 2-1.2l2.4 1 2-3.4-2-1.6A7 7 0 0 0 19 12z" /></svg>,
};

const ADMIN_SECTIONS = [
  { id: 'overview',   label: 'Genel Bakış' },
  { id: 'categories', label: 'Kategoriler' },
  { id: 'products',   label: 'Ürünler' },
  { id: 'users',      label: 'Kullanıcılar & Yetkiler' },
  { id: 'reports',    label: 'Raporlar' },
  { id: 'system',     label: 'Sistem & LDAP' },
];

// Bölüm placeholder'ları için açıklama (sonraki parçalarda neyin geleceği)
const ADMIN_SECTION_INTRO = {
  categories: { title: 'Kategori Yönetimi', desc: 'Ana kategori ve alt kategori ekleme/düzenleme/silme. Katalogda anında yansır.', soon: 'Hazır ✓' },
  products:   { title: 'Ürün Yönetimi', desc: 'Ürün ekleme/düzenleme/pasifleştirme, görsel ekleme, fiyat/gider türü.', soon: 'Hazır ✓' },
  users:      { title: 'Kullanıcılar & Yetkiler', desc: 'Kullanıcı listesi, modül bazlı rol atama, kategori-bazlı yetki.', soon: 'Hazır ✓' },
  reports:    { title: 'Raporlar', desc: 'Harcama, onay süreleri, red analizi, bütçe kullanımı; departman/kategori kırılımı, grafikler, dışa aktarma.', soon: 'Parça 3.5' },
  system:     { title: 'Sistem & LDAP', desc: 'On-prem AD/LDAP bağlantısı (LDAPS adres/port, bind hesabı, base DN), AD grubu → uygulama rolü eşlemesi, onay eşikleri.', soon: 'Parça 3.6' },
};

// ─────────── Hızlı erişim kısayolları (Bildirim / Sepet / Onay Kutusu / Taleplerim) ───────────
// Süper Admin de aynı zamanda talep eden + onaycı olabilir; yönetim ekranından bu sayfalara
// hızlıca geçebilsin diye katalog header'ındaki ikonların bir kopyası.
// İkon + isim + sayı rozeti taşıyan kısayol düğmesi
function AdminNavBtn({ c, label, badge, badgeColor, onClick, children }) {
  const Pill = window.CountPill;
  return (
    <button onClick={onClick} title={label} style={{
      appearance: 'none', border: `1px solid ${c.border}`, cursor: 'pointer', fontFamily: 'inherit',
      background: 'transparent', color: c.text,
      display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 11px', borderRadius: 10,
      fontSize: 13, fontWeight: 500, whiteSpace: 'nowrap', transition: 'background 120ms',
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = c.borderSoft}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
      <span style={{ display: 'flex', color: c.muted }}>{children}</span>
      {label}
      {badge > 0 && Pill && <Pill n={badge} color={badgeColor || c.danger} />}
    </button>
  );
}

function AdminQuickNav({ c }) {
  const Ic = window.UIIcons || {};
  const go = (p) => window.__navigate && window.__navigate(p);

  const currentUser = window.useCurrentUser ? window.useCurrentUser() : (window.__user || null);
  const notifs = window.useNotifSnapshot ? window.useNotifSnapshot() : [];
  const cart = window.useCartSnapshot ? window.useCartSnapshot() : [];
  const approvals = window.useApprovalsSnapshot ? window.useApprovalsSnapshot() : [];
  const suppliers = window.useSuppliersSnapshot ? window.useSuppliersSnapshot() : [];
  const usersAll = window.useUsersSnapshot ? window.useUsersSnapshot() : [];

  const notifCount = notifs.filter((n) => !n.read).length;
  const cartCount = cart.length;
  const canApprove = !!(window.can && currentUser && window.can.approve(currentUser, 'it'));
  // Onay Kutusu sayacı: bu kullanıcının onayındaki talepler + tedarikçi kart + profil değişiklikleri
  const reqApprovals = currentUser
    ? approvals.filter((r) => r.status === 'pending' && r.stage === 'approval' && r.approverId === currentUser.id).length
    : 0;
  const supChanges = currentUser
    ? suppliers.filter((s) => s.pendingEdit && s.pendingEdit.status === 'pending' && (s.pendingEdit.approverId === currentUser.id || currentUser.superAdmin)).length
    : 0;
  const profChanges = currentUser
    ? usersAll.filter((u) => u.pendingProfileEdit && u.pendingProfileEdit.status === 'pending' && (u.pendingProfileEdit.approverId === currentUser.id || currentUser.superAdmin)).length
    : 0;
  const myApprovalCount = reqApprovals + supChanges + profChanges;

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
      <AdminNavBtn c={c} label="Bildirim" badge={notifCount} onClick={() => go('notifications')}>{Ic.bell}</AdminNavBtn>
      <AdminNavBtn c={c} label="Sepet" badge={cartCount} badgeColor={c.primary} onClick={() => go('cart')}>{Ic.cart}</AdminNavBtn>
      {canApprove && (
        <AdminNavBtn c={c} label="Onay Kutusu" badge={myApprovalCount} onClick={() => go('approvals')}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M22 12h-6l-2 3h-4l-2-3H2" /><path d="M5.5 5.5 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.5-6.5A2 2 0 0 0 16.8 4H7.2a2 2 0 0 0-1.7 1.5z" />
          </svg>
        </AdminNavBtn>
      )}
      <AdminNavBtn c={c} label="Taleplerim" onClick={() => go('requests')}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2" />
          <rect x="9" y="3" width="6" height="4" rx="1" /><path d="M9 12h6M9 16h4" />
        </svg>
      </AdminNavBtn>
    </div>
  );
}

// ─────────── Sol menü (masaüstü) ───────────
function AdminSidebar({ c, section, setSection, user, dark, setDark }) {
  return (
    <div style={{
      width: 252, flexShrink: 0, position: 'sticky', top: 0, height: '100%',
      background: c.surface, borderRight: `1px solid ${c.border}`,
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ height: 64, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 11, padding: '0 18px', borderBottom: `1px solid ${c.border}` }}>
        <img src="images/logo/mark-color.svg" alt="" width="34" height="34" style={{ borderRadius: 8 }} />
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: c.text, letterSpacing: '-0.01em' }}>Yönetim Paneli</div>
          <div style={{ fontSize: 11, color: c.muted }}>IT Talep Sistemi</div>
        </div>
      </div>

      <nav style={{ flex: 1, overflowY: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 4 }}>
        {ADMIN_SECTIONS.map((s) => {
          const active = section === s.id;
          return (
            <button key={s.id} onClick={() => setSection(s.id)} style={{
              appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
              display: 'flex', alignItems: 'center', gap: 11, padding: '10px 12px', borderRadius: 10,
              border: 'none', background: active ? c.selectedBg : 'transparent',
              color: active ? c.selectedText : c.text, fontSize: 13.5, fontWeight: active ? 600 : 500,
            }}>
              <span style={{ display: 'flex', color: active ? c.selectedText : c.muted }}>{ADMIN_ICONS[s.id]}</span>
              {s.label}
            </button>
          );
        })}
      </nav>

      <div style={{ flexShrink: 0, padding: 12, borderTop: `1px solid ${c.border}`, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <button onClick={() => window.__navigate && window.__navigate('catalog')} style={adminGhost(c)}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /><path d="M9 22V12h6v10" /></svg>
          Mağazaya git
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 4px' }}>
          <span style={{ width: 34, height: 34, borderRadius: 999, background: '#7C3AED', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 12.5, fontWeight: 600, flexShrink: 0 }}>{user ? user.initials : 'FY'}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: c.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user ? user.name : 'Ferhat YILDIZ'}</div>
            <div style={{ fontSize: 11, color: c.muted }}>{user ? user.roleLabel : 'Süper Admin'}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={() => setDark((d) => !d)} title="Tema" style={{ ...adminGhost(c), flex: 1, justifyContent: 'center' }}>
            {dark ? <IconSun /> : <IconMoon />}
          </button>
          <button onClick={() => window.__navigate && window.__navigate('__logout')} title="Çıkış" style={{ ...adminGhost(c), flex: 1, justifyContent: 'center', color: c.danger }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /><path d="M16 17l5-5-5-5M21 12H9" /></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

function adminGhost(c) {
  return {
    appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
    display: 'inline-flex', alignItems: 'center', gap: 8, padding: '9px 12px', borderRadius: 10,
    background: 'transparent', color: c.text, border: `1px solid ${c.border}`,
    fontSize: 12.5, fontWeight: 500,
  };
}
function adminSolid(bg) {
  return {
    appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', border: 'none',
    display: 'inline-flex', alignItems: 'center', gap: 7, padding: '9px 14px', borderRadius: 10,
    background: bg, color: '#fff', fontSize: 12.5, fontWeight: 600,
  };
}
function adminInput(c) {
  return {
    boxSizing: 'border-box', padding: '9px 12px', background: c.inputBg, color: c.text,
    border: `1px solid ${c.border}`, borderRadius: 10, fontSize: 13, fontFamily: 'inherit', outline: 'none',
  };
}

// ─────────── Kategori ikon seçici ───────────
const CAT_ICON_OPTIONS = ['monitor', 'disc', 'wrench', 'microsoft', 'remote', 'grid'];
function IconPicker({ value, onChange, c }) {
  const icons = window.CatIcons || {};
  return (
    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
      {CAT_ICON_OPTIONS.map((k) => {
        const active = value === k;
        return (
          <button key={k} type="button" onClick={() => onChange(k)} title={k} style={{
            appearance: 'none', cursor: 'pointer', width: 38, height: 38, borderRadius: 10,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            background: active ? c.selectedBg : 'transparent',
            color: active ? c.selectedText : c.muted,
            border: `1px solid ${active ? c.primary : c.border}`,
          }}>{icons[k]}</button>
        );
      })}
    </div>
  );
}

// ─────────── Kategori Yönetimi (Faz 3 / Parça 3.2) ───────────
function AdminCategories({ c }) {
  const isMobile = useIsMobile();
  const cats = useCategoriesSnapshot();
  const products = window.CATALOG_PRODUCTS || [];
  const M = window.__categories || {};

  const [adding, setAdding] = React.useState(false);
  const [newName, setNewName] = React.useState('');
  const [newIcon, setNewIcon] = React.useState('grid');
  const [editId, setEditId] = React.useState(null);
  const [editName, setEditName] = React.useState('');
  const [editIcon, setEditIcon] = React.useState('grid');
  const [subDraft, setSubDraft] = React.useState({});   // {groupId: text}

  const groupCount = (gid) => products.filter((p) => p.group === gid).length;
  const subCount = (gid, sub) => products.filter((p) => p.group === gid && p.sub === sub).length;

  function addGroup() {
    if (!newName.trim()) { alert('Kategori adı zorunlu.'); return; }
    if (M.addGroup) M.addGroup({ name: newName, iconKey: newIcon });
    setNewName(''); setNewIcon('grid'); setAdding(false);
  }
  function startEdit(g) { setEditId(g.id); setEditName(g.name); setEditIcon(g.iconKey || 'grid'); }
  function saveEdit() {
    if (!editName.trim()) { alert('Kategori adı zorunlu.'); return; }
    if (M.updateGroup) M.updateGroup(editId, { name: editName.trim(), iconKey: editIcon });
    setEditId(null);
  }
  function delGroup(g) {
    const n = groupCount(g.id);
    const msg = n > 0
      ? `"${g.name}" kategorisinde ${n} ürün var. Kategoriyi silerseniz bu ürünler kategorisiz kalır. Silinsin mi?`
      : `"${g.name}" kategorisi silinsin mi?`;
    if (window.confirm(msg) && M.removeGroup) M.removeGroup(g.id);
  }
  function addSub(gid) {
    const v = (subDraft[gid] || '').trim();
    if (!v) return;
    if (M.addSub) M.addSub(gid, v);
    setSubDraft((p) => ({ ...p, [gid]: '' }));
  }
  function delSub(gid, sub) {
    const n = subCount(gid, sub);
    const msg = n > 0 ? `"${sub}" alt kategorisinde ${n} ürün var. Silinsin mi?` : `"${sub}" silinsin mi?`;
    if (window.confirm(msg) && M.removeSub) M.removeSub(gid, sub);
  }

  return (
    <div>
      {/* Üst aksiyon */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
        <div style={{ fontSize: 13, color: c.muted }}>{cats.length} ana kategori · {cats.reduce((s, g) => s + g.subs.length, 0)} alt kategori</div>
        {!adding && <button onClick={() => setAdding(true)} style={adminSolid(c.primary)}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14" /></svg>
          Yeni ana kategori
        </button>}
      </div>

      {/* Yeni kategori formu */}
      {adding && (
        <div style={{ background: c.card, border: `1px solid ${c.primary}`, borderRadius: 14, padding: 18, marginBottom: 16 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: c.text, marginBottom: 12 }}>Yeni ana kategori</div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'flex-start' }}>
            <input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="Kategori adı (örn. Ağ & Güvenlik)" autoFocus
              style={{ ...adminInput(c), flex: isMobile ? '1 1 100%' : '1 1 240px' }} onKeyDown={(e) => e.key === 'Enter' && addGroup()} />
            <div>
              <div style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>İkon</div>
              <IconPicker value={newIcon} onChange={setNewIcon} c={c} />
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            <button onClick={addGroup} style={adminSolid(c.success)}>Ekle</button>
            <button onClick={() => { setAdding(false); setNewName(''); }} style={adminGhost(c)}>Vazgeç</button>
          </div>
        </div>
      )}

      {/* Kategori kartları */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {cats.map((g) => {
          const editing = editId === g.id;
          return (
            <div key={g.id} style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 14, padding: isMobile ? 14 : 18 }}>
              {/* Başlık satırı */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: editing ? 12 : 14 }}>
                <span style={{ display: 'flex', color: c.muted }}>{(window.CatIcons || {})[g.iconKey] || (window.CatIcons || {}).grid}</span>
                {editing ? (
                  <input value={editName} onChange={(e) => setEditName(e.target.value)} style={{ ...adminInput(c), flex: 1 }} onKeyDown={(e) => e.key === 'Enter' && saveEdit()} />
                ) : (
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 15, fontWeight: 600, color: c.text }}>{g.name}</div>
                    <div style={{ fontSize: 12, color: c.muted }}>{groupCount(g.id)} ürün · {g.subs.length} alt kategori</div>
                  </div>
                )}
                {!editing && (
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button onClick={() => startEdit(g)} style={{ ...adminGhost(c), padding: '7px 11px' }}>Düzenle</button>
                    <button onClick={() => delGroup(g)} style={{ ...adminGhost(c), padding: '7px 11px', color: c.danger }}>Sil</button>
                  </div>
                )}
              </div>

              {editing && (
                <div style={{ marginBottom: 14 }}>
                  <div style={{ fontSize: 11.5, color: c.muted, marginBottom: 6 }}>İkon</div>
                  <IconPicker value={editIcon} onChange={setEditIcon} c={c} />
                  <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                    <button onClick={saveEdit} style={adminSolid(c.success)}>Kaydet</button>
                    <button onClick={() => setEditId(null)} style={adminGhost(c)}>Vazgeç</button>
                  </div>
                </div>
              )}

              {/* Alt kategoriler */}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}>
                {g.subs.length === 0 && <span style={{ fontSize: 12.5, color: c.subtle }}>Henüz alt kategori yok.</span>}
                {g.subs.map((sub) => (
                  <span key={sub} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 7,
                    padding: '5px 8px 5px 11px', borderRadius: 999,
                    background: c.chipBg, color: c.text, fontSize: 12.5,
                  }}>
                    {sub}
                    <span style={{ fontSize: 11, color: c.muted }}>{subCount(g.id, sub)}</span>
                    <button onClick={() => delSub(g.id, sub)} title="Sil" style={{
                      appearance: 'none', cursor: 'pointer', border: 'none', background: 'transparent',
                      color: c.muted, display: 'inline-flex', padding: 0,
                    }}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
                    </button>
                  </span>
                ))}
              </div>

              {/* Alt kategori ekle */}
              <div style={{ display: 'flex', gap: 8 }}>
                <input value={subDraft[g.id] || ''} onChange={(e) => setSubDraft((p) => ({ ...p, [g.id]: e.target.value }))}
                  placeholder="Alt kategori ekle..." style={{ ...adminInput(c), flex: 1, padding: '8px 11px' }}
                  onKeyDown={(e) => e.key === 'Enter' && addSub(g.id)} />
                <button onClick={() => addSub(g.id)} style={{ ...adminGhost(c), padding: '8px 14px' }}>Ekle</button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─────────── Üst sekme şeridi (mobil) ───────────
function AdminMobileBar({ c, section, setSection, dark, setDark }) {
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 20, background: c.surface, borderBottom: `1px solid ${c.border}` }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px' }}>
        <img src="images/logo/mark-color.svg" alt="" width="30" height="30" style={{ borderRadius: 7 }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: c.text }}>Yönetim Paneli</div>
        </div>
        <button onClick={() => setDark((d) => !d)} style={{ ...adminGhost(c), padding: 8 }}>{dark ? <IconSun /> : <IconMoon />}</button>
        <button onClick={() => window.__navigate && window.__navigate('catalog')} style={{ ...adminGhost(c), padding: 8 }} title="Mağaza">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /></svg>
        </button>
        <button onClick={() => window.__navigate && window.__navigate('__logout')} style={{ ...adminGhost(c), padding: 8, color: c.danger }} title="Çıkış">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /><path d="M16 17l5-5-5-5M21 12H9" /></svg>
        </button>
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', padding: '0 12px 8px' }}>
        <AdminQuickNav c={c} />
      </div>
      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '0 16px 12px' }}>
        {ADMIN_SECTIONS.map((s) => {
          const active = section === s.id;
          return (
            <button key={s.id} onClick={() => setSection(s.id)} style={{
              appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap',
              padding: '7px 13px', borderRadius: 999, border: `1px solid ${active ? c.primary : c.border}`,
              background: active ? c.selectedBg : 'transparent', color: active ? c.selectedText : c.muted,
              fontSize: 12.5, fontWeight: 600,
            }}>{s.label}</button>
          );
        })}
      </div>
    </div>
  );
}

// ─────────── Genel Bakış (gerçek özet) ───────────
function AdminOverview({ c }) {
  const isMobile = useIsMobile();
  const products = window.CATALOG_PRODUCTS || [];
  const cats = window.CATALOG_CATEGORIES || [];
  const subCount = cats.reduce((s, g) => s + ((g.subs && g.subs.length) || 0), 0);
  const users = window.DEMO_USERS || [];
  const allApprovals = useApprovalsSnapshot();
  const pendingApprovals = allApprovals.filter((r) => r.status === 'pending').length;

  const stats = [
    ['Toplam ürün', String(products.length), c.primary],
    ['Kategori', `${cats.length} ana · ${subCount} alt`, c.text],
    ['Kullanıcı', String(users.length), c.text],
    ['Bekleyen onay', String(pendingApprovals), pendingApprovals > 0 ? '#B45309' : c.text],
  ];

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)', gap: 12, marginBottom: 20 }}>
        {stats.map(([label, val, color]) => (
          <div key={label} style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 14, padding: isMobile ? '13px 15px' : '16px 18px' }}>
            <div style={{ fontSize: 11.5, color: c.muted, marginBottom: 7 }}>{label}</div>
            <div style={{ fontSize: isMobile ? 18 : 22, fontWeight: 700, color, letterSpacing: '-0.01em' }}>{val}</div>
          </div>
        ))}
      </div>

      <div style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 16, padding: isMobile ? 18 : 24 }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: c.text, marginBottom: 8 }}>Yönetim Paneline hoş geldiniz</div>
        <div style={{ fontSize: 13.5, color: c.muted, lineHeight: 1.6, marginBottom: 16 }}>
          Buradan katalog (kategori & ürün), kullanıcı/yetki, raporlar ve sistem ayarlarını yöneteceksiniz.
          Soldaki menüden ilgili bölüme geçin. Bölümler sırayla devreye alınıyor:
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {ADMIN_SECTIONS.filter((s) => s.id !== 'overview').map((s) => {
            const intro = ADMIN_SECTION_INTRO[s.id];
            return (
              <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 13px', borderRadius: 12, background: c.chipBg }}>
                <span style={{ display: 'flex', color: c.muted }}>{ADMIN_ICONS[s.id]}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: c.text }}>{s.label}</div>
                  <div style={{ fontSize: 12, color: c.muted }}>{intro ? intro.desc : ''}</div>
                </div>
                <span style={{ fontSize: 11, fontWeight: 600, color: c.muted, whiteSpace: 'nowrap' }}>{intro ? intro.soon : ''}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─────────── Placeholder bölüm ───────────
function AdminPlaceholder({ c, section }) {
  const intro = ADMIN_SECTION_INTRO[section] || { title: 'Bölüm', desc: '', soon: '' };
  return (
    <div style={{ background: c.card, border: `1px dashed ${c.border}`, borderRadius: 16, padding: 40, textAlign: 'center' }}>
      <div style={{ width: 52, height: 52, borderRadius: 14, background: c.chipBg, color: c.muted, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
        {ADMIN_ICONS[section]}
      </div>
      <div style={{ fontSize: 16, fontWeight: 700, color: c.text, marginBottom: 8 }}>{intro.title}</div>
      <div style={{ fontSize: 13.5, color: c.muted, lineHeight: 1.6, maxWidth: 520, margin: '0 auto 16px' }}>{intro.desc}</div>
      <span style={{ display: 'inline-block', padding: '6px 14px', borderRadius: 999, background: c.selectedBg, color: c.selectedText, fontSize: 12.5, fontWeight: 600 }}>
        Bu bölüm sıradaki adımda eklenecek · {intro.soon}
      </span>
    </div>
  );
}

// ─────────── Ürün ekleme/düzenleme formu ───────────
const PRODUCT_IMG_KINDS = ['laptop', 'desktop', 'monitor', 'keyboard', 'mouse', 'headset', 'webcam', 'dock', 'speaker', 'software', 'server', 'service'];

function ProductForm({ c, cats, initial, onSave, onCancel }) {
  const isMobile = useIsMobile();
  const [name, setName] = React.useState(initial ? initial.name : '');
  const [brand, setBrand] = React.useState(initial ? (initial.brand || '') : '');
  const [model, setModel] = React.useState(initial ? (initial.model || '') : '');
  const [group, setGroup] = React.useState(initial ? initial.group : (cats[0] && cats[0].id) || '');
  const [sub, setSub] = React.useState(initial ? (initial.sub || '') : '');
  const [priceNet, setPriceNet] = React.useState(initial ? String(initial.priceNet || '') : '');
  const [priceUnit, setPriceUnit] = React.useState(initial ? (initial.priceUnit || '') : '');
  const [expenseType, setExpenseType] = React.useState(initial ? (initial.expenseType || 'auto') : 'auto');
  const [imgKind, setImgKind] = React.useState(initial ? (initial.imgKind || 'service') : 'service');
  const [desc, setDesc] = React.useState(initial ? (initial.desc || '') : '');
  const [imgDataUrl, setImgDataUrl] = React.useState(initial ? (initial.imgDataUrl || '') : '');

  const groupObj = cats.find((g) => g.id === group);
  const subs = (groupObj && groupObj.subs) || [];
  const previewSrc = imgDataUrl || (initial ? window.productImgSrc(initial) : null);

  function onFile(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) { alert('Lütfen bir görsel dosyası seçin.'); return; }
    if (file.size > 3 * 1024 * 1024) { alert('Görsel 3 MB\'tan küçük olmalı.'); return; }
    const reader = new FileReader();
    reader.onload = () => setImgDataUrl(reader.result);
    reader.readAsDataURL(file);
  }

  function save() {
    if (!name.trim()) { alert('Ürün adı zorunlu.'); return; }
    if (!group) { alert('Kategori seçin.'); return; }
    const price = parseInt(String(priceNet).replace(/[^\d]/g, ''), 10) || 0;
    if (price <= 0) { alert('Geçerli bir net fiyat girin.'); return; }
    const data = {
      name: name.trim(), brand: brand.trim(), model: model.trim(),
      group, sub: sub || (subs[0] || ''), priceNet: price,
      priceUnit: priceUnit.trim() || null,
      imgKind, desc: desc.trim(),
      imgDataUrl: imgDataUrl || undefined,
    };
    if (expenseType !== 'auto') data.expenseType = expenseType;
    onSave(data);
  }

  const lbl = { fontSize: 11.5, color: c.muted, marginBottom: 6, display: 'block' };
  const col = { display: 'flex', flexDirection: 'column' };

  return (
    <div style={{ background: c.card, border: `1px solid ${c.primary}`, borderRadius: 14, padding: isMobile ? 16 : 22, marginBottom: 16 }}>
      <div style={{ fontSize: 14, fontWeight: 700, color: c.text, marginBottom: 16 }}>{initial ? 'Ürünü düzenle' : 'Yeni ürün'}</div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
        <div style={{ ...col, gridColumn: isMobile ? 'auto' : '1 / -1' }}>
          <label style={lbl}>Ürün adı *</label>
          <input value={name} onChange={(e) => setName(e.target.value)} style={adminInput(c)} placeholder="örn. Dell UltraSharp U2723QE 27 4K" />
        </div>
        <div style={col}><label style={lbl}>Marka</label><input value={brand} onChange={(e) => setBrand(e.target.value)} style={adminInput(c)} /></div>
        <div style={col}><label style={lbl}>Model</label><input value={model} onChange={(e) => setModel(e.target.value)} style={adminInput(c)} /></div>
        <div style={col}>
          <label style={lbl}>Kategori *</label>
          <select value={group} onChange={(e) => { setGroup(e.target.value); setSub(''); }} style={adminInput(c)}>
            {cats.map((g) => <option key={g.id} value={g.id}>{g.name}</option>)}
          </select>
        </div>
        <div style={col}>
          <label style={lbl}>Alt kategori</label>
          <select value={sub} onChange={(e) => setSub(e.target.value)} style={adminInput(c)}>
            <option value="">— (yok)</option>
            {subs.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
        <div style={col}><label style={lbl}>Net fiyat (₺) *</label><input value={priceNet} onChange={(e) => setPriceNet(e.target.value)} style={adminInput(c)} placeholder="18500" inputMode="numeric" /></div>
        <div style={col}><label style={lbl}>Fiyat birimi (ops.)</label><input value={priceUnit} onChange={(e) => setPriceUnit(e.target.value)} style={adminInput(c)} placeholder="örn. yıllık/kullanıcı" /></div>
        <div style={col}>
          <label style={lbl}>Gider türü</label>
          <select value={expenseType} onChange={(e) => setExpenseType(e.target.value)} style={adminInput(c)}>
            <option value="auto">Otomatik (kategori/fiyata göre)</option>
            <option value="capex">Yatırım · CapEx</option>
            <option value="opex">İşletme Gideri · OpEx</option>
          </select>
        </div>
        <div style={col}>
          <label style={lbl}>Görsel tipi (placeholder)</label>
          <select value={imgKind} onChange={(e) => setImgKind(e.target.value)} style={adminInput(c)}>
            {PRODUCT_IMG_KINDS.map((k) => <option key={k} value={k}>{k}</option>)}
          </select>
        </div>
        <div style={{ ...col, gridColumn: isMobile ? 'auto' : '1 / -1' }}>
          <label style={lbl}>Açıklama</label>
          <textarea value={desc} onChange={(e) => setDesc(e.target.value)} rows={2} style={{ ...adminInput(c), resize: 'vertical' }} placeholder="Kısa teknik açıklama" />
        </div>

        {/* Görsel yükleme */}
        <div style={{ ...col, gridColumn: isMobile ? 'auto' : '1 / -1' }}>
          <label style={lbl}>Ürün görseli</label>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
            <div style={{ width: 84, height: 84, borderRadius: 12, border: `1px solid ${c.border}`, background: c.imgBg, overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              {previewSrc
                ? <img src={previewSrc} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                : <span style={{ fontSize: 11, color: c.subtle }}>görsel yok</span>}
            </div>
            <div>
              <label style={{ ...adminGhost(c), cursor: 'pointer' }}>
                Görsel seç
                <input type="file" accept="image/*" onChange={onFile} style={{ display: 'none' }} />
              </label>
              {imgDataUrl && <button onClick={() => setImgDataUrl('')} style={{ ...adminGhost(c), marginLeft: 8, color: c.danger }}>Kaldır</button>}
              <div style={{ fontSize: 11, color: c.subtle, marginTop: 6 }}>PNG/JPG, en çok 3 MB. (Prototipte oturum boyunca tutulur.)</div>
            </div>
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
        <button onClick={save} style={adminSolid(c.success)}>{initial ? 'Kaydet' : 'Ürünü ekle'}</button>
        <button onClick={onCancel} style={adminGhost(c)}>Vazgeç</button>
      </div>
    </div>
  );
}

// ─────────── Ürün Yönetimi (Faz 3 / Parça 3.3) ───────────
function AdminProducts({ c }) {
  const isMobile = useIsMobile();
  const products = useProductsSnapshot();
  const cats = useCategoriesSnapshot();
  const P = window.__products || {};

  const [mode, setMode] = React.useState(null);    // null | 'add' | {edit: product}
  const [filterGroup, setFilterGroup] = React.useState('all');
  const [q, setQ] = React.useState('');

  const groupName = (gid) => (cats.find((g) => g.id === gid) || {}).name || '—';
  const list = products.filter((p) => {
    if (filterGroup !== 'all' && p.group !== filterGroup) return false;
    if (q.trim()) {
      const s = q.trim().toLowerCase();
      if (!((p.name || '').toLowerCase().includes(s) || (p.brand || '').toLowerCase().includes(s))) return false;
    }
    return true;
  });

  function handleSave(data) {
    if (mode && mode.edit) { if (P.updateProduct) P.updateProduct(mode.edit.id, data); }
    else { if (P.addProduct) P.addProduct(data); }
    setMode(null);
  }

  return (
    <div>
      {mode && (
        <ProductForm c={c} cats={cats} initial={mode.edit || null} onSave={handleSave} onCancel={() => setMode(null)} />
      )}

      {/* Filtre + ekle */}
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 16, flexWrap: 'wrap' }}>
        <select value={filterGroup} onChange={(e) => setFilterGroup(e.target.value)} style={{ ...adminInput(c), padding: '8px 11px' }}>
          <option value="all">Tüm kategoriler</option>
          {cats.map((g) => <option key={g.id} value={g.id}>{g.name}</option>)}
        </select>
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Ürün ara..." style={{ ...adminInput(c), flex: '1 1 200px', padding: '8px 11px' }} />
        {!mode && <button onClick={() => setMode({ add: true })} style={adminSolid(c.primary)}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14" /></svg>
          Yeni ürün
        </button>}
      </div>

      <div style={{ fontSize: 12.5, color: c.muted, marginBottom: 10 }}>{list.length} ürün</div>

      {/* Ürün listesi */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {list.length === 0 && (
          <div style={{ background: c.card, border: `1px dashed ${c.border}`, borderRadius: 14, padding: 32, textAlign: 'center', color: c.muted }}>Ürün bulunamadı.</div>
        )}
        {list.map((p) => {
          const passive = p.active === false;
          const exp = window.getExpenseType ? window.getExpenseType(p) : 'opex';
          return (
            <div key={p.id} style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 14, padding: isMobile ? 12 : 14, display: 'flex', alignItems: 'center', gap: 14, opacity: passive ? 0.6 : 1 }}>
              <div style={{ width: 52, height: 52, borderRadius: 10, border: `1px solid ${c.border}`, background: c.imgBg, overflow: 'hidden', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {window.productImgSrc(p)
                  ? <img src={window.productImgSrc(p)} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                  : <span style={{ fontSize: 13, fontWeight: 600, color: c.muted }}>{(p.name || '?').charAt(0)}</span>}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 13.5, fontWeight: 600, color: c.text }}>{p.name}</span>
                  {passive && <span style={{ fontSize: 10.5, fontWeight: 600, color: c.muted, background: c.chipBg, padding: '2px 7px', borderRadius: 999 }}>Pasif</span>}
                </div>
                <div style={{ fontSize: 12, color: c.muted, marginTop: 2 }}>
                  {groupName(p.group)}{p.sub ? ` · ${p.sub}` : ''} · {formatTL(p.priceNet)}{p.priceUnit ? ` · ${p.priceUnit}` : ''} · {exp === 'capex' ? 'CapEx' : 'OpEx'}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                <button onClick={() => setMode({ edit: p })} style={{ ...adminGhost(c), padding: '7px 11px' }}>Düzenle</button>
                <button onClick={() => P.setActive && P.setActive(p.id, passive)} style={{ ...adminGhost(c), padding: '7px 11px', color: passive ? c.success : c.danger }}>
                  {passive ? 'Aktifleştir' : 'Pasifleştir'}
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─────────── Kullanıcı ekleme/düzenleme formu ───────────
const ROLE_ORDER = ['requester', 'approver', 'purchaser', 'catalog_manager', 'module_admin'];

function UserForm({ c, cats, users, selfId, initial, onSave, onCancel }) {
  const isMobile = useIsMobile();
  const R = window.ROLES || {};
  const [name, setName] = React.useState(initial ? initial.name : '');
  const [email, setEmail] = React.useState(initial ? (initial.email || '') : '');
  const [department, setDepartment] = React.useState(initial ? (initial.department || '') : '');
  const [position, setPosition] = React.useState(initial ? (initial.position || '') : '');
  const MODS = window.MODULES || {};
  const activeModules = Object.keys(MODS).filter((m) => MODS[m].active);
  // Modül-bazlı roller: { it: Set, admin: Set, pmkt: Set, ... }
  const [rolesByModule, setRolesByModule] = React.useState(() => {
    const init = (initial && initial.roles) || { it: ['requester'] };
    const o = {};
    Object.keys(init).forEach((m) => { o[m] = new Set(init[m]); });
    return o;
  });
  const [superAdmin, setSuperAdmin] = React.useState(initial ? !!initial.superAdmin : false);
  const [allowed, setAllowed] = React.useState(() => new Set((initial && initial.allowedCategories) || []));
  const [managerId, setManagerId] = React.useState(initial ? (initial.managerId || '') : '');
  const [catQuery, setCatQuery] = React.useState('');   // kategori izni arama (binlerce kategori için)
  const managerOptions = (users || []).filter((u) => u.id !== selfId);

  const toggleRole = (mod, r) => setRolesByModule((prev) => {
    const n = { ...prev };
    const s = new Set(n[mod] || []);
    s.has(r) ? s.delete(r) : s.add(r);
    n[mod] = s;
    return n;
  });
  const toggleCat = (id) => setAllowed((prev) => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });

  // Döngü engeli: seçilen yöneticiden yukarı yürürken bu kullanıcıya ulaşıyorsak loop olur.
  function createsCycle(mid) {
    if (!mid || !selfId) return false;
    const byId = {}; (users || []).forEach((u) => { byId[u.id] = u; });
    let cur = mid, guard = 0;
    while (cur && guard++ < 50) {
      if (cur === selfId) return true;
      cur = byId[cur] && byId[cur].managerId;
    }
    return false;
  }

  function save() {
    if (!name.trim()) { alert('Ad soyad zorunlu.'); return; }
    // Modül-bazlı rolleri topla: aktif olmayan modüllerin mevcut rollerini koru
    const rolesObj = {};
    if (initial && initial.roles) {
      Object.keys(initial.roles).forEach((m) => { if (!activeModules.includes(m)) rolesObj[m] = initial.roles[m]; });
    }
    activeModules.forEach((m) => {
      const arr = ROLE_ORDER.filter((r) => (rolesByModule[m] || new Set()).has(r));
      if (arr.length) rolesObj[m] = arr;
    });
    if (!superAdmin && Object.keys(rolesObj).length === 0) { alert('En az bir modülde rol seçin (veya Süper Admin işaretleyin).'); return; }
    if (managerId && createsCycle(managerId)) { alert('Geçersiz: bu kullanıcı, seçtiğiniz yöneticinin (alt) yöneticisi durumunda — döngü oluşur.'); return; }
    const initials = name.trim().split(/\s+/).slice(0, 2).map((w) => w[0]).join('').toUpperCase() || '?';
    const data = {
      name: name.trim(), email: email.trim(), department: department.trim(), position: position.trim(),
      initials,
      roles: Object.keys(rolesObj).length ? rolesObj : { it: ['requester'] },
      superAdmin: superAdmin || undefined,
      allowedCategories: Array.from(allowed),
      managerId: managerId || null,
      managerSource: 'manual',
    };
    data.roleLabel = window.roleLabelFor ? window.roleLabelFor(data) : '';
    onSave(data);
  }

  const lbl = { fontSize: 11.5, color: c.muted, marginBottom: 6, display: 'block' };
  const col = { display: 'flex', flexDirection: 'column' };

  return (
    <div style={{ background: c.card, border: `1px solid ${c.primary}`, borderRadius: 14, padding: isMobile ? 16 : 22, marginBottom: 16 }}>
      <div style={{ fontSize: 14, fontWeight: 700, color: c.text, marginBottom: 16 }}>{initial ? 'Kullanıcıyı düzenle' : 'Yeni kullanıcı'}</div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
        <div style={col}><label style={lbl}>Ad soyad *</label><input value={name} onChange={(e) => setName(e.target.value)} style={adminInput(c)} placeholder="örn. Ali Vural" /></div>
        <div style={col}><label style={lbl}>E-posta</label><input value={email} onChange={(e) => setEmail(e.target.value)} style={adminInput(c)} placeholder="ali.vural@sirket.com" /></div>
        <div style={col}><label style={lbl}>Departman</label><input value={department} onChange={(e) => setDepartment(e.target.value)} style={adminInput(c)} placeholder="örn. Pazarlama" /></div>
        <div style={col}><label style={lbl}>Pozisyon</label><input value={position} onChange={(e) => setPosition(e.target.value)} style={adminInput(c)} placeholder="örn. Uzman" /></div>
        <div style={{ ...col, gridColumn: isMobile ? 'auto' : '1 / -1' }}>
          <label style={lbl}>Bağlı olduğu yönetici (onay zincirinde "Yöneticim")</label>
          <select value={managerId} onChange={(e) => setManagerId(e.target.value)} style={adminInput(c)}>
            <option value="">— Yok / en üst kademe</option>
            {managerOptions.map((u) => <option key={u.id} value={u.id}>{u.name}{u.department ? ` · ${u.department}` : ''}</option>)}
          </select>
          <div style={{ fontSize: 11, color: c.subtle, marginTop: 6 }}>
            Active Directory bağlandığında bu alan AD'deki <b>manager</b> özniteliğinden otomatik dolar (Sistem &amp; LDAP). AD yoksa buradan elle atanır.
          </div>
        </div>
      </div>

      {/* Roller — her aktif modül için ayrı atama */}
      <div style={{ marginTop: 16 }}>
        <label style={lbl}>Modül rolleri</label>
        <div style={{ fontSize: 11.5, color: c.subtle, marginBottom: 10 }}>
          Kullanıcı her modülde farklı rol alabilir. Rol seçilmeyen <b>kısıtlı</b> modülü göremez; <b>ortak</b> modüller (IT, İdari) rolsüz de görünür ama talep için en az "Talep Eden" gerekir.
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {activeModules.map((mid) => {
            const m = MODS[mid] || {};
            const sel = rolesByModule[mid] || new Set();
            return (
              <div key={mid} style={{ border: `1px solid ${c.border}`, borderRadius: 12, padding: '12px 14px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                  <span style={{ width: 10, height: 10, borderRadius: 999, background: m.color, flexShrink: 0 }} />
                  <span style={{ fontSize: 13, fontWeight: 700, color: c.text }}>{m.name}</span>
                  <span style={{ fontSize: 11, color: c.subtle }}>{m.scope === 'restricted' ? '🔒 kısıtlı' : 'ortak'}</span>
                </div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {ROLE_ORDER.map((r) => {
                    const on = sel.has(r);
                    return (
                      <button key={r} type="button" onClick={() => toggleRole(mid, r)} title={R[r] && R[r].desc} style={{
                        appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
                        padding: '7px 12px', borderRadius: 999, fontSize: 12, fontWeight: 600,
                        border: `1px solid ${on ? c.primary : c.border}`,
                        background: on ? c.selectedBg : 'transparent', color: on ? c.selectedText : c.muted,
                      }}>{on ? '✓ ' : ''}{(R[r] && R[r].label) || r}</button>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Süper Admin */}
      <label style={{ display: 'flex', alignItems: 'center', gap: 9, marginTop: 16, fontSize: 13, color: c.text, cursor: 'pointer' }}>
        <input type="checkbox" checked={superAdmin} onChange={(e) => setSuperAdmin(e.target.checked)} />
        <span><b>Süper Admin</b> — tüm yetkiler + sistem ayarları</span>
      </label>

      {/* Kategori izni — modüle göre gruplu + aramalı (binlerce kategori için) */}
      <div style={{ marginTop: 16 }}>
        <label style={lbl}>İzinli kategoriler (kategori-bazlı yetki)</label>
        <div style={{ fontSize: 11.5, color: c.subtle, marginBottom: 8 }}>
          Bir modülde <b>hiç</b> kategori seçili değilse kullanıcı o modülün <b>tümünü</b> görür. Seçilirse yalnız işaretliler. İzin <b>modül bazında</b> çalışır.
        </div>
        <input value={catQuery} onChange={(e) => setCatQuery(e.target.value)} placeholder="Kategori ara…" style={{ ...adminInput(c), marginBottom: 12 }} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {activeModules.map((mid) => {
            const m = MODS[mid] || {};
            const q = catQuery.trim().toLowerCase();
            const modCats = cats.filter((g) => (g.module || 'it') === mid && (!q || g.name.toLowerCase().includes(q)));
            const totalInMod = cats.filter((g) => (g.module || 'it') === mid).length;
            const selInMod = cats.filter((g) => (g.module || 'it') === mid && allowed.has(g.id)).length;
            if (q && modCats.length === 0) return null;   // arama sonucu boşsa bu modülü gizle
            return (
              <div key={mid} style={{ border: `1px solid ${c.border}`, borderRadius: 12, padding: '10px 12px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 999, background: m.color, flexShrink: 0 }} />
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: c.text }}>{m.name}</span>
                  <span style={{ fontSize: 11, color: selInMod ? c.primary : c.subtle }}>
                    {selInMod ? `${selInMod} kategori seçili` : 'tümü görünür'}
                  </span>
                  {selInMod > 0 && (
                    <button type="button" onClick={() => setAllowed((prev) => { const n = new Set(prev); cats.forEach((g) => { if ((g.module || 'it') === mid) n.delete(g.id); }); return n; })}
                      style={{ marginLeft: 'auto', appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer', fontSize: 11, color: c.muted, fontFamily: 'inherit', textDecoration: 'underline' }}>
                      sıfırla
                    </button>
                  )}
                </div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {modCats.map((g) => {
                    const on = allowed.has(g.id);
                    return (
                      <button key={g.id} type="button" onClick={() => toggleCat(g.id)} style={{
                        appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
                        padding: '6px 11px', borderRadius: 999, fontSize: 12, fontWeight: 500,
                        border: `1px solid ${on ? c.primary : c.border}`,
                        background: on ? c.selectedBg : 'transparent', color: on ? c.selectedText : c.muted,
                      }}>{on ? '✓ ' : ''}{g.name}</button>
                    );
                  })}
                  {!q && modCats.length === 0 && <span style={{ fontSize: 11.5, color: c.subtle }}>Bu modülde kategori yok.</span>}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, marginTop: 20 }}>
        <button onClick={save} style={adminSolid(c.success)}>{initial ? 'Kaydet' : 'Kullanıcı ekle'}</button>
        <button onClick={onCancel} style={adminGhost(c)}>Vazgeç</button>
      </div>
    </div>
  );
}

// ─────────── Kullanıcılar & Yetkiler (Faz 3 / Parça 3.4) ───────────
function AdminUsers({ c }) {
  const isMobile = useIsMobile();
  const users = useUsersSnapshot();
  const cats = useCategoriesSnapshot();
  const U = window.__users || {};
  const R = window.ROLES || {};
  const [mode, setMode] = React.useState(null);   // null | {add} | {edit:user}

  const catName = (id) => (cats.find((g) => g.id === id) || {}).name || id;
  const userName = (id) => (users.find((x) => x.id === id) || {}).name || null;

  function handleSave(data) {
    if (mode && mode.edit) { if (U.updateUser) U.updateUser(mode.edit.id, data); }
    else { if (U.addUser) U.addUser(data); }
    setMode(null);
  }

  return (
    <div>
      {mode && <UserForm c={c} cats={cats} users={users} selfId={mode.edit ? mode.edit.id : null} initial={mode.edit || null} onSave={handleSave} onCancel={() => setMode(null)} />}

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
        <div style={{ fontSize: 13, color: c.muted }}>{users.length} kullanıcı</div>
        {!mode && <button onClick={() => setMode({ add: true })} style={adminSolid(c.primary)}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14" /></svg>
          Yeni kullanıcı
        </button>}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {users.map((u) => {
          const passive = u.active === false;
          const MODS = window.MODULES || {};
          const roleMods = Object.keys(u.roles || {}).filter((m) => (u.roles[m] || []).length);
          const allowedCats = u.allowedCategories || [];
          return (
            <div key={u.id} style={{ background: c.card, border: `1px solid ${c.border}`, borderRadius: 14, padding: isMobile ? 14 : 16, opacity: passive ? 0.6 : 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <span style={{ width: 42, height: 42, borderRadius: 999, flexShrink: 0, background: u.superAdmin ? '#7C3AED' : '#475569', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 600 }}>{u.initials}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 14, fontWeight: 600, color: c.text }}>{u.name}</span>
                    {passive && <span style={{ fontSize: 10.5, fontWeight: 600, color: c.muted, background: c.chipBg, padding: '2px 7px', borderRadius: 999 }}>Pasif</span>}
                  </div>
                  <div style={{ fontSize: 12, color: c.muted }}>
                    {u.email || '—'}{u.department ? ` · ${u.department}` : ''}
                    {' · '}Yönetici: {userName(u.managerId) || <span style={{ color: c.subtle }}>atanmamış</span>}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                  <button onClick={() => setMode({ edit: u })} style={{ ...adminGhost(c), padding: '7px 11px' }}>Düzenle</button>
                  <button onClick={() => U.setActive && U.setActive(u.id, passive)} style={{ ...adminGhost(c), padding: '7px 11px', color: passive ? c.success : c.danger }}>{passive ? 'Aktifleştir' : 'Pasifleştir'}</button>
                </div>
              </div>

              {/* Roller + kategori izni */}
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 12, alignItems: 'center' }}>
                {u.superAdmin && <span style={{ padding: '3px 10px', borderRadius: 999, fontSize: 11.5, fontWeight: 600, background: 'rgba(124,58,237,0.14)', color: '#7C3AED' }}>Süper Admin</span>}
                {!u.superAdmin && roleMods.length === 0 && <span style={{ fontSize: 11.5, color: c.subtle }}>Rol atanmamış</span>}
                {roleMods.map((mid) => {
                  const m = MODS[mid] || {};
                  return (
                    <span key={mid} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px', borderRadius: 999, fontSize: 11.5, fontWeight: 600, background: (m.color || '#475569') + '14', color: m.color || c.text, border: `1px solid ${(m.color || '#475569')}33` }}>
                      <span style={{ width: 7, height: 7, borderRadius: 999, background: m.color || '#475569' }} />
                      {m.short || mid}: {(u.roles[mid] || []).map((r) => (R[r] && R[r].label) || r).join(', ')}
                    </span>
                  );
                })}
                <span style={{ marginLeft: 'auto', fontSize: 11.5, color: c.muted }}>
                  {allowedCats.length === 0 ? 'Tüm kategoriler' : `${allowedCats.length} kategori: ${allowedCats.map(catName).join(', ')}`}
                </span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─────────── Sayfa ───────────
function AdminPanel({ initialDark = false, user }) {
  const [dark, setDark] = React.useState(initialDark);
  React.useEffect(() => { setDark(initialDark); }, [initialDark]);
  const c = catalogTheme(dark);
  const isMobile = useIsMobile();
  const [section, setSection] = React.useState('overview');
  const current = ADMIN_SECTIONS.find((s) => s.id === section) || ADMIN_SECTIONS[0];

  return (
    <div style={{ minHeight: '100%', background: c.bg, fontFamily: 'Inter, system-ui, sans-serif', display: 'flex', flexDirection: isMobile ? 'column' : 'row' }}>
      {isMobile
        ? <AdminMobileBar c={c} section={section} setSection={setSection} dark={dark} setDark={setDark} />
        : <AdminSidebar c={c} section={section} setSection={setSection} user={user} dark={dark} setDark={setDark} />}

      <div style={{ flex: 1, minWidth: 0, padding: isMobile ? '18px 16px 40px' : '28px 32px 56px' }}>
        <div style={{ marginBottom: 18, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <h1 style={{ margin: 0, fontSize: isMobile ? 20 : 24, fontWeight: 700, color: c.text, letterSpacing: '-0.015em' }}>{current.label}</h1>
          {!isMobile && <AdminQuickNav c={c} />}
        </div>
        {section === 'overview' ? <AdminOverview c={c} />
          : section === 'categories' ? <AdminCategories c={c} />
          : section === 'products' ? <AdminProducts c={c} />
          : section === 'users' ? <AdminUsers c={c} />
          : <AdminPlaceholder c={c} section={section} />}
      </div>
    </div>
  );
}

Object.assign(window, { AdminPanel, ADMIN_SECTIONS });
