// training.jsx — Eğitim Videoları sistemi (V1: altyapı + admin video butonu + popup)
// Her sayfa/menü için bir eğitim videosu kaydı tutulur (YouTube). Süper admin V3'te
// linkleri düzenleyebilecek; V1'de altyapı + admin başlığındaki "Video Eğitim" butonu + popup.
// Veri window.__training üzerinden paylaşılır, localStorage'a yazılır (app.jsx).

// ─────────── YouTube link çözücü ───────────
// Çeşitli YouTube link biçimlerinden video kimliğini çıkarır:
//   https://www.youtube.com/watch?v=ID · https://youtu.be/ID · /embed/ID · /shorts/ID
// Zaten kimlik (11 karakter) verilmişse onu döndürür. Çözülemezse '' döner.
function parseYouTubeId(input) {
  if (!input) return '';
  const s = String(input).trim();
  if (/^[A-Za-z0-9_-]{11}$/.test(s)) return s;                       // doğrudan kimlik
  try {
    const u = new URL(s.startsWith('http') ? s : 'https://' + s);
    if (u.searchParams.get('v')) return u.searchParams.get('v');     // watch?v=ID
    const parts = u.pathname.split('/').filter(Boolean);
    const last = parts[parts.length - 1] || '';
    if (/^[A-Za-z0-9_-]{11}$/.test(last)) return last;               // youtu.be/ID · /embed/ID · /shorts/ID
  } catch (e) { /* geçersiz URL */ }
  const m = s.match(/[A-Za-z0-9_-]{11}/);                            // son çare: ilk 11'lik dizi
  return m ? m[0] : '';
}

// ─────────── Eğitim videoları seed'i ───────────
// area: 'admin' (yönetim paneli bölümleri) | 'user' (kullanıcı sayfaları — V2 Eğitim menüsü).
// Demo'da hepsi aynı tanıtım videosuna bağlı; süper admin V3'te tek tek değiştirecek.
const DEMO_TRAINING_VIDEO = 'wwIt5ZvROrs';
const TRAINING_VIDEOS_SEED = [
  // — Yönetim paneli bölümleri (anahtar: 'admin:<sectionId>') —
  { key: 'admin:overview',   area: 'admin', title: 'Genel Bakış nasıl kullanılır', desc: 'Yönetim panelinin özet ekranı, hızlı erişim ve bölümlerin tanıtımı.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'admin:categories', area: 'admin', title: 'Kategori yönetimi', desc: 'Ana/alt kategori ekleme, düzenleme ve katalogda anında yansıması.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'admin:products',   area: 'admin', title: 'Ürün ekleme ve düzenleme', desc: 'Ürün kartı alanları (fiyat birimi, gider türü, alım profili, takip türü), görsel ve üretici linki.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'admin:demand',     area: 'admin', title: 'Dönem planlama', desc: 'Talep dönemi açma, toplama, konsolidasyon ve tedarik planı.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'admin:wallet',     area: 'admin', title: 'Bütçe tahsisi', desc: 'Departman/kişi bütçe cüzdanları, teklif ve tahsis akışı.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'admin:users',      area: 'admin', title: 'Kullanıcılar ve yetkiler', desc: 'Kullanıcı ekleme, modül rolleri, kurumsal görevler ve kategori yetkileri.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'admin:reports',    area: 'admin', title: 'Raporlar', desc: 'Harcama, onay süreleri ve bütçe kullanımı raporları.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'admin:system',     area: 'admin', title: 'Sistem & LDAP', desc: 'AD/LDAP bağlantısı, grup-rol eşlemesi ve onay eşikleri.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'admin:scrap',      area: 'admin', title: 'Hurda onayları', desc: 'Hurdaya ayırma taleplerinin onayı ve süreç.', youtubeId: DEMO_TRAINING_VIDEO },
  // — Kullanıcı sayfaları (anahtar: 'user:<sayfa>') — Eğitim menüsünde gösterilir —
  { key: 'user:start',     area: 'user', title: 'Başlangıç: Sisteme genel bakış', desc: 'Yeni başlayanlar için: menüler, arama, dark mode ve temel akış.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'user:catalog',   area: 'user', title: 'Ürün bulma ve talep oluşturma', desc: 'Katalogda ürün arama, ürün detayını okuma, bütçeye ekleme / acil talep.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'user:cart',      area: 'user', title: 'Sepet ve talebi gönderme', desc: 'Sepeti gözden geçirme, adet/açıklama ve talebi onaya gönderme.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'user:requests',  area: 'user', title: 'Taleplerim ve durum takibi', desc: 'Taleplerin onay aşamalarını izleme, taslaklar ve geçmiş.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'user:demand',    area: 'user', title: 'Bütçe / dönem talepleri', desc: 'Dönem planlamasında ihtiyaç bildirme ve bütçeye ekleme.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'user:approvals', area: 'user', title: 'Onay kutusu (onaycılar)', desc: 'Onaycılar için: talebi inceleme, onaylama/reddetme, kalem çıkarma.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'user:myassets',  area: 'user', title: 'Zimmetlerim ve dijital imza', desc: 'Teslim alınan ekipmanın zimmet formunu imzalama ve iade başlatma.', youtubeId: DEMO_TRAINING_VIDEO },
  { key: 'user:profile',   area: 'user', title: 'Profil ve bütçe görünümü', desc: 'Kişisel/departman bütçe durumunu görme ve profil bilgileri.', youtubeId: DEMO_TRAINING_VIDEO },
];

