// Auth screens: Login/Register, Tournament List, Share Modal.
const { useState: uSt, useEffect: uEf } = React;

// ── Loading screen ────────────────────────────────────────────
function LoadingScreen() {
  return (
    <div style={{
      minHeight: '100vh', display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center', background: 'var(--bg)', gap: 16,
    }}>
      <div style={{ fontFamily: 'var(--display)', fontSize: 32, letterSpacing: '.1em', color: 'var(--gold)' }}>EL BARRIO</div>
      <div style={{ width: 36, height: 36, border: '3px solid var(--border-2)', borderTopColor: 'var(--accent)', borderRadius: '50%', animation: 'spin .8s linear infinite' }}/>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

// ── Auth screen ───────────────────────────────────────────────
function AuthScreen({ onAuth }) {
  const [mode, setMode] = uSt('login');
  const [email, setEmail] = uSt('');
  const [password, setPassword] = uSt('');
  const [name, setName] = uSt('');
  const [loading, setLoading] = uSt(false);
  const [error, setError] = uSt('');
  const [info, setInfo] = uSt('');

  function reset() { setError(''); setInfo(''); }

  async function submit(e) {
    e.preventDefault();
    reset(); setLoading(true);
    try {
      if (mode === 'forgot') {
        const { error: err } = await window.Auth.resetPassword(email);
        if (err) throw err;
        setInfo('Revisa tu correo para restablecer la contraseña.');
        setLoading(false); return;
      }
      if (mode === 'register') {
        if (!name.trim()) { setError('Escribe tu nombre'); setLoading(false); return; }
        const { data, error: err } = await window.Auth.signUp(email, password, name.trim());
        if (err) throw err;
        if (data.user && !data.session) {
          setInfo('Revisa tu correo para confirmar tu cuenta antes de entrar.');
          setLoading(false); return;
        }
        onAuth(data.user);
      } else {
        const { data, error: err } = await window.Auth.signIn(email, password);
        if (err) throw err;
        onAuth(data.user);
      }
    } catch (err) { setError(err.message || 'Error desconocido'); }
    setLoading(false);
  }

  return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--bg)',
      backgroundImage: 'radial-gradient(ellipse at 30% 20%, rgba(76,127,255,.08) 0%, transparent 55%), radial-gradient(ellipse at 70% 80%, rgba(245,200,66,.06) 0%, transparent 50%)',
    }}>
      <div style={{ width: '100%', maxWidth: 420, padding: '0 16px' }}>
        {/* Logo */}
        <div style={{ textAlign: 'center', marginBottom: 36 }}>
          <div style={{ fontSize: 48, marginBottom: 8 }}>🏆</div>
          <div style={{ fontFamily: 'var(--display)', fontSize: 34, letterSpacing: '.1em', color: 'var(--gold)' }}>EL BARRIO</div>
          <div style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '.22em', textTransform: 'uppercase', marginTop: 4 }}>Gestor de Torneos</div>
        </div>

        {/* Card */}
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 'var(--r-lg)', padding: '28px 24px',
          boxShadow: '0 24px 64px rgba(0,0,0,.6)',
        }}>
          {/* Tab switcher */}
          {mode !== 'forgot' && (
            <div style={{ display: 'flex', background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', padding: 3, marginBottom: 22 }}>
              {[['login','Iniciar sesión'], ['register','Registrarse']].map(([m, label]) => (
                <button key={m} onClick={() => { setMode(m); reset(); }}
                  style={{
                    flex: 1, padding: '8px 0', borderRadius: 'calc(var(--r-sm) - 2px)',
                    background: mode === m ? 'var(--accent)' : 'transparent',
                    color: mode === m ? 'white' : 'var(--muted)',
                    border: 'none', cursor: 'pointer',
                    fontFamily: 'var(--ui)', fontWeight: 600, fontSize: 13,
                    transition: 'all .15s',
                  }}>{label}</button>
              ))}
            </div>
          )}
          {mode === 'forgot' && (
            <div style={{ marginBottom: 20 }}>
              <button onClick={() => { setMode('login'); reset(); }}
                style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 12, padding: 0 }}>
                ← Volver
              </button>
              <div style={{ fontFamily: 'var(--display)', fontSize: 20, letterSpacing: '.04em', marginTop: 8 }}>RECUPERAR CONTRASEÑA</div>
            </div>
          )}

          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {mode === 'register' && (
              <div className="field">
                <label>Nombre</label>
                <input className="input" type="text" placeholder="Tu nombre" required
                  value={name} onChange={e => setName(e.target.value)} autoFocus/>
              </div>
            )}
            <div className="field">
              <label>Correo electrónico</label>
              <input className="input" type="email" placeholder="correo@ejemplo.com" required
                value={email} onChange={e => setEmail(e.target.value)} autoFocus={mode !== 'register'}/>
            </div>
            {mode !== 'forgot' && (
              <div className="field">
                <label style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span>Contraseña</span>
                  {mode === 'login' && (
                    <button type="button" onClick={() => { setMode('forgot'); reset(); }}
                      style={{ background: 'none', border: 'none', color: 'var(--accent)', cursor: 'pointer', fontSize: 11, padding: 0, fontWeight: 600 }}>
                      ¿Olvidaste la contraseña?
                    </button>
                  )}
                </label>
                <input className="input" type="password"
                  placeholder={mode === 'register' ? 'Mínimo 6 caracteres' : '••••••••'}
                  required minLength={6} value={password} onChange={e => setPassword(e.target.value)}/>
              </div>
            )}

            {error && (
              <div style={{ background: 'rgba(255,71,87,.12)', border: '1px solid rgba(255,71,87,.3)', borderRadius: 'var(--r-sm)', padding: '10px 14px', fontSize: 12.5, color: '#ff6b78' }}>
                {error}
              </div>
            )}
            {info && (
              <div style={{ background: 'rgba(34,197,94,.1)', border: '1px solid rgba(34,197,94,.3)', borderRadius: 'var(--r-sm)', padding: '10px 14px', fontSize: 12.5, color: 'var(--green)' }}>
                ✓ {info}
              </div>
            )}

            <button className="btn btn-primary" type="submit" disabled={loading}
              style={{ marginTop: 4, padding: '12px', fontSize: 14, fontWeight: 700, letterSpacing: '.04em' }}>
              {loading ? '⏳ Procesando...' : mode === 'login' ? '→ Entrar' : mode === 'register' ? '→ Crear cuenta' : '→ Enviar correo'}
            </button>
          </form>
        </div>
        <div style={{ textAlign: 'center', marginTop: 18, fontSize: 11, color: 'var(--muted)' }}>elbarrio.pro</div>
      </div>
    </div>
  );
}

