/* global React, Ico, Button, Label, Card, Avatar, BrandMark */
// NEXT XI · SuperAdmin Platform Dashboard

const { useState: useSA, useEffect: useEA } = React;

// ────────────────────────────────────────────────────────────
// SUPERADMIN PLATFORM SCREEN
// ────────────────────────────────────────────────────────────
const SuperAdminPlatformScreen = ({ lang, onToast, onSettings, profile }) => {
  const langKey = lang === 'ru' ? 'ru' : lang === 'en' ? 'en' : 'tr';
  const isTr = langKey === 'tr';
  const isRu = langKey === 'ru';
  const t = (tr, en, ru) => isRu ? (ru ?? tr) : isTr ? tr : (en ?? tr);

  const [view,             setView]             = useSA('list');
  const [selectedAcademy, setSelectedAcademy]  = useSA(null);
  const [academies,        setAcademies]        = useSA([]);
  const [allUsers,         setAllUsers]         = useSA([]);
  const [actionLoading,    setActionLoading]    = useSA('');
  const [filter,           setFilter]           = useSA('all');

  const [adminEmail,         setAdminEmail]         = useSA('');
  const [adminInviteLoading, setAdminInviteLoading] = useSA(false);
  const [adminInviteMsg,     setAdminInviteMsg]     = useSA(null); // { type: 'ok'|'err', text }

  useEA(() => {
    if (!window.NX) return;
    const unsubA = window.NX.onAllAcademies(
      setAcademies,
      e => console.error('[SA] academies:', e)
    );
    const unsubU = window.NX.onAllUsers(
      setAllUsers,
      e => console.error('[SA] users:', e)
    );
    return () => { unsubA(); unsubU(); };
  }, []);

  const usersFor = (academyId) => allUsers.filter(u => u.academyId === academyId);

  const openAcademy = (academy) => {
    setSelectedAcademy(academy);
    setView('academy');
    setAdminEmail('');
    setAdminInviteMsg(null);
  };

  // ── Status badge helper ───────────────────────────────────
  const StatusBadge = ({ status }) => {
    const cfg = {
      active:   { color: '#00FF88', bg: 'rgba(0,255,136,0.08)',   border: 'rgba(0,255,136,0.25)',  label: t('AKTİF','ACTIVE','АКТИВНА') },
      inactive: { color: '#FFB800', bg: 'rgba(255,184,0,0.08)',   border: 'rgba(255,184,0,0.25)',  label: t('PASİF','INACTIVE','НЕАКТИВНА') },
      archived: { color: '#7A7A7A', bg: 'rgba(122,122,122,0.08)', border: 'rgba(122,122,122,0.25)', label: t('ARŞİV','ARCHIVED','АРХИВ') },
    }[status] || { color: '#7A7A7A', bg: 'rgba(122,122,122,0.08)', border: 'rgba(122,122,122,0.25)', label: status?.toUpperCase() || '—' };
    return (
      <span style={{
        fontFamily: 'JetBrains Mono', fontSize: 9, letterSpacing: '0.10em',
        color: cfg.color, background: cfg.bg, border: `1px solid ${cfg.border}`,
        padding: '2px 7px', borderRadius: 999, display: 'inline-flex', alignItems: 'center', gap: 4,
      }}>
        ● {cfg.label}
      </span>
    );
  };

  // ── Actions ──────────────────────────────────────────────
  const handleSetStatus = async (academy, newStatus) => {
    const msgMap = {
      active:   t('Akademi aktifleştirildi', 'Academy activated', 'Академия активирована'),
      inactive: t('Akademi devre dışı bırakıldı', 'Academy deactivated', 'Академия деактивирована'),
      archived: t('Akademi arşivlendi', 'Academy archived', 'Академия архивирована'),
    };
    setActionLoading(`status:${academy.id}`);
    try {
      await window.NX.setAcademyStatus(academy.id, newStatus);
      setSelectedAcademy(prev => prev?.id === academy.id ? { ...prev, status: newStatus } : prev);
      onToast?.({ msg: msgMap[newStatus] || newStatus });
    } catch (e) {
      onToast?.({ msg: t('Hata oluştu', 'Error', 'Ошибка') + (e?.code ? `: ${e.code}` : '') });
    } finally { setActionLoading(''); }
  };

  const handleToggleStatus = (academy) => {
    const next = academy.status === 'active' ? 'inactive' : 'active';
    const question = next === 'active'
      ? (isTr ? `${academy.name} akademisini aktifleştir?`
              : isRu ? `Активировать академию ${academy.name}?`
              : `Activate academy ${academy.name}?`)
      : (isTr ? `${academy.name} akademisini devre dışı bırak?`
              : isRu ? `Деактивировать академию ${academy.name}?`
              : `Deactivate academy ${academy.name}?`);
    if (!window.confirm(question)) return;
    handleSetStatus(academy, next);
  };

  const handleArchive = (academy) => {
    const question = isTr
      ? `${academy.name} arşivlensin mi? Bu işlem geri alınabilir.`
      : isRu
      ? `Архивировать ${academy.name}? Это действие можно отменить.`
      : `Archive ${academy.name}? This can be undone.`;
    if (!window.confirm(question)) return;
    handleSetStatus(academy, 'archived');
  };

  const handleDeleteAcademy = async (academy) => {
    const question = isTr
      ? `${academy.name} AKADEMİSİNİ SİL? Bu işlem geri alınamaz!`
      : isRu
      ? `УДАЛИТЬ академию ${academy.name}? Это действие необратимо!`
      : `DELETE academy ${academy.name}? This cannot be undone!`;
    if (!window.confirm(question)) return;
    setActionLoading(`delete:${academy.id}`);
    try {
      await window.NX.deleteAcademy(academy.id);
      onToast?.({ msg: t('Akademi silindi', 'Academy deleted', 'Академия удалена') });
      setView('list');
      setSelectedAcademy(null);
    } catch (e) {
      onToast?.({ msg: t('Hata oluştu', 'Error', 'Ошибка') + (e?.code ? `: ${e.code}` : '') });
    } finally { setActionLoading(''); }
  };

  const handleRegenCode = async (academy) => {
    setActionLoading(`code:${academy.id}`);
    try {
      const newCode = await window.NX.generateAndSaveAcademyCode(academy.id);
      setSelectedAcademy(prev => prev?.id === academy.id ? { ...prev, academyCode: newCode } : prev);
      onToast?.({ msg: t('Yeni kod oluşturuldu', 'New code generated', 'Новый код создан'), code: newCode });
    } catch (e) {
      onToast?.({ msg: t('Hata oluştu', 'Error', 'Ошибка') + (e?.code ? `: ${e.code}` : '') });
    } finally { setActionLoading(''); }
  };

  const handleSportType = async (academy, newType) => {
    if (academy.sportType === newType) return;
    setActionLoading(`sport:${academy.id}`);
    try {
      await window.NX.updateAcademy(academy.id, { sportType: newType });
      setSelectedAcademy(prev => prev?.id === academy.id ? { ...prev, sportType: newType } : prev);
      onToast?.({ msg: t('Spor türü güncellendi', 'Sport type updated', 'Вид спорта обновлён') });
    } catch (e) {
      onToast?.({ msg: t('Hata oluştu', 'Error', 'Ошибка') + (e?.code ? `: ${e.code}` : '') });
    } finally { setActionLoading(''); }
  };

  const handleRemoveAdmin = async (user) => {
    const confirmed = window.confirm(
      isTr ? `${user.displayName || user.email} yönetici erişimini kaldır?`
           : isRu ? `Убрать права администратора у ${user.displayName || user.email}?`
           : `Remove admin access for ${user.displayName || user.email}?`
    );
    if (!confirmed) return;
    setActionLoading(`removeAdmin:${user.uid}`);
    try {
      await window.NX.updateUserProfile(user.uid, {
        academyId:   null,
        academyRole: null,
        status:      'pending',
      });
      onToast?.({ msg: t('Yönetici erişimi kaldırıldı', 'Admin access removed', 'Доступ администратора удалён') });
    } catch (e) {
      onToast?.({ msg: t('Hata oluştu', 'Error', 'Ошибка') + (e?.code ? `: ${e.code}` : '') });
    } finally { setActionLoading(''); }
  };

  const handleInviteAdmin = async (academy) => {
    const email = adminEmail.trim().toLowerCase();
    if (!email) return;
    setAdminInviteLoading(true);
    setAdminInviteMsg(null);
    try {
      const existing = await window.NX.getUserByEmail(email);
      if (existing) {
        await window.NX.updateUserProfile(existing.uid, {
          role:        'admin',
          academyRole: 'admin',
          academyId:   academy.id,
          academyName: academy.name,
          sportType:   academy.sportType,
          status:      'approved',
        });
        setAdminInviteMsg({ type: 'ok', text: t(`${email} yönetici yapıldı`, `${email} is now an admin`, `${email} теперь администратор`) });
      } else {
        await window.NX.createAdminInvite({
          email,
          academyId:   academy.id,
          academyName: academy.name,
          invitedBy:   profile.uid,
        });
        setAdminInviteMsg({ type: 'ok', text: t(`${email} için davet oluşturuldu`, `Invite created for ${email}`, `Приглашение создано для ${email}`) });
      }
      setAdminEmail('');
    } catch (e) {
      setAdminInviteMsg({ type: 'err', text: t('İşlem başarısız', 'Operation failed', 'Ошибка операции') + (e?.code ? `: ${e.code}` : '') });
    } finally { setAdminInviteLoading(false); }
  };

  // ── UserRow sub-component ─────────────────────────────────
  const UserRow = ({ user, canRemove }) => {
    const ini = (user.displayName || user.email || '?').split(' ').map(s => s[0]).join('').slice(0, 2).toUpperCase();
    const isOwner   = user.academyRole === 'owner';
    const isAdmin   = user.academyRole === 'admin';
    const isPending = user.status === 'pending';
    const isLoading = actionLoading === `removeAdmin:${user.uid}`;

    const roleLabelMap = {
      admin:  { label: 'ADMIN', color: '#B26BFF' },
      coach:  { label: isTr ? 'KOÇ' : isRu ? 'ТРЕНЕР' : 'COACH', color: '#FFB800' },
      player: { label: isTr ? 'SPORCU' : isRu ? 'СПОРТСМЕН' : 'PLAYER', color: '#00FF88' },
      parent: { label: isTr ? 'VELİ' : isRu ? 'РОДИТЕЛЬ' : 'PARENT', color: '#4F8DFF' },
    };
    const roleInfo = roleLabelMap[user.role];

    return (
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 0',
        borderBottom:'1px solid rgba(255,255,255,0.04)' }}>
        <Avatar initials={ini} size={30} avatarId={user.role === 'coach' ? 'coach' : user.avatarId}/>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:'flex', alignItems:'center', gap:5, flexWrap:'wrap' }}>
            <span style={{ fontFamily:'Manrope', fontWeight:700, fontSize:12, color:'#fff',
              overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', maxWidth:120 }}>
              {user.displayName || '—'}
            </span>
            {roleInfo && (
              <span style={{ fontFamily:'JetBrains Mono', fontSize:8,
                color: roleInfo.color, letterSpacing:'0.10em', flexShrink:0 }}>
                {roleInfo.label}
              </span>
            )}
            {isOwner && (
              <span style={{ fontFamily:'JetBrains Mono', fontSize:8, color:'#FFB800',
                letterSpacing:'0.10em', flexShrink:0 }}>OWNER</span>
            )}
            {!isOwner && isAdmin && (
              <span style={{ fontFamily:'JetBrains Mono', fontSize:8, color:'#B26BFF',
                letterSpacing:'0.10em', flexShrink:0 }}>ADMIN</span>
            )}
            {isPending && (
              <span style={{ fontFamily:'JetBrains Mono', fontSize:8, color:'#4F8DFF',
                letterSpacing:'0.10em', flexShrink:0 }}>PENDING</span>
            )}
          </div>
          <div style={{ fontFamily:'Manrope', fontSize:10, color:'#7A7A7A',
            overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
            {user.email || '—'}
          </div>
        </div>
        {canRemove && !isOwner && (
          <button disabled={isLoading} onClick={() => handleRemoveAdmin(user)} style={{
            padding:'5px 8px', borderRadius:7, cursor: isLoading ? 'not-allowed' : 'pointer',
            background:'rgba(255,77,77,0.06)', border:'1px solid rgba(255,77,77,0.24)',
            color:'#FF6B6B', fontFamily:'Manrope', fontWeight:700, fontSize:10,
            opacity: isLoading ? 0.4 : 1, flexShrink:0 }}>
            {isLoading ? '…' : t('Kaldır', 'Remove', 'Убрать')}
          </button>
        )}
      </div>
    );
  };

  // ── UserGroup section ─────────────────────────────────────
  const UserGroup = ({ title, users, canRemove }) => {
    if (users.length === 0) return null;
    return (
      <Card style={{ padding:12 }}>
        <Label style={{ display:'block', marginBottom:8 }}>{title} ({users.length})</Label>
        {users.map(u => <UserRow key={u.uid} user={u} canRemove={!!canRemove}/>)}
      </Card>
    );
  };

  // ── Overview stats ────────────────────────────────────────
  const totalAcademies  = academies.length;
  const activeAcademies = academies.filter(a => a.status === 'active').length;
  const pendingAdmins   = allUsers.filter(u => u.role === 'admin' && u.status === 'pending').length;
  const totalUsers      = allUsers.length;

  // ── Filter logic ──────────────────────────────────────────
  const filterTabs = [
    { id: 'all',      label: t('Tümü','All','Все') },
    { id: 'active',   label: t('Aktif','Active','Активные') },
    { id: 'inactive', label: t('Pasif','Inactive','Неактивные') },
    { id: 'archived', label: t('Arşiv','Archived','Архив') },
    { id: 'football', label: t('Futbol','Football','Футбол') },
    { id: 'swimming', label: t('Yüzme','Swimming','Плавание') },
  ];
  const filteredAcademies = academies.filter(a => {
    if (filter === 'all')      return a.status !== 'archived';
    if (filter === 'active')   return a.status === 'active';
    if (filter === 'inactive') return a.status === 'inactive';
    if (filter === 'archived') return a.status === 'archived';
    if (filter === 'football') return a.sportType === 'football' && a.status !== 'archived';
    if (filter === 'swimming') return a.sportType === 'swimming' && a.status !== 'archived';
    return true;
  });

  // ── LIST VIEW ─────────────────────────────────────────────
  if (view === 'list') {
    return (
      <div style={{ display:'flex', flexDirection:'column', height:'100%',
        background:'#0B0B0B', overflowY:'auto' }}>

        {/* Header */}
        <div style={{ padding:'68px 20px 14px', borderBottom:'1px solid rgba(255,255,255,0.06)' }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:4 }}>
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <BrandMark size={26}/>
              <span style={{ fontFamily:'Manrope', fontWeight:800, fontSize:11,
                letterSpacing:'0.18em', textTransform:'uppercase', color:'#fff' }}>ATHLORYX</span>
              <span style={{ fontFamily:'JetBrains Mono', fontSize:10, color:'#FF5C2E',
                padding:'2px 7px', borderRadius:999,
                border:'1px solid rgba(255,92,46,0.30)', background:'rgba(255,92,46,0.08)' }}>
                PLATFORM
              </span>
            </div>
            {onSettings && (
              <button onClick={onSettings} style={{ width:32, height:32, borderRadius:999, cursor:'pointer',
                background:'#1C1C1C', border:'1px solid rgba(255,255,255,0.06)', color:'#fff',
                display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Ico name="cog" size={16}/>
              </button>
            )}
          </div>
          <h1 style={{ fontFamily:'Oswald', fontWeight:700, fontSize:24, lineHeight:1.0,
            textTransform:'uppercase', letterSpacing:'0.02em', color:'#fff', margin:'6px 0 14px' }}>
            {t('Platform Yönetimi', 'Platform Admin', 'Управление платформой')}
          </h1>

          {/* Overview cards */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
            {[
              [totalAcademies,  t('Toplam Akademi', 'Total Academies', 'Всего академий'),     '#FF5C2E'],
              [activeAcademies, t('Aktif',           'Active',           'Активных'),           '#00FF88'],
              [pendingAdmins,   t('Bekleyen Admin',  'Pending Admins',   'Ожидающих'),          '#FFB800'],
              [totalUsers,      t('Toplam Kullanıcı','Total Users',      'Всего пользователей'),'#4F8DFF'],
            ].map(([n, l, c]) => (
              <div key={l} style={{ padding:'12px 14px', borderRadius:12,
                background:`${c}08`, border:`1px solid ${c}20` }}>
                <div style={{ fontFamily:'Oswald', fontWeight:700, fontSize:28, color:c, lineHeight:1 }}>{n}</div>
                <div style={{ fontFamily:'Manrope', fontWeight:700, fontSize:9,
                  letterSpacing:'0.12em', textTransform:'uppercase', color:'#7A7A7A', marginTop:4 }}>{l}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Filter bar */}
        <div style={{ padding:'10px 16px 0', borderBottom:'1px solid rgba(255,255,255,0.06)',
          display:'flex', gap:6, overflowX:'auto', paddingBottom:10 }}>
          {filterTabs.map(tab => {
            const active = filter === tab.id;
            return (
              <button key={tab.id} onClick={() => setFilter(tab.id)} style={{
                padding:'5px 12px', borderRadius:999, cursor:'pointer', flexShrink:0,
                fontFamily:'Manrope', fontWeight:700, fontSize:11,
                background: active ? 'rgba(255,255,255,0.10)' : 'transparent',
                border: active ? '1px solid rgba(255,255,255,0.18)' : '1px solid rgba(255,255,255,0.06)',
                color: active ? '#fff' : '#7A7A7A',
              }}>
                {tab.label}
              </button>
            );
          })}
        </div>

        {/* Academy list */}
        <div style={{ flex:1, padding:'12px 16px', display:'flex', flexDirection:'column', gap:10 }}>
          <Label>
            {t('Akademiler', 'Academies', 'Академии')}
            {' '}
            <span style={{ color:'#4A4A4A', fontWeight:400 }}>({filteredAcademies.length})</span>
          </Label>
          {filteredAcademies.length === 0 ? (
            <div style={{ textAlign:'center', padding:'40px 0',
              fontFamily:'Manrope', fontSize:13, color:'#5A5A5A' }}>
              {t('Bu filtrede akademi yok.', 'No academies match this filter.', 'Нет академий по этому фильтру.')}
            </div>
          ) : filteredAcademies.map(academy => {
            const users   = usersFor(academy.id);
            const admins  = users.filter(u => u.role === 'admin'  && u.status === 'approved');
            const coaches = users.filter(u => u.role === 'coach'  && u.status === 'approved');
            const players = users.filter(u => u.role === 'player' && u.status === 'approved');
            const parents = users.filter(u => u.role === 'parent' && u.status === 'approved');
            const pending = users.filter(u => u.status === 'pending');
            const owner   = users.find(u => u.academyRole === 'owner');
            const isSwim  = academy.sportType === 'swimming';
            const ownerStr = owner ? (owner.displayName || owner.email) : (admins[0]?.displayName || admins[0]?.email || '—');
            return (
              <button key={academy.id} onClick={() => openAcademy(academy)} style={{
                textAlign:'left', width:'100%', padding:14, borderRadius:14, cursor:'pointer',
                background: academy.status === 'archived' ? '#111' : '#141414',
                border:'1px solid rgba(255,255,255,0.06)',
                opacity: academy.status === 'archived' ? 0.6 : 1 }}>
                <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:10 }}>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                      <span style={{ fontFamily:'Oswald', fontWeight:700, fontSize:16,
                        textTransform:'uppercase', letterSpacing:'0.02em', color:'#fff' }}>
                        {academy.name}
                      </span>
                      <span style={{ fontFamily:'JetBrains Mono', fontSize:9,
                        color: isSwim ? '#38E8FF' : '#00FF88', padding:'2px 6px', borderRadius:999,
                        border:`1px solid ${isSwim ? '#38E8FF40' : '#00FF8840'}`,
                        background:`${isSwim ? '#38E8FF' : '#00FF88'}10` }}>
                        {isSwim ? t('YÜZME','SWIM','ПЛАВАНИЕ') : t('FUTBOL','FOOTBALL','ФУТБОЛ')}
                      </span>
                    </div>
                    <div style={{ fontFamily:'Manrope', fontSize:11, color:'#7A7A7A', marginTop:3 }}>
                      {t('Sahip:','Owner:','Владелец:')} <span style={{ color:'#B8B8B8' }}>{ownerStr}</span>
                    </div>
                    <div style={{ fontFamily:'JetBrains Mono', fontSize:10, color:'#4A4A4A', marginTop:2 }}>
                      {academy.academyCode}
                    </div>
                  </div>
                  <StatusBadge status={academy.status}/>
                </div>
                <div style={{ display:'flex', gap:6, marginTop:10, flexWrap:'wrap' }}>
                  {[
                    [admins.length,  t('Admin','Admin','Адм'),        '#B26BFF'],
                    [coaches.length, t('Koç','Coach','Тренер'),        '#FFB800'],
                    [players.length, t('Sporcu','Player','Спортсмен'), '#00FF88'],
                    [parents.length, t('Veli','Parent','Родитель'),    '#4F8DFF'],
                    ...(pending.length > 0 ? [[pending.length, t('Bekleyen','Pending','Ожидают'), '#FF5C2E']] : []),
                  ].map(([n, l, c]) => (
                    <span key={l} style={{ fontFamily:'Manrope', fontWeight:700, fontSize:10,
                      padding:'3px 8px', borderRadius:999,
                      background:`${c}10`, border:`1px solid ${c}25`, color:c }}>
                      {n} {l}
                    </span>
                  ))}
                </div>
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  // ── ACADEMY DETAIL VIEW ───────────────────────────────────
  const acad = selectedAcademy;
  if (!acad) { setView('list'); return null; }

  const acadUsers   = usersFor(acad.id);
  const acadAdmins  = acadUsers.filter(u => u.role === 'admin'  && u.status === 'approved');
  const acadCoaches = acadUsers.filter(u => u.role === 'coach'  && u.status === 'approved');
  const acadPlayers = acadUsers.filter(u => u.role === 'player' && u.status === 'approved');
  const acadParents = acadUsers.filter(u => u.role === 'parent' && u.status === 'approved');
  const acadPending = acadUsers.filter(u => u.status === 'pending');
  const totalMembers = acadUsers.length;
  const isSwim       = acad.sportType === 'swimming';
  const isArchived   = acad.status === 'archived';
  const isActive     = acad.status === 'active';

  return (
    <div style={{ display:'flex', flexDirection:'column', height:'100%',
      background:'#0B0B0B', overflowY:'auto' }}>

      {/* Back header */}
      <div style={{ padding:'68px 20px 14px', borderBottom:'1px solid rgba(255,255,255,0.06)' }}>
        <button onClick={() => setView('list')} style={{
          display:'flex', alignItems:'center', gap:8,
          background:'none', border:'none', padding:0, cursor:'pointer', marginBottom:10 }}>
          <Ico name="chev" size={16} style={{ color:'#7A7A7A', transform:'scaleX(-1)' }}/>
          <span style={{ fontFamily:'Manrope', fontWeight:700, fontSize:12,
            color:'#7A7A7A', letterSpacing:'0.08em' }}>
            {t('← Akademiler', '← Academies', '← Академии')}
          </span>
        </button>
        <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:10 }}>
          <div>
            <h1 style={{ fontFamily:'Oswald', fontWeight:700, fontSize:22,
              textTransform:'uppercase', letterSpacing:'0.02em', color:'#fff', margin:0 }}>
              {acad.name}
            </h1>
            <div style={{ display:'flex', gap:8, marginTop:6, flexWrap:'wrap', alignItems:'center' }}>
              <StatusBadge status={acad.status}/>
              <span style={{ fontFamily:'JetBrains Mono', fontSize:9,
                color: isSwim ? '#38E8FF' : '#00FF88', padding:'2px 6px', borderRadius:999,
                border:`1px solid ${isSwim ? '#38E8FF40' : '#00FF8840'}`,
                background:`${isSwim ? '#38E8FF' : '#00FF88'}10` }}>
                {isSwim ? t('Yüzme','Swimming','Плавание') : t('Futbol','Football','Футбол')}
              </span>
              <span style={{ fontFamily:'Manrope', fontSize:10, color:'#5A5A5A' }}>
                {totalMembers} {t('üye', 'members', 'участников')}
              </span>
            </div>
          </div>
        </div>
      </div>

      <div style={{ flex:1, padding:'12px 16px', display:'flex', flexDirection:'column', gap:12 }}>

        {/* Registration code */}
        <Card style={{ padding:12 }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:10 }}>
            <div>
              <Label>{t('Kayıt Kodu','Registration Code','Код регистрации')}</Label>
              <div style={{ fontFamily:'JetBrains Mono', fontWeight:700, fontSize:18,
                color:'var(--nx-accent)', marginTop:4, letterSpacing:'0.08em' }}>
                {acad.academyCode}
              </div>
            </div>
            <button disabled={!!actionLoading} onClick={() => handleRegenCode(acad)} style={{
              padding:'7px 12px', borderRadius:9, cursor: actionLoading ? 'not-allowed' : 'pointer',
              background:'var(--nx-accent-soft)', border:'1px solid var(--nx-accent-glow)',
              color:'var(--nx-accent)', fontFamily:'Manrope', fontWeight:700, fontSize:11,
              opacity: actionLoading === `code:${acad.id}` ? 0.5 : 1 }}>
              {actionLoading === `code:${acad.id}` ? '…' : t('Yenile','Regen','Обновить')}
            </button>
          </div>
        </Card>

        {/* Sport type */}
        <Card style={{ padding:12 }}>
          <Label style={{ display:'block', marginBottom:8 }}>
            {t('Spor Türü','Sport Type','Вид спорта')}
          </Label>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
            {[
              ['football', t('Futbol','Football','Футбол'), '#00FF88'],
              ['swimming', t('Yüzme','Swimming','Плавание'), '#38E8FF'],
            ].map(([type, label, color]) => {
              const on = acad.sportType === type;
              return (
                <button key={type} disabled={!!actionLoading} onClick={() => handleSportType(acad, type)} style={{
                  padding:'9px 10px', borderRadius:9, cursor: actionLoading ? 'not-allowed' : 'pointer',
                  background: on ? `${color}10` : '#1C1C1C',
                  border:`1px solid ${on ? `${color}55` : 'rgba(255,255,255,0.06)'}`,
                  color: on ? color : '#7A7A7A',
                  fontFamily:'Manrope', fontWeight:700, fontSize:12,
                  opacity: actionLoading && !on ? 0.5 : 1 }}>
                  {label}
                </button>
              );
            })}
          </div>
        </Card>

        {/* Status controls — not shown for archived academies */}
        {!isArchived && (
          <button disabled={actionLoading === `status:${acad.id}`} onClick={() => handleToggleStatus(acad)}
            style={{ padding:'11px', borderRadius:11, cursor:'pointer', width:'100%',
              background: isActive ? 'rgba(255,184,0,0.06)' : 'rgba(0,255,136,0.08)',
              border:`1px solid ${isActive ? 'rgba(255,184,0,0.25)' : 'rgba(0,255,136,0.30)'}`,
              color: isActive ? '#FFB800' : '#00FF88',
              fontFamily:'Manrope', fontWeight:700, fontSize:12,
              letterSpacing:'0.08em', textTransform:'uppercase',
              opacity: actionLoading === `status:${acad.id}` ? 0.5 : 1 }}>
            {actionLoading === `status:${acad.id}` ? '…' :
              isActive
                ? t('Akademiyi Devre Dışı Bırak','Deactivate Academy','Деактивировать академию')
                : t('Akademiyi Aktifleştir','Activate Academy','Активировать академию')}
          </button>
        )}

        {/* Archive / Delete zone — only for inactive/archived, never if has users when deleting */}
        {(acad.status === 'inactive' || acad.status === 'archived') && (
          <Card style={{ padding:12, background:'rgba(255,77,77,0.04)', border:'1px solid rgba(255,77,77,0.12)' }}>
            <div style={{ fontFamily:'JetBrains Mono', fontSize:9, color:'#FF6B6B',
              letterSpacing:'0.14em', textTransform:'uppercase', marginBottom:10 }}>
              {t('Tehlikeli Bölge', 'Danger Zone', 'Опасная зона')}
            </div>
            {!isArchived && (
              <button disabled={!!actionLoading} onClick={() => handleArchive(acad)} style={{
                width:'100%', padding:'9px', borderRadius:9, cursor: actionLoading ? 'not-allowed' : 'pointer',
                background:'rgba(122,122,122,0.08)', border:'1px solid rgba(122,122,122,0.25)',
                color:'#9A9A9A', fontFamily:'Manrope', fontWeight:700, fontSize:11,
                letterSpacing:'0.06em', textTransform:'uppercase', marginBottom:8,
                opacity: actionLoading === `status:${acad.id}` ? 0.4 : 1 }}>
                {actionLoading === `status:${acad.id}` ? '…' : t('Arşivle','Archive','Архивировать')}
              </button>
            )}
            {isArchived && (
              <button disabled={!!actionLoading} onClick={() => handleSetStatus(acad, 'inactive')} style={{
                width:'100%', padding:'9px', borderRadius:9, cursor: actionLoading ? 'not-allowed' : 'pointer',
                background:'rgba(255,184,0,0.06)', border:'1px solid rgba(255,184,0,0.20)',
                color:'#FFB800', fontFamily:'Manrope', fontWeight:700, fontSize:11,
                letterSpacing:'0.06em', textTransform:'uppercase', marginBottom:8,
                opacity: actionLoading === `status:${acad.id}` ? 0.4 : 1 }}>
                {actionLoading === `status:${acad.id}` ? '…' : t('Arşivden Çıkar','Unarchive','Из архива')}
              </button>
            )}
            {totalMembers > 0 ? (
              <div style={{ padding:'9px 12px', borderRadius:9,
                background:'rgba(255,77,77,0.06)', border:'1px solid rgba(255,77,77,0.18)',
                fontFamily:'Manrope', fontSize:11, color:'#FF9A9A', lineHeight:1.5 }}>
                {t(
                  `Bu akademide ${totalMembers} üye var. Silmek için önce üyeleri kaldırın.`,
                  `This academy has ${totalMembers} members. Remove all members before deleting.`,
                  `В академии ${totalMembers} участников. Удалите их перед удалением академии.`
                )}
              </div>
            ) : (
              <button disabled={!!actionLoading} onClick={() => handleDeleteAcademy(acad)} style={{
                width:'100%', padding:'9px', borderRadius:9, cursor: actionLoading ? 'not-allowed' : 'pointer',
                background:'rgba(255,77,77,0.08)', border:'1px solid rgba(255,77,77,0.30)',
                color:'#FF6B6B', fontFamily:'Manrope', fontWeight:700, fontSize:11,
                letterSpacing:'0.06em', textTransform:'uppercase',
                opacity: actionLoading === `delete:${acad.id}` ? 0.4 : 1 }}>
                {actionLoading === `delete:${acad.id}` ? '…' : t('Akademiyi Sil','Delete Academy','Удалить академию')}
              </button>
            )}
          </Card>
        )}

        {/* Admins section */}
        <Card style={{ padding:12 }}>
          <Label style={{ display:'block', marginBottom:8 }}>
            {t('Yöneticiler','Admins','Администраторы')} ({acadAdmins.length})
          </Label>
          {acadAdmins.length === 0 ? (
            <div style={{ fontFamily:'Manrope', fontSize:12, color:'#5A5A5A' }}>
              {t('Yönetici yok.','No admins.','Нет администраторов.')}
            </div>
          ) : acadAdmins.map(u => <UserRow key={u.uid} user={u} canRemove={true}/>)}

          {/* Invite */}
          <div style={{ marginTop:12, paddingTop:12, borderTop:'1px solid rgba(255,255,255,0.06)' }}>
            <div style={{ fontFamily:'JetBrains Mono', fontSize:9, color:'#B26BFF',
              letterSpacing:'0.14em', textTransform:'uppercase', marginBottom:8 }}>
              {t('→ Admin Davet Et','→ Invite Admin','→ Пригласить администратора')}
            </div>
            <div style={{ display:'flex', gap:8 }}>
              <input value={adminEmail}
                onChange={e => { setAdminEmail(e.target.value); setAdminInviteMsg(null); }}
                placeholder={t('E-posta adresi','Email address','Эл. почта')}
                style={{ flex:1, background:'#0B0B0B',
                  border:'1px solid rgba(178,107,255,0.25)', borderRadius:9,
                  padding:'9px 12px', fontFamily:'Manrope', fontSize:13,
                  color:'#fff', outline:'none' }}/>
              <button disabled={!adminEmail.trim() || adminInviteLoading}
                onClick={() => handleInviteAdmin(acad)} style={{
                  padding:'9px 12px', borderRadius:9,
                  cursor: (!adminEmail.trim() || adminInviteLoading) ? 'not-allowed' : 'pointer',
                  background:'rgba(178,107,255,0.12)', border:'1px solid rgba(178,107,255,0.40)',
                  color:'#B26BFF', fontFamily:'Manrope', fontWeight:700, fontSize:12,
                  opacity: (!adminEmail.trim() || adminInviteLoading) ? 0.4 : 1 }}>
                {adminInviteLoading ? '…' : t('Davet Et','Invite','Пригласить')}
              </button>
            </div>
            {adminInviteMsg && (
              <div style={{ marginTop:8, padding:'7px 10px', borderRadius:8,
                background: adminInviteMsg.type === 'ok' ? 'rgba(0,255,136,0.08)' : 'rgba(255,77,77,0.08)',
                border:`1px solid ${adminInviteMsg.type === 'ok' ? 'rgba(0,255,136,0.24)' : 'rgba(255,77,77,0.24)'}`,
                color: adminInviteMsg.type === 'ok' ? '#00FF88' : '#FF6B6B',
                fontFamily:'Manrope', fontSize:11 }}>
                {adminInviteMsg.text}
              </div>
            )}
          </div>
        </Card>

        {/* Grouped member sections */}
        <UserGroup
          title={isSwim ? t('Eğitmenler','Instructors','Инструкторы') : t('Koçlar','Coaches','Тренеры')}
          users={acadCoaches}
          canRemove={false}/>

        <UserGroup
          title={isSwim ? t('Yüzücüler','Swimmers','Пловцы') : t('Sporcular','Players','Спортсмены')}
          users={acadPlayers}
          canRemove={false}/>

        <UserGroup
          title={t('Veliler','Parents','Родители')}
          users={acadParents}
          canRemove={false}/>

        <UserGroup
          title={t('Bekleyen Onaylar','Pending Approvals','Ожидают одобрения')}
          users={acadPending}
          canRemove={false}/>

        {acadAdmins.length === 0 && acadCoaches.length === 0 && acadPlayers.length === 0 &&
          acadParents.length === 0 && acadPending.length === 0 && (
          <div style={{ textAlign:'center', padding:'24px 0',
            fontFamily:'Manrope', fontSize:13, color:'#5A5A5A' }}>
            {t('Bu akademide henüz üye yok.','No members yet.','В этой академии пока нет участников.')}
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { SuperAdminPlatformScreen });