// ─────────── Video popup (oynatıcı) ───────────
// videoKey ile window.__training'ten ilgili kaydı okur; iframe ile YouTube videosunu gömer.
function TrainingVideoModal({ videoKey, c, onClose, isNew = false, defaultArea = 'user' }) {
  // Canlı veriye bağlı: süper admin düzenleyince/eklediğinde anında yansır.
  const videos = useTrainingSnapshot();
  const rec = videos.find((v) => v.key === videoKey) || null;
  const isSuper = !!(window.__user && window.__user.superAdmin);
  // Yeni video eklerken doğrudan düzenleme modunda ve boş formla aç
  const [editing, setEditing] = React.useState(isNew);
  const [draft, setDraft] = React.useState({
    title: '', youtubeId: '', desc: '', area: defaultArea,
  });
  // Bu video seed'de tanımlı mı? (özel/eklenen videolar silinebilir, seed'ler silinmez)
  const isSeed = (window.TRAINING_VIDEOS_SEED || []).some((s) => s.key === videoKey);

  // Düzenleme moduna girince taslağı mevcut kayıttan doldur
  function startEdit() {
    setDraft({
      title: (rec && rec.title) || '', youtubeId: (rec && rec.youtubeId) || '',
      desc: (rec && rec.desc) || '', area: (rec && rec.area) || defaultArea,
    });
    setEditing(true);
  }
  function saveEdit() {
    if (window.__training && window.__training.setVideo) {
      window.__training.setVideo(videoKey, {
        title: draft.title.trim() || 'Yeni eğitim videosu',
        youtubeId: draft.youtubeId.trim(),
        desc: draft.desc.trim(),
        area: draft.area || defaultArea,
      });
    }
    if (isNew) { onClose(); return; }   // yeni eklendi → popup'ı kapat
    setEditing(false);
  }
  function deleteVideo() {
    if (!window.confirm('Bu eğitim videosu kaldırılsın mı?')) return;
    if (window.__training && window.__training.removeVideo) window.__training.removeVideo(videoKey);
    onClose();
  }

  // Oynatılacak / önizlenecek video kimliği: düzenlerken taslaktan, değilse kayıttan
  const id = editing ? parseYouTubeId(draft.youtubeId) : (rec ? parseYouTubeId(rec.youtubeId) : '');

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape' && !editing) onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose, editing]);

  const inp = {
    width: '100%', boxSizing: 'border-box', padding: '9px 11px', borderRadius: 9,
    border: `1px solid ${c.border}`, background: c.surface || c.bg, color: c.text,
    fontSize: 13, fontFamily: 'inherit', outline: 'none',
  };
  const inpLbl = { fontSize: 11.5, fontWeight: 600, color: c.muted, marginBottom: 5, display: 'block' };

  return (
    <div onClick={() => { if (!editing) onClose(); }} style={{
      position: 'fixed', inset: 0, zIndex: 5000,
      background: 'rgba(15,23,42,0.62)', backdropFilter: 'blur(2px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 880, background: c.card,
        border: `1px solid ${c.border}`, borderRadius: 16, overflow: 'hidden',
        boxShadow: '0 24px 64px -16px rgba(0,0,0,0.5)',
        maxHeight: '92vh', display: 'flex', flexDirection: 'column',
      }}>
        {/* Başlık */}
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '16px 18px', borderBottom: `1px solid ${c.border}` }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 11, fontWeight: 700, color: c.primary, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 4 }}>
              🎬 {isNew ? 'Yeni Eğitim Videosu' : (editing ? 'Videoyu Düzenle' : 'Eğitim Videosu')}
            </div>
            {!editing && <div style={{ fontSize: 16, fontWeight: 700, color: c.text }}>{rec ? rec.title : 'Eğitim videosu'}</div>}
            {!editing && rec && rec.desc && <div style={{ fontSize: 12.5, color: c.muted, marginTop: 4, lineHeight: 1.5 }}>{rec.desc}</div>}
          </div>
          {/* Süper admin: Düzenle / Kaydet-Vazgeç */}
          {isSuper && !editing && (
            <button onClick={startEdit} title="Bu videoyu düzenle (süper admin)" style={{
              appearance: 'none', cursor: 'pointer', border: `1px solid ${c.primary}`, background: 'transparent',
              color: c.primary, borderRadius: 8, padding: '6px 11px', fontSize: 12.5, fontWeight: 600, fontFamily: 'inherit', flexShrink: 0,
            }}>✏️ Düzenle</button>
          )}
          {editing && (
            <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
              {!isNew && !isSeed && (
                <button onClick={deleteVideo} title="Bu videoyu kaldır" style={{
                  appearance: 'none', cursor: 'pointer', border: `1px solid ${c.danger}`, background: 'transparent', color: c.danger,
                  borderRadius: 8, padding: '6px 11px', fontSize: 12.5, fontWeight: 600, fontFamily: 'inherit',
                }}>🗑 Sil</button>
              )}
              <button onClick={saveEdit} style={{
                appearance: 'none', cursor: 'pointer', border: 'none', background: c.success, color: '#fff',
                borderRadius: 8, padding: '6px 12px', fontSize: 12.5, fontWeight: 600, fontFamily: 'inherit',
              }}>{isNew ? 'Ekle' : 'Kaydet'}</button>
              <button onClick={() => { if (isNew) onClose(); else setEditing(false); }} style={{
                appearance: 'none', cursor: 'pointer', border: `1px solid ${c.border}`, background: 'transparent', color: c.muted,
                borderRadius: 8, padding: '6px 12px', fontSize: 12.5, fontWeight: 600, fontFamily: 'inherit',
              }}>Vazgeç</button>
            </div>
          )}
          {!editing && (
            <button onClick={onClose} aria-label="Kapat" style={{
              appearance: 'none', cursor: 'pointer', border: `1px solid ${c.border}`, background: 'transparent',
              color: c.muted, borderRadius: 8, width: 32, height: 32, fontSize: 18, lineHeight: 1, flexShrink: 0,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'inherit',
            }}>×</button>
          )}
        </div>

        <div style={{ overflowY: 'auto' }}>
          {/* Düzenleme formu (süper admin) */}
          {editing && (
            <div style={{ padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 13, borderBottom: `1px solid ${c.border}` }}>
              <div>
                <label style={inpLbl}>Bölüm</label>
                <select value={draft.area} onChange={(e) => setDraft((d) => ({ ...d, area: e.target.value }))} style={inp}>
                  <option value="user">Sistem Kullanımı (herkese görünür)</option>
                  <option value="admin">Yönetim (yalnız yöneticiler)</option>
                </select>
              </div>
              <div>
                <label style={inpLbl}>Başlık</label>
                <input value={draft.title} onChange={(e) => setDraft((d) => ({ ...d, title: e.target.value }))} style={inp} placeholder="Video başlığı" />
              </div>
              <div>
                <label style={inpLbl}>YouTube linki veya video kimliği</label>
                <input value={draft.youtubeId} onChange={(e) => setDraft((d) => ({ ...d, youtubeId: e.target.value }))} style={inp} placeholder="https://www.youtube.com/watch?v=..." />
                <div style={{ fontSize: 11, marginTop: 5, color: parseYouTubeId(draft.youtubeId) ? c.success : (draft.youtubeId ? c.danger : c.subtle) }}>
                  {parseYouTubeId(draft.youtubeId)
                    ? `✓ Video kimliği: ${parseYouTubeId(draft.youtubeId)}`
                    : (draft.youtubeId ? '✗ Geçerli bir YouTube linki/kimliği çözülemedi' : 'watch?v=, youtu.be/, /embed/, /shorts/ linkleri desteklenir')}
                </div>
              </div>
              <div>
                <label style={inpLbl}>Açıklama</label>
                <textarea value={draft.desc} onChange={(e) => setDraft((d) => ({ ...d, desc: e.target.value }))} rows={2} style={{ ...inp, resize: 'vertical' }} placeholder="Kısa açıklama" />
              </div>
            </div>
          )}

          {/* Video alanı (16:9) — düzenlerken yazılan linkin canlı önizlemesi */}
          <div style={{ position: 'relative', width: '100%', paddingTop: '56.25%', background: '#000' }}>
            {id ? (
              <iframe
                title={rec ? rec.title : 'Eğitim videosu'}
                src={`https://www.youtube.com/embed/${id}?rel=0&modestbranding=1`}
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
                style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 'none' }}
              />
            ) : (
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#9CA3AF', fontSize: 13.5, textAlign: 'center', padding: 24 }}>
                {editing ? 'Geçerli bir YouTube linki girin — önizleme burada görünür.' : 'Bu bölüm için henüz eğitim videosu eklenmemiş.'}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────── "Video Eğitim" butonu ───────────
// videoKey'e bağlı popup açar. label opsiyonel (varsayılan "Video Eğitim").
// compact=true → yalnız ikon (dar alanlar için).
function TrainingButton({ videoKey, c, label = 'Video Eğitim', compact = false }) {
  const [open, setOpen] = React.useState(false);
  return (
    <React.Fragment>
      <button onClick={() => setOpen(true)} title="Bu bölümün eğitim videosunu izle" style={{
        appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
        display: 'inline-flex', alignItems: 'center', gap: 7,
        padding: compact ? '7px 9px' : '7px 12px', borderRadius: 10,
        border: `1px solid ${c.primary}`, background: 'transparent', color: c.primary,
        fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', transition: 'background 120ms',
      }}
      onMouseEnter={(e) => e.currentTarget.style.background = c.selectedBg}
      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
        <span style={{ fontSize: 14, lineHeight: 1 }}>🎬</span>
        {!compact && label}
      </button>
      {open && <TrainingVideoModal videoKey={videoKey} c={c} onClose={() => setOpen(false)} />}
    </React.Fragment>
  );
}

// Eğitim videoları abonesi (window.__training + 'trainingchange') — süper admin düzenleyince (V3) canlı yansır
function useTrainingSnapshot() {
  const [items, setItems] = React.useState(() => (window.__training && window.__training.items) || window.TRAINING_VIDEOS_SEED || []);
  React.useEffect(() => {
    const sync = () => setItems((window.__training && window.__training.items) || window.TRAINING_VIDEOS_SEED || []);
    window.addEventListener('trainingchange', sync);
    sync();
    return () => window.removeEventListener('trainingchange', sync);
  }, []);
  return items;
}

// YouTube küçük resmi (thumbnail) — kart önizlemesi için
function ytThumb(youtubeId) {
  const id = parseYouTubeId(youtubeId);
  return id ? `https://img.youtube.com/vi/${id}/hqdefault.jpg` : null;
}

// ─────────── Eğitim videosu kartı ───────────
function TrainingCard({ rec, c, onOpen }) {
  const thumb = ytThumb(rec.youtubeId);
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={() => onOpen(rec.key)}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', padding: 0,
        background: c.card, border: `1px solid ${hover ? c.primary : c.border}`, borderRadius: 14, overflow: 'hidden',
        display: 'flex', flexDirection: 'column', transition: 'border-color 120ms, transform 120ms',
        transform: hover ? 'translateY(-2px)' : 'none',
      }}>
      {/* Küçük resim + oynat ikonu */}
      <div style={{ position: 'relative', width: '100%', paddingTop: '56.25%', background: '#000' }}>
        {thumb
          ? <img src={thumb} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: hover ? 0.85 : 0.7 }} />
          : <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#6B7280', fontSize: 12 }}>video yok</div>}
        <div style={{
          position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{
            width: 52, height: 52, borderRadius: 999, background: 'rgba(0,0,0,0.55)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: '2px solid rgba(255,255,255,0.9)',
          }}>
            <span style={{ color: '#fff', fontSize: 20, marginLeft: 3 }}>▶</span>
          </div>
        </div>
      </div>
      {/* Başlık + açıklama */}
      <div style={{ padding: '13px 15px 15px' }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: c.text, lineHeight: 1.35 }}>{rec.title}</div>
        {rec.desc && <div style={{ fontSize: 12, color: c.muted, marginTop: 5, lineHeight: 1.5 }}>{rec.desc}</div>}
      </div>
    </button>
  );
}