// ── Tournament card ───────────────────────────────────────────
function TournamentCard({ tournament, role, onOpen, onDelete, confirmDelete }) {
  const roleColor = { owner: 'var(--gold)', editor: 'var(--accent)', viewer: 'var(--muted)' }[role] || 'var(--muted)';
  const roleLabel = { owner: 'Admin', editor: 'Editor', viewer: 'Lector' }[role] || role;
  const dateStr = new Date(tournament.updated_at).toLocaleDateString('es', { day: 'numeric', month: 'short', year: 'numeric' });

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14,
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 'var(--r)', padding: '14px 16px',
      cursor: 'pointer', transition: 'border-color .15s, box-shadow .15s',
    }}
      onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--border-2)'; e.currentTarget.style.boxShadow = 'var(--shadow-sm)'; }}
      onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.boxShadow = 'none'; }}
      onClick={onOpen}>
      <div style={{
        width: 44, height: 44, borderRadius: 'var(--r-sm)', flexShrink: 0,
        background: 'var(--accent-gradient)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
      }}>🏆</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 14.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {tournament.name}
        </div>
        <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>Actualizado {dateStr}</div>
      </div>
      <span style={{
        fontSize: 10, fontWeight: 800, letterSpacing: '.1em', textTransform: 'uppercase',
        color: roleColor, background: `${roleColor}18`, padding: '3px 10px', borderRadius: 20,
        fontFamily: 'var(--ui-cond)', flexShrink: 0,
      }}>{roleLabel}</span>
      <button className="btn btn-sm" onClick={e => { e.stopPropagation(); onOpen(); }}
        style={{ fontSize: 12, flexShrink: 0 }}>Abrir →</button>
      {onDelete && (
        <button onClick={e => { e.stopPropagation(); onDelete(); }}
          style={{
            background: confirmDelete ? 'var(--hot)' : 'none',
            color: confirmDelete ? 'white' : 'var(--faint)',
            border: 'none', borderRadius: 4, cursor: 'pointer',
            fontSize: confirmDelete ? 11 : 16, padding: '3px 7px', lineHeight: 1,
            transition: 'all .15s', fontWeight: confirmDelete ? 700 : 400, flexShrink: 0,
          }}>
          {confirmDelete ? '✓ Borrar' : '×'}
        </button>
      )}
    </div>
  );
}

