/* Capitán Fantasy — Onboarding, Live Matchday, Profile, Mode/League detail, Quiniela, Notifications, Rules */

// ── ONBOARDING ────────────────────────────────────────────────
function Splash({ onDone }) {
  React.useEffect(() => { const t = setTimeout(onDone, 2200); return () => clearTimeout(t); }, []);
  return (
    <div onClick={onDone} style={{ position: 'absolute', inset: 0, zIndex: 95, cursor: 'pointer', background: 'radial-gradient(120% 90% at 50% 35%, hsl(240 12% 9%) 0%, hsl(var(--background)) 60%)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 22 }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: `url(${window.LT_ASSETS.bg})`, backgroundSize: 'cover', backgroundPosition: 'center', opacity: 0.12 }} />
      <img src={window.LT_ASSETS.logo} alt="Layvtime" style={{ width: 248, position: 'relative', animation: 'floatY 4s ease-in-out infinite', filter: 'drop-shadow(0 12px 30px rgba(0,0,0,0.6))' }} />
      <div style={{ position: 'relative', fontSize: 12, fontWeight: 800, letterSpacing: 3, color: C.mut, textTransform: 'uppercase', animation: 'fadeIn 1.4s ease' }}>El fantasy de la Liga MX</div>
      <div style={{ position: 'absolute', bottom: 80, width: 28, height: 28, borderRadius: 999, border: `3px solid ${C.secondary}`, borderTopColor: C.primary, animation: 'spin .8s linear infinite' }} />
    </div>
  );
}

function Login({ onDone }) {
  const feats = [
    { icon: 'radio', col: C.destructive, t: 'Partidos en vivo y gratis', s: 'Liga MX, Femenil y Selección' },
    { icon: 'trophy', col: C.gold, t: 'Fantasy de la Liga MX', s: 'Arma tu 11 y compite cada jornada' },
    { icon: 'target', col: C.primary, t: 'Quinielas y premios', s: 'Predice, gana puntos y sorteos' },
  ];
  return (
    <div className="noscroll" style={{ position: 'absolute', inset: 0, zIndex: 93, background: C.bg, animation: 'fadeIn .3s', overflowY: 'auto', overflowX: 'hidden' }}>
      <div style={{ position: 'relative', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Fondo animado: destellos que flotan */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: '-10%', left: '-15%', width: 300, height: 300, borderRadius: '50%', background: 'radial-gradient(circle, hsl(var(--primary) / 0.30), transparent 70%)', filter: 'blur(40px)', animation: 'auroraA 14s ease-in-out infinite' }} />
        <div style={{ position: 'absolute', bottom: '8%', right: '-20%', width: 320, height: 320, borderRadius: '50%', background: 'radial-gradient(circle, hsl(var(--gold) / 0.22), transparent 70%)', filter: 'blur(46px)', animation: 'auroraB 17s ease-in-out infinite' }} />
        <div style={{ position: 'absolute', top: '35%', left: '40%', width: 220, height: 220, borderRadius: '50%', background: 'radial-gradient(circle, hsl(var(--info) / 0.16), transparent 70%)', filter: 'blur(40px)', animation: 'auroraA 20s ease-in-out infinite reverse' }} />
        {/* partículas subiendo */}
        {[12, 30, 52, 68, 84].map((x, i) => (
          <span key={i} style={{ position: 'absolute', left: x + '%', bottom: 0, width: 4, height: 4, borderRadius: 9, background: i % 2 ? 'hsl(var(--gold) / 0.6)' : 'hsl(var(--primary) / 0.6)', animation: `driftUp ${9 + i * 1.5}s linear ${i * 1.2}s infinite` }} />
        ))}
      </div>

      {/* Hero superior con logo arriba */}
      <div style={{ position: 'relative', overflow: 'hidden', paddingTop: 64, paddingBottom: 24, flexShrink: 0 }}>
        <div style={{ position: 'absolute', inset: 0, backgroundImage: `url(${window.LT_ASSETS.hero})`, backgroundSize: 'cover', backgroundPosition: 'center', animation: 'glowPulse 8s ease-in-out infinite' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, hsl(var(--background) / 0.4) 0%, hsl(var(--background) / 0.55) 55%, hsl(var(--background)) 100%)' }} />
        {/* barrido de luz */}
        <div style={{ position: 'absolute', top: 0, bottom: 0, width: '45%', background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.10), transparent)', animation: 'lightSweep 6s ease-in-out infinite' }} />
        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, padding: '0 28px' }}>
          <img src={window.LT_ASSETS.logo} alt="Layvtime" style={{ width: 224, filter: 'drop-shadow(0 8px 24px rgba(0,0,0,0.8))', animation: 'logoIn .7s cubic-bezier(.2,.8,.2,1) both' }} />
          <div style={{ textAlign: 'center', animation: 'riseIn .6s ease .15s both' }}>
            <h1 style={{ fontSize: 29, fontWeight: 900, lineHeight: 1.08, textWrap: 'balance' }}>El fútbol mexicano <span className="text-gradient-gold">se vive aquí</span></h1>
            <p style={{ color: 'hsl(var(--foreground) / 0.8)', fontSize: 14, marginTop: 8, textWrap: 'pretty' }}>Transmisión, fantasy y quinielas en una sola app.</p>
          </div>
        </div>
      </div>

      {/* Propuestas de valor (llenan el centro) */}
      <div style={{ position: 'relative', flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 12, padding: '8px 24px' }}>
        {feats.map((f, i) => (
          <div key={f.t} style={{ display: 'flex', alignItems: 'center', gap: 14, background: 'hsl(var(--surface) / 0.72)', backdropFilter: 'blur(10px)', border: `1px solid ${C.cardBorder}`, borderRadius: 14, padding: '13px 15px', animation: `riseIn .55s ease ${0.3 + i * 0.12}s both` }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, flexShrink: 0, background: f.col.replace('hsl', 'hsla').replace(')', ' / 0.14)'), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={f.icon} size={22} color={f.col} />
            </div>
            <div>
              <div style={{ fontWeight: 700, fontSize: 15 }}>{f.t}</div>
              <div style={{ fontSize: 12.5, color: C.mut, marginTop: 1 }}>{f.s}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Acciones */}
      <div style={{ position: 'relative', padding: '8px 24px 38px', display: 'flex', flexDirection: 'column', gap: 11, flexShrink: 0, animation: 'riseIn .55s ease .66s both' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: C.secondary, border: `1px solid ${C.border}`, borderRadius: 12, padding: '14px 16px' }}>
          <span style={{ fontSize: 15, fontWeight: 600, color: C.mut }}>🇲🇽 +52</span>
          <div style={{ width: 1, height: 18, background: C.border }} />
          <span style={{ flex: 1, fontSize: 15, color: C.mut }}>55 1234 5678</span>
        </div>
        <Btn variant="primary" size="lg" full onClick={onDone}>Continuar</Btn>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '2px 0' }}>
          <div style={{ flex: 1, height: 1, background: C.border }} /><span style={{ fontSize: 12, color: C.mut }}>o</span><div style={{ flex: 1, height: 1, background: C.border }} />
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          {['Apple', 'Google'].map((s) => <Btn key={s} variant="secondary" full onClick={onDone}>{s}</Btn>)}
        </div>
      </div>
      </div>
    </div>
  );
}

function TeamSelect({ onDone }) {
  const T = window.CF.teams, keys = Object.keys(T);
  const [sel, setSel] = React.useState('ame');
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 92, background: C.bg, display: 'flex', flexDirection: 'column', animation: 'fadeIn .3s' }}>
      <div style={{ padding: '66px 24px 14px' }}>
        <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: 1, color: C.primary, textTransform: 'uppercase', marginBottom: 8 }}>Último paso</div>
        <h1 style={{ fontSize: 28, fontWeight: 900, lineHeight: 1.05 }}>Elige tu equipo favorito</h1>
        <p style={{ color: C.mut, fontSize: 14, marginTop: 8 }}>Personalizamos tu fantasy, ligas y alertas.</p>
      </div>
      <div className="noscroll" style={{ flex: 1, overflowY: 'auto', padding: '0 24px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 11 }}>
          {keys.map((k) => {
            const on = sel === k;
            return (
              <button key={k} onClick={() => setSel(k)} style={{ background: on ? 'hsl(var(--primary) / 0.1)' : C.card, cursor: 'pointer', border: `1.5px solid ${on ? C.primary : C.cardBorder}`, borderRadius: 14, padding: '14px 6px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
                <Crest team={k} size={40} />
                <span style={{ fontSize: 11, fontWeight: 600, color: on ? C.fg : C.mut, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>{T[k].name}</span>
              </button>
            );
          })}
        </div>
        <div style={{ height: 12 }} />
      </div>
      <div style={{ padding: '14px 24px 38px', borderTop: `1px solid ${C.border}` }}>
        <Btn variant="gold" size="lg" full icon="check" onClick={() => { window.CF.user.fav = sel; onDone(); }}>Empezar a jugar</Btn>
      </div>
    </div>
  );
}

function Onboarding({ onFinish }) {
  const [step, setStep] = React.useState('splash');
  return (<>
    {step === 'splash' && <Splash onDone={() => setStep('login')} />}
    {step === 'login' && <Login onDone={() => setStep('team')} />}
    {step === 'team' && <TeamSelect onDone={onFinish} />}
  </>);
}

// ── HEADER for stacked screens (with back) ────────────────────
function StackHeader({ title, onBack, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '52px 18px 12px', flexShrink: 0 }}>
      <button onClick={onBack} style={{ width: 38, height: 38, borderRadius: 999, background: C.secondary, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}><Icon name="chevL" size={20} color={C.fg} /></button>
      <h1 style={{ flex: 1, fontSize: 19, fontWeight: 800, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</h1>
      {right}
    </div>
  );
}

// ── LIVE MATCHDAY ─────────────────────────────────────────────
function LiveScreen({ onBack, go }) {
  const CF = window.CF, T = CF.teams;
  return (
    <div className="animate-slide-up">
      <StackHeader title="Jornada en vivo" onBack={onBack} right={<LiveBadge />} />
      {/* Canal Layvtime acceso */}
      {go && (
        <div style={{ padding: '0 18px', marginBottom: 14 }}>
          <div onClick={() => go('channel')} className="gradient-pitch" style={{ borderRadius: 14, padding: '13px 15px', display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer', border: '1px solid hsl(var(--pitch-light) / 0.5)' }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: 'rgba(0,0,0,0.25)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="radio" size={20} color="#fff" /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 800, fontSize: 14.5, color: '#fff' }}>Canal Layvtime</div>
              <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.8)' }}>Layvtime Live al aire ahora · 38.2K viendo</div>
            </div>
            <Icon name="chevR" size={18} color="#fff" />
          </div>
        </div>
      )}
      {/* my GW points hero */}
      <div style={{ padding: '0 18px', marginBottom: 16 }}>
        <div className="gradient-card" style={{ borderRadius: 16, padding: 16, border: `1px solid ${C.cardBorder}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 11.5, color: C.mut, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4 }}>Tus puntos · J14</div>
            <div className="num text-gradient-primary" style={{ fontWeight: 900, fontSize: 34, lineHeight: 1.1 }}>48</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'flex-end' }}><LiveDot size={7} /><span style={{ fontSize: 12.5, color: C.mut }}>6 jugadores en cancha</span></div>
            <div style={{ fontSize: 12.5, color: C.success, fontWeight: 700, marginTop: 4 }}>↑ subiste 38 lugares</div>
          </div>
        </div>
      </div>

      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ fontSize: 11, color: C.mut, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: -2 }}>En juego</div>
        {CF.liveMatches.filter((m) => m.status === 'live').map((m) => (
          <Card key={m.id} pad={14}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, marginBottom: m.scorers.length ? 12 : 0 }}>
              <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 9, justifyContent: 'flex-end' }}>
                <span style={{ fontWeight: 700, fontSize: 14 }}>{T[m.home].name}</span><Crest team={m.home} size={30} />
              </div>
              <div style={{ textAlign: 'center', minWidth: 64 }}>
                <div className="num" style={{ fontWeight: 900, fontSize: 24 }}>{m.hs} <span style={{ color: C.mut }}>-</span> {m.as}</div>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginTop: 2 }}><LiveDot size={5} /><span className="num" style={{ fontSize: 11, color: C.destructive, fontWeight: 700 }}>{m.minute}'</span></div>
              </div>
              <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 9 }}>
                <Crest team={m.away} size={30} /><span style={{ fontWeight: 700, fontSize: 14 }}>{T[m.away].name}</span>
              </div>
            </div>
            {m.scorers.length > 0 && (
              <div style={{ borderTop: `1px solid ${C.border}`, paddingTop: 10, display: 'flex', flexWrap: 'wrap', gap: '4px 14px' }}>
                {m.scorers.map((s, i) => <span key={i} style={{ fontSize: 11.5, color: C.mut, display: 'flex', alignItems: 'center', gap: 5 }}>⚽ {s}</span>)}
              </div>
            )}
          </Card>
        ))}
        <div style={{ fontSize: 11, color: C.mut, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, margin: '6px 0 -2px' }}>Por comenzar</div>
        {CF.liveMatches.filter((m) => m.status === 'soon').map((m) => (
          <Card key={m.id} pad={13} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span className="num" style={{ width: 48, fontSize: 13, fontWeight: 700, color: C.mut }}>{m.kickoff}</span>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 9 }}><Crest team={m.home} size={24} /><span style={{ fontSize: 13.5, fontWeight: 600 }}>{T[m.home].short}</span><span style={{ color: C.mut, fontSize: 12 }}>vs</span><Crest team={m.away} size={24} /><span style={{ fontSize: 13.5, fontWeight: 600 }}>{T[m.away].short}</span></div>
          </Card>
        ))}
      </div>
    </div>
  );
}

// ── QUINIELA predictions ──────────────────────────────────────
function QuinielaScreen({ onBack }) {
  const CF = window.CF, T = CF.teams;
  const [picks, setPicks] = React.useState({});
  const done = Object.keys(picks).length;
  return (
    <div className="animate-slide-up">
      <StackHeader title="Quiniela de la jornada" onBack={onBack} />
      <div style={{ padding: '0 18px', marginBottom: 14 }}>
        <Card pad={14} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div><div style={{ fontSize: 11.5, color: C.mut, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4 }}>Progreso</div><div className="num" style={{ fontWeight: 900, fontSize: 22 }}>{done}<span style={{ color: C.mut, fontSize: 16 }}>/{CF.quiniela.length}</span></div></div>
          <div style={{ textAlign: 'right' }}><div style={{ fontSize: 11.5, color: C.mut, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4 }}>Premio</div><div className="num text-gradient-gold" style={{ fontWeight: 900, fontSize: 22 }}>180 pts</div></div>
        </Card>
      </div>
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 9 }}>
        {CF.quiniela.map((q) => (
          <Card key={q.id} pad={12}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 7, minWidth: 0 }}><Crest team={q.home} size={24} /><span style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{T[q.home].short}</span></div>
              <div style={{ display: 'flex', gap: 5 }}>
                {[['home', 'L'], ['draw', 'E'], ['away', 'V']].map(([k, l]) => {
                  const on = picks[q.id] === k;
                  return <button key={k} onClick={() => setPicks((p) => ({ ...p, [q.id]: k }))} style={{ width: 34, height: 34, borderRadius: 9, fontFamily: 'inherit', fontWeight: 800, fontSize: 13, cursor: 'pointer', border: `1px solid ${on ? C.primary : C.border}`, background: on ? C.primary : C.secondary, color: on ? '#fff' : C.mut }}>{l}</button>;
                })}
              </div>
              <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 7, justifyContent: 'flex-end', minWidth: 0 }}><span style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{T[q.away].short}</span><Crest team={q.away} size={24} /></div>
            </div>
          </Card>
        ))}
        <Btn variant={done === CF.quiniela.length ? 'gold' : 'secondary'} full disabled={done !== CF.quiniela.length} icon={done === CF.quiniela.length ? 'check' : 'lock'} style={{ marginTop: 4 }}>{done === CF.quiniela.length ? 'Enviar quiniela' : `Faltan ${CF.quiniela.length - done}`}</Btn>
      </div>
    </div>
  );
}

// ── MODE DETAIL (join a game mode) ────────────────────────────
function ModeDetail({ modeId, onBack, go }) {
  const CF = window.CF;
  const m = CF.modeById(modeId);
  const modeColors = { primary: C.primary, info: C.info, gold: C.gold, pitch: C.pitchLight, destructive: C.destructive };
  const col = modeColors[m.color];
  const sample = [
    { name: 'Liga Pública Nacional', members: '12.4K', open: true },
    { name: 'Novatos Bienvenidos', members: '3.2K', open: true },
    { name: 'Solo Cracks (Pro)', members: '890', open: false },
  ];
  return (
    <div className="animate-slide-up">
      <StackHeader title={m.name} onBack={onBack} />
      <div style={{ padding: '0 18px 24px' }}>
        <div style={{ borderRadius: 18, padding: 20, marginBottom: 18, background: col.replace('hsl', 'hsla').replace(')', ' / 0.1)'), border: `1px solid ${col.replace('hsl', 'hsla').replace(')', ' / 0.25)')}`, position: 'relative', overflow: 'hidden' }}>
          <div style={{ width: 56, height: 56, borderRadius: 16, background: col.replace('hsl', 'hsla').replace(')', ' / 0.16)'), display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}><Icon name={m.icon} size={28} color={col} /></div>
          <h2 style={{ fontSize: 21, fontWeight: 900, marginBottom: 6 }}>{m.name}</h2>
          <p style={{ fontSize: 14, color: C.mut, lineHeight: 1.5, textWrap: 'pretty' }}>{m.desc}</p>
          <div style={{ display: 'flex', gap: 5, alignItems: 'center', marginTop: 12 }}><Icon name="users" size={14} color={C.mut} /><span style={{ fontSize: 12.5, color: C.mut, fontWeight: 600 }}>{m.players} jugadores activos</span></div>
        </div>

        <div style={{ display: 'flex', gap: 10, marginBottom: 22 }}>
          <Btn variant="primary" full icon="plus">Crear liga</Btn>
          <Btn variant="secondary" full icon="users">Con código</Btn>
        </div>

        <SectionHead title="Ligas abiertas" sub="Únete con un toque" />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          {sample.map((s, i) => (
            <Card key={i} pad={14} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 42, height: 42, borderRadius: 11, background: C.secondary, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={m.icon} size={20} color={col} /></div>
              <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14.5 }}>{s.name}</div><div style={{ fontSize: 12, color: C.mut, marginTop: 2 }}>{s.members} miembros</div></div>
              <Btn size="sm" variant={s.open ? 'outline' : 'ghost'} disabled={!s.open}>{s.open ? 'Unirme' : 'Llena'}</Btn>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── LEAGUE DETAIL ─────────────────────────────────────────────
function LeagueDetail({ leagueId, onBack }) {
  const CF = window.CF;
  const l = CF.myLeagues.find((x) => x.id === leagueId) || CF.myLeagues[0];
  const mode = CF.modeById(l.mode);
  const members = CF.leaderboard.slice(0, l.members > 7 ? 7 : l.members).map((r, i) => ({ ...r, rank: i + 1 }));
  return (
    <div className="animate-slide-up">
      <StackHeader title={l.name} onBack={onBack} right={<button style={{ width: 38, height: 38, borderRadius: 999, background: C.secondary, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}><Icon name="share" size={17} color={C.mut} /></button>} />
      <div style={{ padding: '0 18px 24px' }}>
        <div style={{ display: 'flex', gap: 10, marginBottom: 18 }}>
          {[['Modo', mode.name], ['Miembros', l.members], ['Tu lugar', l.myRank ? '#' + l.myRank : l.record || '—']].map(([a, b]) => (
            <Card key={a} pad={12} style={{ flex: 1, textAlign: 'center' }}><div className="num" style={{ fontWeight: 900, fontSize: 16 }}>{b}</div><div style={{ fontSize: 10.5, color: C.mut, fontWeight: 600, marginTop: 2 }}>{a}</div></Card>
          ))}
        </div>
        <SectionHead title="Clasificación" sub={`Jornada ${l.gw || 14}`} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {members.map((r) => (
            <div key={r.rank} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px', borderRadius: 13, background: r.you ? 'hsl(var(--primary) / 0.1)' : C.card, border: `1px solid ${r.you ? 'hsl(var(--primary) / 0.3)' : C.cardBorder}` }}>
              <span className="num" style={{ width: 20, fontWeight: 900, fontSize: 15, color: r.rank === 1 ? C.gold : r.rank === 2 ? C.silver : r.rank === 3 ? C.bronze : C.mut }}>{r.rank}</span>
              <Avatar name={r.name} size={34} />
              <span style={{ flex: 1, fontWeight: 700, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.name}</span>
              <span className="num" style={{ fontWeight: 900, fontSize: 16, color: r.you ? C.primary : C.fg }}>{r.pts.toLocaleString('es-MX')}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── NOTIFICATIONS ─────────────────────────────────────────────
function NotifScreen({ onBack }) {
  const items = [
    { icon: 'fire', col: C.primary, title: 'L. Romo (tu capitán) anotó', sub: '+12 pts · doble por capitán', time: '2 min' },
    { icon: 'lock', col: C.warning, title: 'La jornada cierra en 2 horas', sub: 'Confirma tu alineación', time: '1 h' },
    { icon: 'trophy', col: C.gold, title: 'Subiste al puesto #2', sub: 'Liga de la Oficina', time: '3 h' },
    { icon: 'swords', col: C.info, title: 'Tu rival de Liga 1v1 alineó', sub: 'Cracks del Barrio · J14', time: '5 h' },
    { icon: 'users', col: C.success, title: 'Carlos te invitó a una liga', sub: 'Survivor Familiar', time: '1 d' },
  ];
  return (
    <div className="animate-slide-up">
      <StackHeader title="Notificaciones" onBack={onBack} />
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 9 }}>
        {items.map((n, i) => (
          <Card key={i} pad={13} style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, flexShrink: 0, background: n.col.replace('hsl', 'hsla').replace(')', ' / 0.14)'), display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={n.icon} size={19} color={n.col} /></div>
            <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14 }}>{n.title}</div><div style={{ fontSize: 12, color: C.mut, marginTop: 1 }}>{n.sub}</div></div>
            <span style={{ fontSize: 11, color: C.mut }}>{n.time}</span>
          </Card>
        ))}
      </div>
    </div>
  );
}

// ── PROFILE ───────────────────────────────────────────────────
function ProfileScreen({ go }) {
  const CF = window.CF, u = CF.user, T = CF.teams;
  return (
    <div className="animate-slide-up">
      <div style={{ position: 'relative', paddingTop: 56, paddingBottom: 18, overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: `linear-gradient(180deg, ${T[u.fav].c1}40, transparent 70%)` }} />
        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 9 }}>
          <Crest team={u.fav} size={72} />
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 21, fontWeight: 900 }}>{u.name}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center', marginTop: 3 }}>
              <span style={{ fontSize: 13, color: C.mut }}>{u.handle}</span>
              <TierBadge tier="professional" small />
            </div>
          </div>
        </div>
      </div>
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
          {[['Total pts', u.totalPts.toLocaleString('es-MX'), C.gold], ['Ranking', '#' + u.rank.toLocaleString('es-MX'), C.fg], ['Mejor J', u.bestGw, C.primary]].map(([l, v, col]) => (
            <Card key={l} pad={13} style={{ textAlign: 'center' }}><div className="num" style={{ fontWeight: 900, fontSize: 17, color: col }}>{v}</div><div style={{ fontSize: 10.5, color: C.mut, fontWeight: 600, marginTop: 2 }}>{l}</div></Card>
          ))}
        </div>

        <div>
          <SectionHead title="Mis ligas" sub={`${CF.myLeagues.length} activas`} action="Ver todas" onAction={() => go('fantasy')} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            {CF.myLeagues.slice(0, 2).map((l) => <LeagueCard key={l.id} league={l} onClick={() => go('league', l.id)} />)}
          </div>
        </div>

        <div>
          <SectionHead title="Cuenta" />
          <Card pad={0}>
            {[['Equipo favorito', T[u.fav].name, 'shield'], ['Notificaciones', 'Activadas', 'bell'], ['Cómo se juega', '', 'book'], ['Ajustes', '', 'settings'], ['Cerrar sesión', '', 'logout']].map(([l, v, ic], i, arr) => (
              <div key={l} onClick={ic === 'book' ? () => go('rules') : undefined} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px', borderBottom: i < arr.length - 1 ? `1px solid ${C.border}` : 'none', cursor: 'pointer' }}>
                <Icon name={ic} size={19} color={ic === 'logout' ? C.destructive : C.mut} />
                <span style={{ flex: 1, fontWeight: 600, fontSize: 14, color: ic === 'logout' ? C.destructive : C.fg }}>{l}</span>
                {v && <span style={{ fontSize: 13, color: C.mut }}>{v}</span>}
                {ic !== 'logout' && <Icon name="chevR" size={16} color={C.mut} />}
              </div>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
}

// ── RULES / scoring ───────────────────────────────────────────
function FormatRule({ mode }) {
  const [open, setOpen] = React.useState(false);
  const cvar = `var(--${mode.color || 'primary'})`;
  const col = `hsl(${cvar})`;
  return (
    <Card pad={0} style={{ overflow: 'hidden' }}>
      <button onClick={() => setOpen((o) => !o)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
        <div style={{ width: 38, height: 38, borderRadius: 10, background: `hsl(${cvar} / 0.14)`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name={mode.icon} size={19} color={col} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 14.5, color: C.fg }}>{mode.name}</div>
          {mode.tag && <div style={{ fontSize: 11, color: col, fontWeight: 600, marginTop: 1 }}>{mode.tag}</div>}
        </div>
        <Icon name="chevD" size={18} color={C.mut} style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .2s', flexShrink: 0 }} />
      </button>
      {open && (
        <div style={{ padding: '0 14px 14px 64px', animation: 'fadeIn .2s' }}>
          <p style={{ fontSize: 13, color: C.mut, lineHeight: 1.55, margin: 0 }}>{mode.desc}</p>
        </div>
      )}
    </Card>
  );
}

function RulesScreen({ onBack }) {
  const scoring = [
    { label: 'Jugar (titular)', pts: '+2' }, { label: 'Jugar 90 min', pts: '+2' },
    { label: 'Gol (DEL)', pts: '+2' }, { label: 'Gol (MED)', pts: '+3' }, { label: 'Gol (DEF)', pts: '+5' }, { label: 'Gol (POR)', pts: '+10' },
    { label: 'Asistencia', pts: '+2' }, { label: 'Portería en cero (POR/DEF)', pts: '+3' },
    { label: 'Victoria del equipo', pts: '+3' }, { label: 'Tarjeta amarilla', pts: '-1' }, { label: 'Tarjeta roja', pts: '-3' }, { label: 'Autogol', pts: '-3' },
  ];
  return (
    <div className="animate-slide-up">
      <StackHeader title="Cómo se juega" onBack={onBack} />
      <div style={{ padding: '0 18px 24px' }}>
        <p style={{ fontSize: 14, color: C.mut, lineHeight: 1.6, marginBottom: 18 }}>Arma tu equipo de 11 con un presupuesto de 100 créditos, elige capitán (puntos dobles) y un DT. Tus jugadores suman puntos según su desempeño real cada jornada.</p>
        <SectionHead title="Sistema de puntos" icon="sparkle" />
        <Card pad={0}>
          {scoring.map((s, i) => (
            <div key={s.label} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', borderBottom: i < scoring.length - 1 ? `1px solid ${C.border}` : 'none' }}>
              <span style={{ fontSize: 14, fontWeight: 500 }}>{s.label}</span>
              <span className="num" style={{ fontWeight: 800, fontSize: 15, color: s.pts.startsWith('-') ? C.destructive : C.success }}>{s.pts}</span>
            </div>
          ))}
        </Card>
        <div style={{ marginTop: 16, padding: 14, borderRadius: 12, background: 'hsl(var(--gold) / 0.08)', border: '1px solid hsl(var(--gold) / 0.2)', display: 'flex', gap: 10 }}>
          <Icon name="crown" size={20} color={C.gold} style={{ flexShrink: 0, marginTop: 1 }} />
          <span style={{ fontSize: 13, color: C.fg, lineHeight: 1.5 }}>Tu <b>capitán</b> suma el <b>doble</b> de puntos. Elígelo bien cada jornada.</span>
        </div>

        <div style={{ marginTop: 22 }}>
          <SectionHead title="Otros formatos" sub="Toca para ver cómo se juega cada uno" icon="swords" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {window.CF.gameModes.map((m) => <FormatRule key={m.id} mode={m} />)}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Onboarding, Splash, Login, TeamSelect, StackHeader, LiveScreen, QuinielaScreen, ModeDetail, LeagueDetail, NotifScreen, ProfileScreen, RulesScreen });
