/* Capitán Fantasy — Fantasy (Leaderboard), Juegos, Quiniela Mundial, Stats */

// ── FANTASY / LEADERBOARD ─────────────────────────────────────
function FantasyScreen({ go }) {
  const CF = window.CF, u = CF.user;
  const [tab, setTab] = React.useState('global');
  return (
    <div className="animate-slide-up">
      <TopHeader title="Fantasy" sub="Liga MX · Clausura" right={<button onClick={() => go('notif')} style={{ width: 38, height: 38, borderRadius: 999, background: C.secondary, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', position: 'relative' }}><Icon name="bell" size={18} color={C.mut} /><span style={{ position: 'absolute', top: 9, right: 10, width: 7, height: 7, borderRadius: 9, background: C.primary, border: '1.5px solid hsl(var(--surface))' }} /></button>} />

      {/* My performance hero */}
      <div style={{ padding: '0 18px', marginBottom: 18 }}>
        <div className="gradient-card glow-primary" style={{ borderRadius: 18, padding: 18, border: `1px solid ${C.cardBorder}`, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', right: -30, top: -30, width: 150, height: 150, borderRadius: 999, background: 'radial-gradient(circle, hsl(var(--primary) / 0.18), transparent 70%)' }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16, position: 'relative' }}>
            <div style={{ position: 'relative' }}>
              <Crest team={u.fav} size={48} />
              <span style={{ position: 'absolute', bottom: -3, right: -3, width: 20, height: 20, borderRadius: 999, background: C.gold, color: '#1a1505', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '2px solid hsl(var(--card))' }}><Icon name="crown" size={11} color="#1a1505" /></span>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 800, fontSize: 17 }}>{u.teamName}</div>
              <div style={{ fontSize: 12.5, color: C.mut }}>{u.handle} · <span style={{ color: C.primary, fontWeight: 600 }}>{u.level}</span></div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10, position: 'relative' }}>
            {[['Total', u.totalPts.toLocaleString('es-MX'), C.gold], ['Jornada', u.gwPts, C.primary], ['Ranking', '#' + u.rank.toLocaleString('es-MX'), C.fg]].map(([l, v, col]) => (
              <div key={l} style={{ flex: 1, background: C.secondary, borderRadius: 12, padding: '11px 8px', textAlign: 'center' }}>
                <div className="num" style={{ fontWeight: 900, fontSize: 19, color: col }}>{v}</div>
                <div style={{ fontSize: 10.5, color: C.mut, fontWeight: 600, marginTop: 1 }}>{l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* tabs */}
      <div style={{ padding: '0 18px', display: 'flex', gap: 8, marginBottom: 14 }}>
        {[['global', 'Global'], ['leagues', 'Mis ligas']].map(([k, l]) => (
          <button key={k} onClick={() => setTab(k)} style={{ flex: 1, padding: '9px', borderRadius: 10, fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, cursor: 'pointer', border: `1px solid ${tab === k ? C.primary : C.border}`, background: tab === k ? C.primary : 'transparent', color: tab === k ? '#fff' : C.mut }}>{l}</button>
        ))}
      </div>

      {tab === 'global' && (
        <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {CF.leaderboard.map((r) => (
            <div key={r.rank} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 14, background: r.you ? 'hsl(var(--primary) / 0.1)' : C.card, border: `1px solid ${r.you ? 'hsl(var(--primary) / 0.3)' : C.cardBorder}` }}>
              <div style={{ width: 26, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <span className="num" style={{ fontWeight: 900, fontSize: 16, color: r.rank === 1 ? C.gold : r.rank === 2 ? C.silver : r.rank === 3 ? C.bronze : C.mut }}>{r.rank}</span>
                {r.move !== 0 && <span style={{ display: 'flex', alignItems: 'center', color: r.move > 0 ? C.success : C.destructive }}><Icon name={r.move > 0 ? 'arrowUp' : 'arrowDown'} size={11} /></span>}
              </div>
              <Avatar name={r.name} size={38} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.name}</div>
                <div style={{ fontSize: 11.5, color: C.mut }}>{r.team} · J{r.gw}</div>
              </div>
              <div className="num" style={{ fontWeight: 900, fontSize: 17, color: r.you ? C.primary : C.fg }}>{r.pts.toLocaleString('es-MX')}</div>
            </div>
          ))}
        </div>
      )}

      {tab === 'leagues' && (
        <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {CF.myLeagues.map((l) => <LeagueCard key={l.id} league={l} onClick={() => go('league', l.id)} />)}
          <Btn variant="outline" icon="plus" full style={{ marginTop: 4 }} onClick={() => go('games')}>Unirme o crear liga</Btn>
        </div>
      )}
    </div>
  );
}

function LeagueCard({ league, onClick }) {
  const mode = window.CF.modeById(league.mode);
  return (
    <Card onClick={onClick} pad={14} style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
      <div style={{ width: 44, height: 44, borderRadius: 12, flexShrink: 0, background: C.secondary, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={mode?.icon || 'trophy'} size={22} color={C.primary} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 15 }}>{league.name}</div>
        <div style={{ fontSize: 12, color: C.mut, marginTop: 2 }}>{mode?.name} · {league.members} miembros</div>
      </div>
      <div style={{ textAlign: 'right' }}>
        {league.myRank && <div className="num" style={{ fontWeight: 800, fontSize: 16 }}>#{league.myRank}</div>}
        {league.record && <div className="num" style={{ fontWeight: 800, fontSize: 14, color: C.success }}>{league.record}</div>}
        {league.status && <div style={{ fontSize: 12, fontWeight: 700, color: C.success }}>{league.status}</div>}
        <div style={{ fontSize: 11, color: C.mut }}>{league.myRank ? 'tu lugar' : league.alive ? league.alive + ' vivos' : ''}</div>
      </div>
      <Icon name="chevR" size={18} color={C.mut} />
    </Card>
  );
}

// ── JUEGOS (game modes) ───────────────────────────────────────
function GamesScreen({ go }) {
  const CF = window.CF;
  const modeColors = { primary: C.primary, info: C.info, gold: C.gold, pitch: C.pitchLight, destructive: C.destructive };
  return (
    <div className="animate-slide-up">
      <TopHeader title="Juegos" sub="Elige tu modo de competencia" />
      <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {CF.gameModes.map((m) => {
          const col = modeColors[m.color];
          return (
            <Card key={m.id} onClick={() => go('mode', m.id)} pad={0} style={{ overflow: 'hidden' }}>
              <div style={{ display: 'flex', gap: 14, padding: 16 }}>
                <div style={{ width: 52, height: 52, borderRadius: 14, flexShrink: 0, background: col.replace('hsl', 'hsla').replace(')', ' / 0.14)'), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name={m.icon} size={26} color={col} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                    <span style={{ fontWeight: 800, fontSize: 16 }}>{m.name}</span>
                    {m.tag && <span style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: 0.3, padding: '2px 7px', borderRadius: 999, color: col, background: col.replace('hsl', 'hsla').replace(')', ' / 0.14)') }}>{m.tag.toUpperCase()}</span>}
                  </div>
                  <div style={{ fontSize: 12.5, color: C.mut, lineHeight: 1.4, textWrap: 'pretty' }}>{m.desc}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 8 }}>
                    <Icon name="users" size={13} color={C.mut} />
                    <span style={{ fontSize: 11.5, color: C.mut, fontWeight: 600 }}>{m.players} jugando</span>
                  </div>
                </div>
                <Icon name="chevR" size={18} color={C.mut} style={{ alignSelf: 'center' }} />
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

// ── QUINIELA MUNDIAL ──────────────────────────────────────────
function MundialScreen() {
  const CF = window.CF;
  const [picks, setPicks] = React.useState({});
  const [tab, setTab] = React.useState('predice');
  return (
    <div className="animate-slide-up">
      <TopHeader title="Mundial" sub="Quiniela · Fase de grupos" right={<span style={{ fontSize: 26 }}>🏆</span>} />

      {/* prize banner */}
      <div style={{ padding: '0 18px', marginBottom: 16 }}>
        <div className="gradient-gold" style={{ borderRadius: 16, padding: 16, color: '#1a1505', position: 'relative', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: 0.5, opacity: 0.7, textTransform: 'uppercase' }}>Bolsa global</div>
              <div className="num" style={{ fontWeight: 900, fontSize: 28, lineHeight: 1.1 }}>$50,000 MXN</div>
              <div style={{ fontSize: 12.5, fontWeight: 600, marginTop: 2 }}>+ 24,102 participantes</div>
            </div>
            <Icon name="trophy" size={48} color="#1a1505" style={{ opacity: 0.25 }} />
          </div>
        </div>
      </div>

      <div style={{ padding: '0 18px', display: 'flex', gap: 8, marginBottom: 14 }}>
        {[['predice', 'Predice'], ['grupos', 'Grupos']].map(([k, l]) => (
          <button key={k} onClick={() => setTab(k)} style={{ flex: 1, padding: '9px', borderRadius: 10, fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, cursor: 'pointer', border: `1px solid ${tab === k ? C.gold : C.border}`, background: tab === k ? 'hsl(var(--gold) / 0.14)' : 'transparent', color: tab === k ? C.gold : C.mut }}>{l}</button>
        ))}
      </div>

      {tab === 'predice' && (
        <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {CF.mundialFixtures.map((m) => (
            <Card key={m.id} pad={14}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: C.mut, marginBottom: 12, fontWeight: 600 }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="clock" size={12} /> {m.date}</span>
                <span>+10 pts acierto</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 26 }}>{m.hf}</span><span style={{ fontWeight: 700, fontSize: 14 }}>{m.home}</span>
                </div>
                <div style={{ display: 'flex', gap: 5 }}>
                  {[['home', '1'], ['draw', 'X'], ['away', '2']].map(([k, l]) => {
                    const on = picks[m.id] === k;
                    return <button key={k} onClick={() => setPicks((p) => ({ ...p, [m.id]: k }))} style={{ width: 38, height: 38, borderRadius: 10, fontFamily: 'inherit', fontWeight: 800, fontSize: 14, cursor: 'pointer', border: `1px solid ${on ? C.gold : C.border}`, background: on ? C.gold : C.secondary, color: on ? '#1a1505' : C.fg }}>{l}</button>;
                  })}
                </div>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}>
                  <span style={{ fontWeight: 700, fontSize: 14, textAlign: 'right' }}>{m.away}</span><span style={{ fontSize: 26 }}>{m.af}</span>
                </div>
              </div>
            </Card>
          ))}
          <Btn variant="gold" full icon="check" style={{ marginTop: 4 }}>Guardar predicciones</Btn>
        </div>
      )}

      {tab === 'grupos' && (
        <div style={{ padding: '0 18px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          {CF.mundialGroups.map((g) => (
            <Card key={g.group} pad={0} style={{ overflow: 'hidden' }}>
              <div style={{ padding: '10px 14px', borderBottom: `1px solid ${C.border}`, fontWeight: 800, fontSize: 14 }}>Grupo {g.group}</div>
              {g.teams.sort((a, b) => b.pts - a.pts).map((t, i) => (
                <div key={t.n} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '10px 14px', borderBottom: i < 3 ? `1px solid ${C.border}` : 'none', background: i < 2 ? 'hsl(var(--success) / 0.05)' : 'transparent' }}>
                  <span className="num" style={{ width: 14, color: i < 2 ? C.success : C.mut, fontWeight: 700, fontSize: 13 }}>{i + 1}</span>
                  <span style={{ fontSize: 22 }}>{t.f}</span>
                  <span style={{ flex: 1, fontWeight: 600, fontSize: 14 }}>{t.n}</span>
                  <span className="num" style={{ fontSize: 12, color: C.mut }}>{t.pj} PJ</span>
                  <span className="num" style={{ fontWeight: 800, fontSize: 15, width: 24, textAlign: 'right' }}>{t.pts}</span>
                </div>
              ))}
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

// ── STATS ─────────────────────────────────────────────────────
function StatsScreen() {
  const CF = window.CF;
  const [tab, setTab] = React.useState('fantasy');
  return (
    <div className="animate-slide-up">
      <TopHeader title="Estadísticas" sub="Liga MX · Clausura J14" />
      <div style={{ padding: '0 18px', display: 'flex', gap: 8, marginBottom: 16 }}>
        {[['fantasy', 'Fantasy'], ['scorers', 'Goleo'], ['tabla', 'Tabla']].map(([k, l]) => (
          <button key={k} onClick={() => setTab(k)} style={{ flex: 1, padding: '9px', borderRadius: 10, fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, cursor: 'pointer', border: `1px solid ${tab === k ? C.primary : C.border}`, background: tab === k ? C.primary : 'transparent', color: tab === k ? '#fff' : C.mut }}>{l}</button>
        ))}
      </div>

      {tab === 'fantasy' && (
        <div style={{ padding: '0 18px 24px' }}>
          <SectionHead title="Top puntos fantasy" sub="Más valiosos de la temporada" icon="sparkle" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {CF.topFantasy.map((p, i) => (
              <Card key={p.id} pad={12} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <span className="num" style={{ width: 20, fontWeight: 900, fontSize: 15, color: i < 3 ? C.gold : C.mut }}>{i + 1}</span>
                <PlayerAvatar player={p} size={36} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 14.5 }}>{p.name}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}><PosPill pos={p.pos} /><span style={{ fontSize: 11.5, color: C.mut }}>{CF.teams[p.team].name}</span></div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="num" style={{ fontWeight: 900, fontSize: 18, color: C.primary }}>{p.pts}</div>
                  <div className="num" style={{ fontSize: 11, color: C.gold }}>{p.cost} cr</div>
                </div>
              </Card>
            ))}
          </div>
        </div>
      )}

      {tab === 'scorers' && (
        <div style={{ padding: '0 18px 24px' }}>
          <SectionHead title="Tabla de goleo" sub="Pichichi del torneo" icon="target" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {CF.topScorers.map((s, i) => {
              const p = CF.pById(s.player);
              return (
                <Card key={s.player} pad={12} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span className="num" style={{ width: 20, fontWeight: 900, fontSize: 15, color: i === 0 ? C.gold : C.mut }}>{i + 1}</span>
                  <PlayerAvatar player={p} size={36} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 14.5 }}>{p.name}</div>
                    <div style={{ fontSize: 11.5, color: C.mut, marginTop: 2 }}>{CF.teams[p.team].name}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 14, textAlign: 'center' }}>
                    <div><div className="num" style={{ fontWeight: 900, fontSize: 18 }}>{s.goals}</div><div style={{ fontSize: 10, color: C.mut, fontWeight: 600 }}>GOL</div></div>
                    <div><div className="num" style={{ fontWeight: 800, fontSize: 18, color: C.mut }}>{s.assists}</div><div style={{ fontSize: 10, color: C.mut, fontWeight: 600 }}>ASI</div></div>
                  </div>
                </Card>
              );
            })}
          </div>
        </div>
      )}

      {tab === 'tabla' && (
        <div style={{ padding: '0 18px 24px' }}>
          <SectionHead title="Tabla general" sub="Liga MX Clausura" icon="trophy" />
          <Card pad={0}>
            <div style={{ display: 'flex', padding: '9px 14px', borderBottom: `1px solid ${C.border}`, fontSize: 10.5, color: C.mut, fontWeight: 700, letterSpacing: 0.4 }}>
              <span style={{ width: 22 }}>#</span><span style={{ flex: 1 }}>EQUIPO</span><span style={{ width: 34, textAlign: 'center' }}>PJ</span><span style={{ width: 38, textAlign: 'center' }}>DG</span><span style={{ width: 32, textAlign: 'center' }}>PTS</span>
            </div>
            {CF.standings.map((r, i) => (
              <div key={r.team} style={{ display: 'flex', alignItems: 'center', padding: '10px 14px', borderBottom: i < CF.standings.length - 1 ? `1px solid ${C.border}` : 'none' }}>
                <span className="num" style={{ width: 22, fontWeight: 700, fontSize: 13, color: i < 4 ? C.success : i < 6 ? C.warning : C.mut }}>{i + 1}</span>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 9 }}><Crest team={r.team} size={24} /><span style={{ fontWeight: 600, fontSize: 13.5 }}>{CF.teams[r.team].name}</span></div>
                <span className="num" style={{ width: 34, textAlign: 'center', fontSize: 13, color: C.mut }}>{r.pj}</span>
                <span className="num" style={{ width: 38, textAlign: 'center', fontSize: 13, color: C.mut }}>{r.dg > 0 ? '+' : ''}{r.dg}</span>
                <span className="num" style={{ width: 32, textAlign: 'center', fontWeight: 900, fontSize: 15 }}>{r.pts}</span>
              </div>
            ))}
          </Card>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { FantasyScreen, LeagueCard, GamesScreen, MundialScreen, StatsScreen });