// ── Tournament list screen ────────────────────────────────────
function TournamentListScreen({ user, onSelect, onLogout }) {
  const [owned, setOwned] = uSt([]);
  const [shared, setShared] = uSt([]);
  const [loading, setLoading] = uSt(true);
  const [creating, setCreating] = uSt(false);
  const [newName, setNewName] = uSt('');
  const [joinCode, setJoinCode] = uSt('');
  const [joinLoading, setJoinLoading] = uSt(false);
  const [joinMsg, setJoinMsg] = uSt({ type: '', text: '' });
  const [deleteConfirm, setDeleteConfirm] = uSt(null);

  async function refresh() {
    setLoading(true);
    const { data } = await window.Auth.listTournaments();
    setOwned(data?.owned || []);
    setShared(data?.member || []);
    setLoading(false);
  }
  uEf(() => { refresh(); }, []);

  async function createNew() {
    const name = newName.trim() || 'Nuevo Torneo';
    const defaultState = window.tournamentDefaultState();
    defaultState.meta.name = name;
    const { data, error } = await window.Auth.createTournament(name, defaultState);
    if (error) { alert('Error: ' + error.message); return; }
    onSelect(data.id, 'owner', defaultState);
  }

  async function openTournament(id, role) {
    const { data, error } = await window.Auth.getTournament(id);
    if (error || !data) { alert('No se pudo cargar el torneo.'); return; }
    onSelect(id, role, data.data);
  }

  async function deleteT(id) {
    if (deleteConfirm !== id) {
      setDeleteConfirm(id);
      setTimeout(() => setDeleteConfirm(null), 2500);
      return;
    }
    await window.Auth.deleteTournament(id);
    setDeleteConfirm(null);
    refresh();
  }

  async function join() {
    if (!joinCode.trim()) return;
    setJoinLoading(true); setJoinMsg({ type: '', text: '' });
    const { data, error } = await window.Auth.joinWithCode(joinCode.trim());
    setJoinLoading(false);
    if (error || data?.error) {
      setJoinMsg({ type: 'error', text: data?.error || error?.message || 'Error' });
      return;
    }
    setJoinMsg({ type: 'ok', text: `✓ Unido a "${data.tournament_name}" como ${data.role === 'editor' ? 'editor' : 'lector'}` });
    setJoinCode('');
    refresh();
  }

  const displayName = user.user_metadata?.name || user.email?.split('@')[0] || 'Usuario';

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', backgroundImage: 'radial-gradient(ellipse at 20% 10%, rgba(76,127,255,.07) 0%, transparent 55%)' }}>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 24px', borderBottom: '1px solid var(--border)',
        background: 'var(--surface)', position: 'sticky', top: 0, zIndex: 10,
        boxShadow: '0 2px 12px rgba(0,0,0,.3)',
      }}>
        <span style={{ fontFamily: 'var(--display)', fontSize: 22, letterSpacing: '.08em', color: 'var(--gold)' }}>EL BARRIO</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontSize: 13, color: 'var(--text-2)' }}>👤 {displayName}</span>
          <button className="btn btn-ghost btn-sm" onClick={onLogout} style={{ fontSize: 12 }}>Cerrar sesión</button>
        </div>
      </div>

      <div style={{ maxWidth: 700, margin: '0 auto', padding: '32px 16px' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 24 }}>
          <div>
            <h1 style={{ fontFamily: 'var(--display)', fontSize: 28, letterSpacing: '.06em', textTransform: 'uppercase', margin: 0 }}>Mis Torneos</h1>
            <div style={{ color: 'var(--muted)', fontSize: 13, marginTop: 4 }}>Selecciona o crea un torneo</div>
          </div>
          <button className="btn btn-primary" onClick={() => setCreating(c => !c)} style={{ flexShrink: 0 }}>+ Nuevo torneo</button>
        </div>

        {/* Create form */}
        {creating && (
          <div style={{ background: 'var(--surface)', border: '1px solid var(--accent)', borderRadius: 'var(--r)', padding: '16px 18px', marginBottom: 16, boxShadow: '0 0 0 1px var(--accent-dim)' }}>
            <div style={{ fontFamily: 'var(--display)', fontSize: 13, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 10 }}>Nuevo Torneo</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <input className="input" value={newName} onChange={e => setNewName(e.target.value)}
                placeholder="Nombre del torneo" onKeyDown={e => e.key === 'Enter' && createNew()}
                autoFocus style={{ flex: 1 }}/>
              <button className="btn btn-primary" onClick={createNew}>Crear</button>
              <button className="btn btn-ghost" onClick={() => { setCreating(false); setNewName(''); }}>✕</button>
            </div>
          </div>
        )}

        {loading ? (
          <div style={{ textAlign: 'center', padding: '60px 0', color: 'var(--muted)' }}>Cargando...</div>
        ) : owned.length === 0 && shared.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 24px', background: 'var(--surface)', border: '1px dashed var(--border-2)', borderRadius: 'var(--r-lg)' }}>
            <div style={{ fontSize: 48, marginBottom: 12 }}>🏆</div>
            <div style={{ fontFamily: 'var(--display)', fontSize: 20, letterSpacing: '.04em', marginBottom: 8 }}>SIN TORNEOS TODAVÍA</div>
            <div style={{ color: 'var(--muted)', fontSize: 13, marginBottom: 20 }}>Crea tu primer torneo o únete con un código.</div>
            <button className="btn btn-primary" onClick={() => setCreating(true)}>+ Crear primer torneo</button>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 20 }}>
            {owned.map(t => (
              <TournamentCard key={t.id} tournament={t} role="owner"
                onOpen={() => openTournament(t.id, 'owner')}
                onDelete={() => deleteT(t.id)}
                confirmDelete={deleteConfirm === t.id}/>
            ))}
            {shared.length > 0 && (
              <>
                <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.2em', textTransform: 'uppercase', color: 'var(--muted)', margin: '8px 0 2px', fontFamily: 'var(--ui-cond)' }}>
                  Compartidos conmigo
                </div>
                {shared.map(t => (
                  <TournamentCard key={t.id} tournament={t} role={t.role}
                    onOpen={() => openTournament(t.id, t.role)}/>
                ))}
              </>
            )}
          </div>
        )}

        {/* Migrate local data — solo visible para el usuario original */}
        {user.email === 'gnhc88@gmail.com' && (() => {
          try {
            const local = localStorage.getItem('elbarrio.tournament.v1');
            if (!local) return null;
            const parsed = JSON.parse(local);
            if (!parsed?.teams?.length && !parsed?.matches?.length) return null;
            return (
              <div style={{ background: 'rgba(245,200,66,.08)', border: '1px solid rgba(245,200,66,.25)', borderRadius: 'var(--r)', padding: '14px 16px', marginBottom: 8 }}>
                <div style={{ fontSize: 12, color: 'var(--gold)', fontWeight: 700, marginBottom: 6 }}>
                  💾 Tienes datos guardados localmente
                </div>
                <div style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: 10 }}>
                  Se encontró un torneo guardado antes del login: <b>{parsed.meta?.name || 'Torneo'}</b> ({parsed.teams?.length || 0} equipos, {parsed.matches?.length || 0} partidos).
                </div>
                <button className="btn btn-sm" style={{ fontSize: 12, borderColor: 'rgba(245,200,66,.4)', color: 'var(--gold)' }}
                  onClick={async () => {
                    const name = parsed.meta?.name || 'Torneo Importado';
                    const { data, error } = await window.Auth.createTournament(name, parsed);
                    if (error) { alert('Error al importar: ' + error.message); return; }
                    alert('✓ Torneo "' + name + '" importado correctamente. Ábrelo desde la lista.');
                    refresh();
                  }}>
                  ⬆ Importar a la nube
                </button>
              </div>
            );
          } catch(e) { return null; }
        })()}

        {/* Join with code */}
        <div style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 'var(--r)', padding: '16px 18px', marginTop: 4 }}>
          <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 10, fontFamily: 'var(--ui-cond)' }}>
            Unirse con código de invitación
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <input className="input mono" value={joinCode} onChange={e => setJoinCode(e.target.value.toUpperCase())}
              placeholder="CÓDIGO" maxLength={8}
              onKeyDown={e => e.key === 'Enter' && join()}
              style={{ flex: 1, letterSpacing: '.25em', fontSize: 16, fontWeight: 700, textAlign: 'center' }}/>
            <button className="btn btn-primary" onClick={join} disabled={joinLoading || !joinCode.trim()}>
              {joinLoading ? '...' : 'Unirse'}
            </button>
          </div>
          {joinMsg.text && (
            <div style={{ fontSize: 12, marginTop: 8, color: joinMsg.type === 'ok' ? 'var(--green)' : 'var(--hot)' }}>
              {joinMsg.text}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Share modal ───────────────────────────────────────────────
function ShareModal({ tournamentId, onClose }) {
  const [invites, setInvites] = uSt([]);
  const [members, setMembers] = uSt([]);
  const [role, setRole] = uSt('editor');
  const [creating, setCreating] = uSt(false);
  const [copied, setCopied] = uSt(null);

  async function refresh() {
    const [inv, mem] = await Promise.all([
      window.Auth.listInvites(tournamentId),
      window.Auth.listMembers(tournamentId),
    ]);
    setInvites(Array.isArray(inv.data) ? inv.data : []);
    setMembers(Array.isArray(mem.data) ? mem.data : []);
  }
  uEf(() => { refresh(); }, [tournamentId]);

  async function createInvite() {
    setCreating(true);
    await window.Auth.createInvite(tournamentId, role);
    setCreating(false);
    refresh();
  }

  function copyCode(code) {
    navigator.clipboard?.writeText(code).catch(() => {});
    setCopied(code);
    setTimeout(() => setCopied(null), 2000);
  }

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.75)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
      onClick={onClose}>
      <div style={{
        background: 'var(--surface)', border: '1px solid var(--border-2)',
        borderRadius: 'var(--r-lg)', padding: '24px', maxWidth: 460, width: '100%',
        margin: '0 16px', maxHeight: '80vh', overflowY: 'auto',
        boxShadow: '0 24px 64px rgba(0,0,0,.7)',
      }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
          <div style={{ fontFamily: 'var(--display)', fontSize: 18, letterSpacing: '.04em', textTransform: 'uppercase' }}>🔗 Compartir Torneo</div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 20, lineHeight: 1 }}>×</button>
        </div>

        {/* Generate code */}
        <div style={{ padding: '14px 16px', background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', marginBottom: 18 }}>
          <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.15em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 10, fontFamily: 'var(--ui-cond)' }}>
            Generar código de invitación
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <select className="select" value={role} onChange={e => setRole(e.target.value)} style={{ flex: 1, fontSize: 12 }}>
              <option value="editor">Editor — puede editar todo</option>
              <option value="viewer">Lector — solo ver</option>
            </select>
            <button className="btn btn-primary btn-sm" onClick={createInvite} disabled={creating}>
              {creating ? '...' : '+ Crear'}
            </button>
          </div>
        </div>

        {/* Active codes */}
        {invites.length > 0 && (
          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.15em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8, fontFamily: 'var(--ui-cond)' }}>
              Códigos activos
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {invites.map(inv => (
                <div key={inv.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', background: 'var(--surface-3)', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)' }}>
                  <span style={{ fontFamily: 'var(--display)', fontSize: 22, letterSpacing: '.18em', color: 'var(--text)', flex: 1 }}>{inv.code}</span>
                  <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: inv.role === 'editor' ? 'var(--accent)' : 'var(--muted)' }}>
                    {inv.role === 'editor' ? 'Editor' : 'Lector'}
                  </span>
                  <button className="btn btn-sm" onClick={() => copyCode(inv.code)} style={{ fontSize: 11, padding: '3px 10px' }}>
                    {copied === inv.code ? '✓ Copiado' : '📋 Copiar'}
                  </button>
                  <button onClick={() => { window.Auth.deleteInvite(inv.id); refresh(); }}
                    style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 16, padding: '0 4px', lineHeight: 1 }}>×</button>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Members */}
        {members.length > 0 && (
          <div>
            <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.15em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8, fontFamily: 'var(--ui-cond)' }}>
              Miembros ({members.length})
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {members.map(m => (
                <div key={m.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px', background: 'var(--surface-2)', borderRadius: 'var(--r-sm)' }}>
                  <span style={{ flex: 1, fontSize: 13 }}>{m.name || 'Usuario'}</span>
                  <span style={{ fontSize: 10, color: m.role === 'editor' ? 'var(--accent)' : 'var(--muted)', fontWeight: 700, textTransform: 'uppercase' }}>{m.role}</span>
                  <button onClick={() => { window.Auth.removeMember(m.id); refresh(); }}
                    style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 14, padding: '0 4px', lineHeight: 1 }}>×</button>
                </div>
              ))}
            </div>
          </div>
        )}

        {invites.length === 0 && members.length === 0 && (
          <div style={{ textAlign: 'center', padding: '16px 0', color: 'var(--muted)', fontSize: 13 }}>
            Crea un código para invitar personas a este torneo.
          </div>
        )}
      </div>
    </div>
  );
}

window.LoadingScreen = LoadingScreen;
window.AuthScreen = AuthScreen;
window.TournamentListScreen = TournamentListScreen;
window.ShareModal = ShareModal;