// ─────────── Eğitim sayfası (kullanıcı menüsü) ───────────
function TrainingPage({ initialDark = false, user }) {
  const [dark, setDark] = React.useState(initialDark);
  React.useEffect(() => { setDark(initialDark); }, [initialDark]);
  const c = catalogTheme(dark);
  const isMobile = useIsMobile();
  const [search, setSearch] = React.useState('');
  const [openKey, setOpenKey] = React.useState(null);
  const [newKey, setNewKey] = React.useState(null);   // yeni video ekleme popup'ı (süper admin)
  const cart = window.useCartSnapshot ? window.useCartSnapshot() : [];
  const videos = useTrainingSnapshot();
  const cu = (typeof useCurrentUser === 'function') ? useCurrentUser() : (user || window.__user || null);

  const isSuper = !!(cu && cu.superAdmin);
  const canAdmin = !!(cu && (cu.superAdmin
    || (window.manageableModules && window.manageableModules(cu).length > 0)
    || (window.managesAnyone && window.managesAnyone(cu))));

  const term = search.trim().toLowerCase();
  const match = (v) => !term || (v.title || '').toLowerCase().includes(term) || (v.desc || '').toLowerCase().includes(term);
  const userVids = videos.filter((v) => v.area === 'user' && match(v));
  const adminVids = videos.filter((v) => v.area === 'admin' && match(v));

  const grid = { display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(auto-fill, minmax(260px, 1fr))', gap: 16 };
  const sectionTitle = (txt, sub) => (
    <div style={{ margin: '4px 0 14px' }}>
      <h2 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: c.text }}>{txt}</h2>
      {sub && <p style={{ margin: '4px 0 0', fontSize: 12.5, color: c.muted }}>{sub}</p>}
    </div>
  );

  return (
    <div style={{ width: '100%', minHeight: '100%', background: c.bg, color: c.text, fontFamily: 'Inter, system-ui, sans-serif', display: 'flex', flexDirection: 'column' }}>
      <CatalogHeader c={c} dark={dark} onToggleDark={() => setDark((x) => !x)} search={search} setSearch={setSearch} cartCount={cart.length} notifCount={0} />

      <div style={{ padding: isMobile ? '16px 16px 40px' : '28px 32px 48px', maxWidth: 1080, margin: '0 auto', width: '100%', boxSizing: 'border-box' }}>
        <div style={{ marginBottom: 22, display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 240 }}>
            <h1 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: '-0.015em', color: c.text }}>🎓 Eğitim</h1>
            <p style={{ margin: '6px 0 0', fontSize: 13.5, color: c.muted, lineHeight: 1.5 }}>
              Sistemi adım adım öğrenin. Bir videoyu açmak için kartına tıklayın. Yeni başlayan çalışanlar için ideal başlangıç noktasıdır.
            </p>
          </div>
          {/* Süper admin: yeni video ekle */}
          {isSuper && (
            <button onClick={() => setNewKey('user:custom-' + Date.now())} style={{
              appearance: 'none', cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0,
              display: 'inline-flex', alignItems: 'center', gap: 7, padding: '9px 14px', borderRadius: 10,
              border: 'none', background: c.primary, color: '#fff', fontSize: 13.5, fontWeight: 600,
              boxShadow: `0 6px 14px -4px ${c.primary}55`,
            }}>
              <span style={{ fontSize: 16, lineHeight: 1 }}>+</span> Video Ekle
            </button>
          )}
        </div>

        {/* Sistem kullanımı (herkes) */}
        {sectionTitle('Sistem Kullanımı', 'Talep oluşturma, sepet, onay takibi ve günlük kullanım.')}
        {userVids.length > 0
          ? <div style={grid}>{userVids.map((v) => <TrainingCard key={v.key} rec={v} c={c} onOpen={setOpenKey} />)}</div>
          : <div style={{ fontSize: 13, color: c.muted, padding: 16 }}>Aramanıza uygun video bulunamadı.</div>}

        {/* Yönetim (yalnız yetkili) */}
        {canAdmin && adminVids.length > 0 && (
          <div style={{ marginTop: 36 }}>
            {sectionTitle('Yönetim', 'Yönetici/süper admin bölümlerinin kullanımı.')}
            <div style={grid}>{adminVids.map((v) => <TrainingCard key={v.key} rec={v} c={c} onOpen={setOpenKey} />)}</div>
          </div>
        )}
      </div>

      {openKey && <TrainingVideoModal videoKey={openKey} c={c} onClose={() => setOpenKey(null)} />}
      {newKey && <TrainingVideoModal videoKey={newKey} c={c} isNew defaultArea="user" onClose={() => setNewKey(null)} />}
    </div>
  );
}

Object.assign(window, {
  parseYouTubeId, ytThumb, TRAINING_VIDEOS_SEED, TrainingVideoModal, TrainingButton,
  useTrainingSnapshot, TrainingCard, TrainingPage,
});
