/* App modal screens — Partidos / Cursos / Alto Rendimiento */

const ms = {
  body: {
    padding: 0,
    background: 'var(--navy-deep)',
    color: 'var(--ink)',
    fontFamily: 'inherit',
  },
  // shared layout
  toolbar: {
    display: 'flex',
    alignItems: 'center',
    gap: 12,
    padding: '14px 24px',
    borderBottom: '1px solid var(--hairline)',
    fontSize: 13,
    color: 'var(--ink-dim)',
    flexWrap: 'wrap',
  },
  pill: {
    padding: '6px 12px',
    borderRadius: 999,
    fontSize: 12,
    fontWeight: 500,
    border: '1px solid var(--hairline-strong)',
    background: 'transparent',
    color: 'var(--ink-dim)',
    cursor: 'pointer',
    transition: 'all 180ms',
    fontFamily: 'inherit',
  },
  pillActive: {
    background: 'var(--accent)',
    color: 'var(--navy-deep)',
    borderColor: 'var(--accent)',
  },
  search: {
    flex: 1,
    minWidth: 200,
    padding: '8px 14px',
    borderRadius: 8,
    border: '1px solid var(--hairline-strong)',
    background: 'rgba(0, 22, 32,0.5)',
    color: 'var(--ink)',
    fontFamily: 'inherit',
    fontSize: 13,
  },
};

/* ───── PARTIDOS ───── */
const PartidosScreen = () => {
  const [filter, setFilter] = React.useState('Todos');
  const [search, setSearch] = React.useState('');
  const filters = ['Todos', 'Próximos', 'En curso', 'Finalizados'];

  const matches = [
    { id: 1, home: 'Hindú Club', away: 'CASI', league: 'URBA Top 12', date: 'Sáb 16/05', time: '15:30', status: 'live', s1: 14, s2: 11, venue: 'Cancha Don Bosco' },
    { id: 2, home: 'SIC', away: 'Belgrano AC', league: 'URBA Top 12', date: 'Sáb 16/05', time: '17:00', status: 'upcoming', s1: '—', s2: '—', venue: 'Estadio SIC' },
    { id: 3, home: 'Newman', away: 'Alumni', league: 'URBA Top 12', date: 'Dom 17/05', time: '15:30', status: 'upcoming', s1: '—', s2: '—', venue: 'Newman Park' },
    { id: 4, home: 'Tucumán RC', away: 'Los Tarcos', league: 'URT Anual', date: 'Vie 15/05', time: '21:00', status: 'finished', s1: 22, s2: 19, venue: 'Tucumán RC' },
    { id: 5, home: 'Marista (R)', away: 'Jockey CC', league: 'URC Anual', date: 'Sáb 16/05', time: '16:00', status: 'finished', s1: 28, s2: 14, venue: 'Marista' },
  ];

  const filtered = matches.filter(m => {
    const fok = filter === 'Todos' ||
      (filter === 'Próximos' && m.status === 'upcoming') ||
      (filter === 'En curso' && m.status === 'live') ||
      (filter === 'Finalizados' && m.status === 'finished');
    const sok = !search ||
      `${m.home} ${m.away} ${m.league}`.toLowerCase().includes(search.toLowerCase());
    return fok && sok;
  });

  return (
    <div style={ms.body}>
      <div style={ms.toolbar}>
        {filters.map(f => (
          <button
            key={f}
            style={{ ...ms.pill, ...(filter === f ? ms.pillActive : {}) }}
            onClick={() => setFilter(f)}
          >{f}</button>
        ))}
        <input
          style={ms.search}
          placeholder="Buscar club, unión o torneo…"
          value={search}
          onChange={e => setSearch(e.target.value)}
        />
      </div>

      <div style={{ padding: 24, display: 'grid', gap: 12 }}>
        {filtered.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-mute)', fontSize: 13 }}>
            No hay partidos con ese filtro.
          </div>
        )}
        {filtered.map(m => <MatchRow key={m.id} m={m} />)}
      </div>

      <div style={{ padding: '0 24px 24px' }}>
        <div style={{
          padding: 20,
          borderRadius: 14,
          border: '1px solid var(--hairline)',
          background: 'rgba(0, 22, 32,0.4)',
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          gap: 16,
        }}>
          {[
            ['1.247', 'Partidos cargados'],
            ['89', 'Clubes activos'],
            ['24', 'Uniones provinciales'],
            ['3.812', 'Jugadores fichados'],
          ].map(([n, l]) => (
            <div key={l}>
              <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--accent)', letterSpacing: '-0.02em' }}>{n}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 4 }}>{l}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const MatchRow = ({ m }) => {
  const statusBadge = {
    live: { label: 'EN VIVO', color: '#ff5252' },
    upcoming: { label: 'PRÓXIMO', color: 'var(--sky)' },
    finished: { label: 'FINAL', color: 'var(--ink-mute)' },
  }[m.status];

  return (
    <div style={{
      padding: 18,
      borderRadius: 12,
      border: '1px solid var(--hairline)',
      background: m.status === 'live' ? 'rgba(255,82,82,0.06)' : 'rgba(0, 22, 32,0.5)',
      display: 'grid',
      gridTemplateColumns: '120px 1fr auto',
      gap: 18,
      alignItems: 'center',
    }}>
      <div>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.16em', color: statusBadge.color, display: 'flex', alignItems: 'center', gap: 6 }}>
          {m.status === 'live' && <span style={{ width: 6, height: 6, borderRadius: '50%', background: statusBadge.color, animation: 'pulse 1.4s infinite' }} />}
          {statusBadge.label}
        </div>
        <div style={{ fontSize: 13, fontWeight: 600, marginTop: 4 }}>{m.date}</div>
        <div style={{ fontSize: 12, color: 'var(--ink-mute)' }}>{m.time}</div>
      </div>

      <div>
        <div style={{ fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 6 }}>{m.league}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 1 }}>
            <ClubBadge name={m.home} />
            <div style={{ fontSize: 15, fontWeight: 600 }}>{m.home}</div>
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, fontFamily: 'JetBrains Mono, monospace', color: m.status === 'live' ? '#ff5252' : 'var(--ink)' }}>
            {m.s1} <span style={{ color: 'var(--ink-faint)', fontWeight: 400 }}>·</span> {m.s2}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 1, justifyContent: 'flex-end' }}>
            <div style={{ fontSize: 15, fontWeight: 600 }}>{m.away}</div>
            <ClubBadge name={m.away} />
          </div>
        </div>
        <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 8, letterSpacing: '0.06em' }}>📍 {m.venue}</div>
      </div>

      <button style={{
        padding: '10px 16px',
        borderRadius: 999,
        border: '1px solid var(--hairline-strong)',
        background: 'transparent',
        color: 'var(--ink)',
        fontSize: 12,
        fontWeight: 500,
        cursor: 'pointer',
        fontFamily: 'inherit',
      }}>Ver detalle</button>
    </div>
  );
};

const ClubBadge = ({ name }) => {
  const initials = name.split(/\s|\(/).filter(Boolean).slice(0, 2).map(s => s[0]).join('').toUpperCase();
  // hash to a hue
  let h = 0;
  for (let i = 0; i < name.length; i++) h = name.charCodeAt(i) + ((h << 5) - h);
  const hue = Math.abs(h) % 360;
  return (
    <div style={{
      width: 36, height: 36,
      borderRadius: 10,
      background: `linear-gradient(135deg, hsl(${hue}, 30%, 30%), hsl(${(hue + 30) % 360}, 30%, 18%))`,
      border: '1px solid var(--hairline-strong)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 11, fontWeight: 700,
      fontFamily: 'JetBrains Mono, monospace',
      letterSpacing: '0.04em',
      flexShrink: 0,
    }}>{initials}</div>
  );
};

/* ───── CURSOS ───── */
const CursosScreen = () => {
  const [cat, setCat] = React.useState('Todos');
  const cats = ['Todos', 'Entrenadores', 'Médicos', 'Referees', 'Dirigentes'];
  const courses = [
    { title: 'Fundamentos del juego en menores', cat: 'Entrenadores', mod: 8, hrs: 12, lvl: 'Inicial', enrolled: 412, progress: null, instructor: 'Staff UAR Capacitación' },
    { title: 'Concusiones y protocolo HIA', cat: 'Médicos', mod: 6, hrs: 9, lvl: 'Avanzado', enrolled: 234, progress: 65, instructor: 'Dr. M. González' },
    { title: 'Reglamento World Rugby 2025', cat: 'Referees', mod: 12, hrs: 18, lvl: 'Intermedio', enrolled: 187, progress: null, instructor: 'A. Domínguez' },
    { title: 'Gestión de clubes amateurs', cat: 'Dirigentes', mod: 5, hrs: 8, lvl: 'Inicial', enrolled: 156, progress: 30, instructor: 'L. Fernández' },
    { title: 'Preparación física por edades', cat: 'Entrenadores', mod: 10, hrs: 15, lvl: 'Intermedio', enrolled: 318, progress: null, instructor: 'P. Martínez' },
    { title: 'Nutrición deportiva en rugby', cat: 'Médicos', mod: 4, hrs: 6, lvl: 'Inicial', enrolled: 198, progress: null, instructor: 'Lic. R. Páez' },
  ];
  const filtered = cat === 'Todos' ? courses : courses.filter(c => c.cat === cat);

  return (
    <div style={ms.body}>
      <div style={ms.toolbar}>
        {cats.map(c => (
          <button
            key={c}
            style={{ ...ms.pill, ...(cat === c ? ms.pillActive : {}) }}
            onClick={() => setCat(c)}
          >{c}</button>
        ))}
      </div>

      {/* Featured course */}
      <div style={{ padding: 24 }}>
        <div style={{
          borderRadius: 14,
          border: '1px solid var(--accent)',
          background: 'linear-gradient(135deg, rgba(200, 146, 17,0.12), rgba(0, 22, 32,0.5))',
          padding: 24,
          display: 'grid',
          gridTemplateColumns: '1fr auto',
          gap: 20,
          alignItems: 'center',
          marginBottom: 24,
        }}>
          <div>
            <div style={{ fontSize: 10, color: 'var(--accent)', letterSpacing: '0.18em', fontWeight: 600, marginBottom: 8 }}>★ DESTACADO · INSCRIPCIÓN ABIERTA</div>
            <div style={{ fontSize: 22, fontWeight: 700, marginBottom: 6, letterSpacing: '-0.01em' }}>Formación Nivel 1 — Entrenadores de Rugby Infantil</div>
            <div style={{ fontSize: 13, color: 'var(--ink-dim)', lineHeight: 1.5, maxWidth: 560 }}>
              Curso 100% online + 2 instancias presenciales regionales. Certificación oficial UAR.
            </div>
            <div style={{ display: 'flex', gap: 24, marginTop: 14, fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.08em' }}>
              <span>14 MÓDULOS</span><span>·</span><span>22 HS</span><span>·</span><span>INICIO 02/06</span>
            </div>
          </div>
          <button style={{
            padding: '14px 24px',
            borderRadius: 999,
            background: 'var(--accent)',
            color: 'var(--navy-deep)',
            border: 'none',
            fontWeight: 600,
            fontSize: 13,
            cursor: 'pointer',
            fontFamily: 'inherit',
          }}>Inscribirme</button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14 }}>
          {filtered.map((c, i) => <CourseCard key={i} c={c} />)}
        </div>
      </div>
    </div>
  );
};

const CourseCard = ({ c }) => (
  <div style={{
    borderRadius: 12,
    border: '1px solid var(--hairline)',
    background: 'rgba(0, 22, 32,0.4)',
    padding: 18,
    cursor: 'pointer',
    transition: 'border-color 200ms, transform 200ms',
  }}
    onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--hairline-strong)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
    onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--hairline)'; e.currentTarget.style.transform = 'none'; }}
  >
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: 12 }}>
      <div style={{ fontSize: 10, color: 'var(--accent)', letterSpacing: '0.16em', fontWeight: 600 }}>{c.cat.toUpperCase()}</div>
      <div style={{ fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '0.12em' }}>{c.lvl}</div>
    </div>
    <div style={{ fontSize: 15, fontWeight: 600, lineHeight: 1.3, marginBottom: 8, minHeight: 40 }}>{c.title}</div>
    <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginBottom: 14 }}>{c.instructor}</div>

    <div style={{ display: 'flex', gap: 14, fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--ink-dim)', letterSpacing: '0.06em', borderTop: '1px solid var(--hairline)', paddingTop: 12 }}>
      <span>{c.mod} MÓD</span>
      <span>{c.hrs} HS</span>
      <span style={{ marginLeft: 'auto' }}>👥 {c.enrolled}</span>
    </div>

    {c.progress !== null && (
      <div style={{ marginTop: 12 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '0.08em', marginBottom: 6 }}>
          <span>EN CURSO</span>
          <span>{c.progress}%</span>
        </div>
        <div style={{ height: 4, background: 'var(--hairline)', borderRadius: 2, overflow: 'hidden' }}>
          <div style={{ width: `${c.progress}%`, height: '100%', background: 'var(--accent)' }} />
        </div>
      </div>
    )}
  </div>
);

/* ───── ALTO RENDIMIENTO ───── */
const RendimientoScreen = () => {
  const [tab, setTab] = React.useState('Tablero');
  const tabs = ['Tablero', 'Atletas', 'Sesiones'];
  return (
    <div style={ms.body}>
      <div style={ms.toolbar}>
        {tabs.map(t => (
          <button
            key={t}
            style={{ ...ms.pill, ...(tab === t ? ms.pillActive : {}) }}
            onClick={() => setTab(t)}
          >{t}</button>
        ))}
        <div style={{ flex: 1 }} />
        <div style={{ fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.1em', fontFamily: 'JetBrains Mono, monospace' }}>
          ÚLTIMA SINC · HACE 4 MIN
        </div>
      </div>
      <div style={{ padding: 24 }}>
        {tab === 'Tablero' && <RendDashboard />}
        {tab === 'Atletas' && <RendAtletas />}
        {tab === 'Sesiones' && <RendSesiones />}
      </div>
    </div>
  );
};

const RendDashboard = () => {
  const kpis = [
    { lbl: 'Carga semanal', val: '4.820', unit: 'UA', delta: '+8%', good: true },
    { lbl: 'RPE promedio', val: '6.4', unit: '/10', delta: '−0.3', good: true },
    { lbl: 'Disponibles', val: '34', unit: '/38', delta: '89%', good: true },
    { lbl: 'En recuperación', val: '4', unit: 'jug.', delta: '−1', good: true },
  ];

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 18 }}>
        {kpis.map(k => (
          <div key={k.lbl} style={{
            padding: 18,
            borderRadius: 12,
            border: '1px solid var(--hairline)',
            background: 'rgba(0, 22, 32,0.5)',
          }}>
            <div style={{ fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>{k.lbl}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 8 }}>
              <span style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.02em' }}>{k.val}</span>
              <span style={{ fontSize: 11, color: 'var(--ink-mute)' }}>{k.unit}</span>
            </div>
            <div style={{ fontSize: 11, color: k.good ? 'var(--accent)' : '#ff5252', marginTop: 6, fontFamily: 'JetBrains Mono, monospace' }}>{k.delta}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 14 }}>
        <div style={{ padding: 22, borderRadius: 12, border: '1px solid var(--hairline)', background: 'rgba(0, 22, 32,0.5)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
            <div>
              <div style={{ fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>Carga de entrenamiento · 8 sem</div>
              <div style={{ fontSize: 16, fontWeight: 700, marginTop: 4 }}>Plantel completo</div>
            </div>
            <div style={{ fontSize: 11, color: 'var(--ink-mute)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em' }}>UA / SEMANA</div>
          </div>
          <LoadChart />
        </div>

        <div style={{ padding: 22, borderRadius: 12, border: '1px solid var(--hairline)', background: 'rgba(0, 22, 32,0.5)' }}>
          <div style={{ fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 18 }}>Estado del plantel</div>
          {[
            ['Apto pleno', 30, 'var(--accent)'],
            ['Carga restringida', 4, 'var(--sky)'],
            ['Fisioterapia', 3, '#ff8a3d'],
            ['Lesionado', 1, '#ff5252'],
          ].map(([lbl, n, color]) => (
            <div key={lbl} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: color }} />
              <span style={{ fontSize: 13, flex: 1 }}>{lbl}</span>
              <span style={{ fontSize: 14, fontWeight: 700, fontFamily: 'JetBrains Mono, monospace' }}>{n}</span>
              <div style={{ width: 80, height: 4, background: 'var(--hairline)', borderRadius: 2, overflow: 'hidden' }}>
                <div style={{ width: `${(n / 38) * 100}%`, height: '100%', background: color }} />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const LoadChart = () => {
  const data = [3200, 4100, 4800, 4200, 5100, 4900, 5300, 4820];
  const max = 5500;
  return (
    <svg viewBox="0 0 600 180" style={{ width: '100%', height: 180 }}>
      <defs>
        <linearGradient id="loadGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.4" />
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0, 1, 2, 3].map(i => (
        <line key={i} x1="0" x2="600" y1={i * 45} y2={i * 45} stroke="var(--hairline)" strokeWidth="1" />
      ))}
      <path
        d={`M 0 ${180 - (data[0] / max) * 180} ${data.map((d, i) => `L ${(i / (data.length - 1)) * 600} ${180 - (d / max) * 180}`).join(' ')} L 600 180 L 0 180 Z`}
        fill="url(#loadGrad)"
      />
      <path
        d={`M 0 ${180 - (data[0] / max) * 180} ${data.map((d, i) => `L ${(i / (data.length - 1)) * 600} ${180 - (d / max) * 180}`).join(' ')}`}
        fill="none"
        stroke="var(--accent)"
        strokeWidth="2"
      />
      {data.map((d, i) => (
        <circle key={i}
          cx={(i / (data.length - 1)) * 600}
          cy={180 - (d / max) * 180}
          r="3.5"
          fill={i === data.length - 1 ? 'var(--accent)' : 'var(--navy-deep)'}
          stroke="var(--accent)"
          strokeWidth="1.5"
        />
      ))}
    </svg>
  );
};

const RendAtletas = () => {
  const athletes = [
    { name: 'M. Rodríguez', pos: 'Apertura', age: 23, load: 92, rpe: 6, status: 'apto' },
    { name: 'J. Pereyra', pos: 'Pilar', age: 28, load: 78, rpe: 7, status: 'apto' },
    { name: 'F. Sánchez', pos: 'Wing', age: 21, load: 64, rpe: 5, status: 'restringido' },
    { name: 'A. Gómez', pos: 'Hooker', age: 26, load: 88, rpe: 7, status: 'apto' },
    { name: 'D. Marini', pos: 'Centro', age: 25, load: 0, rpe: '—', status: 'fisio' },
    { name: 'L. Vidal', pos: '8º', age: 24, load: 82, rpe: 6, status: 'apto' },
    { name: 'P. Fernández', pos: 'Fullback', age: 27, load: 75, rpe: 6, status: 'apto' },
    { name: 'N. Costa', pos: 'Segunda línea', age: 22, load: 90, rpe: 8, status: 'apto' },
  ];
  const sCol = { apto: 'var(--accent)', restringido: 'var(--sky)', fisio: '#ff8a3d', lesionado: '#ff5252' };
  return (
    <div style={{ borderRadius: 12, border: '1px solid var(--hairline)', overflow: 'hidden' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: '2fr 1.2fr 0.6fr 1fr 0.6fr 1fr',
        gap: 14,
        padding: '12px 18px',
        background: 'rgba(0, 22, 32,0.6)',
        fontSize: 10,
        color: 'var(--ink-mute)',
        letterSpacing: '0.14em',
        textTransform: 'uppercase',
        fontWeight: 600,
      }}>
        <div>Jugador</div><div>Posición</div><div>Edad</div><div>Carga</div><div>RPE</div><div>Estado</div>
      </div>
      {athletes.map((a, i) => (
        <div key={a.name} style={{
          display: 'grid',
          gridTemplateColumns: '2fr 1.2fr 0.6fr 1fr 0.6fr 1fr',
          gap: 14,
          padding: '14px 18px',
          alignItems: 'center',
          fontSize: 13,
          borderTop: i ? '1px solid var(--hairline)' : 'none',
          background: i % 2 ? 'rgba(0, 22, 32,0.2)' : 'transparent',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <ClubBadge name={a.name} />
            <span style={{ fontWeight: 500 }}>{a.name}</span>
          </div>
          <div style={{ color: 'var(--ink-dim)' }}>{a.pos}</div>
          <div style={{ fontFamily: 'JetBrains Mono, monospace' }}>{a.age}</div>
          <div>
            <div style={{ height: 4, background: 'var(--hairline)', borderRadius: 2, overflow: 'hidden', maxWidth: 100 }}>
              <div style={{ width: `${a.load}%`, height: '100%', background: 'var(--accent)' }} />
            </div>
          </div>
          <div style={{ fontFamily: 'JetBrains Mono, monospace' }}>{a.rpe}</div>
          <div>
            <span style={{
              fontSize: 10, fontWeight: 600, letterSpacing: '0.12em',
              padding: '4px 10px', borderRadius: 999,
              background: `${sCol[a.status]}22`,
              color: sCol[a.status],
              textTransform: 'uppercase',
            }}>{a.status}</span>
          </div>
        </div>
      ))}
    </div>
  );
};

const RendSesiones = () => {
  const week = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'];
  const sessions = {
    'Lun': [{ t: '08:00', n: 'Gimnasio · Tren superior', dur: 60, type: 'fuerza' }, { t: '17:00', n: 'Campo · Skills', dur: 90, type: 'tecnica' }],
    'Mar': [{ t: '17:00', n: 'Velocidad + scrum', dur: 75, type: 'tecnica' }],
    'Mié': [{ t: '08:00', n: 'Gimnasio · Tren inferior', dur: 60, type: 'fuerza' }, { t: '17:30', n: 'Tactica · Defensa', dur: 90, type: 'tactica' }],
    'Jue': [{ t: '17:00', n: 'Recuperación activa', dur: 45, type: 'recup' }],
    'Vie': [{ t: '17:00', n: 'Captain\'s run', dur: 60, type: 'tactica' }],
    'Sáb': [{ t: '15:30', n: 'PARTIDO vs CASI', dur: 80, type: 'partido' }],
    'Dom': [],
  };
  const colors = { fuerza: 'var(--accent)', tecnica: 'var(--sky)', tactica: '#b48dde', recup: '#5fc89c', partido: '#ff5252' };
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8 }}>
      {week.map(d => (
        <div key={d} style={{
          borderRadius: 10,
          border: '1px solid var(--hairline)',
          background: 'rgba(0, 22, 32,0.4)',
          minHeight: 240,
          padding: 12,
        }}>
          <div style={{ fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 12, paddingBottom: 8, borderBottom: '1px solid var(--hairline)' }}>{d}</div>
          {sessions[d].map((s, i) => (
            <div key={i} style={{
              padding: 10,
              borderRadius: 8,
              background: `${colors[s.type]}1f`,
              borderLeft: `3px solid ${colors[s.type]}`,
              marginBottom: 8,
            }}>
              <div style={{ fontSize: 10, fontFamily: 'JetBrains Mono, monospace', color: colors[s.type], letterSpacing: '0.08em', marginBottom: 4 }}>{s.t} · {s.dur}'</div>
              <div style={{ fontSize: 12, fontWeight: 500, lineHeight: 1.3 }}>{s.n}</div>
            </div>
          ))}
          {sessions[d].length === 0 && <div style={{ fontSize: 11, color: 'var(--ink-faint)', fontStyle: 'italic', marginTop: 12 }}>Descanso</div>}
        </div>
      ))}
    </div>
  );
};

/* App access landing screens — accessed via modal from the ecosystem */

const ACCESS_INFO = {
  partidos: {
    title: 'Partidos',
    tag: 'APP 01 · GESTIÓN',
    headline: 'Más de 1.000 partidos por semana, administrados de forma digital.',
    body: 'Ficha electrónica, control de disciplina, gestión de incidencias y bienestar del jugador. +800 conmociones gestionadas y +7.000 torneos administrados desde la implementación del sistema.',
    web: { url: 'https://partidos.conecta.rugby', label: 'partidos.conecta.rugby', available: false },
    ios: { url: '#', available: false },
    android: { url: '#', available: false },
  },
  cursos: {
    title: 'Coaching',
    tag: 'APP 02 · CAPACITACIÓN',
    headline: 'La plataforma central de formación continua del rugby sudamericano.',
    body: 'Cursos online con contenidos oficiales de la UAR y World Rugby, biblioteca de recursos didácticos e integración directa con BD UAR para validar acreditaciones. +50 cursos activos y +100.000 cursos aprobados.',
    web: { url: 'cursos.conecta.html', label: 'cursos.conecta.rugby', available: true },
    ios: { url: '#', available: false },
    android: { url: '#', available: false },
  },
  rendimiento: {
    title: 'Alto Rendimiento',
    tag: 'APP 03 · DESARROLLO',
    headline: 'Seguimiento del jugador en academias y centros nacionales.',
    body: 'Sistema HP que acompaña al jugador en su nueva etapa de competencia. 25 academias y centros de formación, +500 jugadores y jugadoras, +80 profesionales (técnico, físico, nutricional, médico y psicológico).',
    web: { url: 'https://rendimiento.conecta.rugby', label: 'rendimiento.conecta.rugby', available: false },
    ios: { url: '#', available: false },
    android: { url: '#', available: false },
  },
};

const AccessScreen = ({ appId, PreviewScreen, IconCmp }) => {
  const info = ACCESS_INFO[appId];
  return (
    <div style={{ background: 'var(--navy-deep)', color: 'var(--ink)' }}>
      {/* Hero band */}
      <div style={{
        padding: '40px 32px 32px',
        borderBottom: '1px solid var(--hairline)',
        background: 'radial-gradient(ellipse 60% 80% at 80% 50%, rgba(200, 146, 17,0.08), transparent 70%)',
      }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 40, alignItems: 'center' }}>
          <div>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 10,
              fontFamily: 'var(--font-mono)', fontSize: 11,
              color: 'var(--accent)', letterSpacing: '0.18em',
              textTransform: 'uppercase', marginBottom: 16,
            }}>
              <span style={{
                width: 6, height: 6, borderRadius: '50%',
                background: info.web.available ? 'var(--accent)' : 'var(--ink-faint)',
                boxShadow: info.web.available ? '0 0 8px var(--accent)' : 'none',
              }} />
              {info.web.available ? 'DISPONIBLE AHORA' : 'PRÓXIMAMENTE · BETA'}
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.1, marginBottom: 12 }}>
              {info.title}
            </div>
            <div style={{ fontFamily: 'var(--font-gotham)', fontSize: 16, color: 'var(--ink-dim)', lineHeight: 1.5, marginBottom: 8 }}>
              {info.headline}
            </div>
            <div style={{ fontFamily: 'var(--font-gotham)', fontSize: 14, color: 'var(--ink-mute)', lineHeight: 1.55, maxWidth: 520, marginBottom: 24 }}>
              {info.body}
            </div>

            {/* Access options */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxWidth: 460 }}>
              <a
                href={info.web.url}
                target={info.web.url.startsWith('http') ? '_blank' : '_self'}
                rel="noopener noreferrer"
                onClick={(e) => { if (!info.web.available) e.preventDefault(); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  padding: '14px 18px',
                  borderRadius: 12,
                  background: info.web.available ? 'var(--accent)' : 'rgba(0, 22, 32,0.4)',
                  color: info.web.available ? 'var(--navy-deep)' : 'var(--ink-mute)',
                  border: info.web.available ? '1px solid var(--accent)' : '1px solid var(--hairline)',
                  textDecoration: 'none',
                  cursor: info.web.available ? 'pointer' : 'not-allowed',
                  transition: 'transform 180ms',
                }}
                onMouseEnter={e => { if (info.web.available) e.currentTarget.style.transform = 'translateY(-1px)'; }}
                onMouseLeave={e => { e.currentTarget.style.transform = 'none'; }}
              >
                <span style={{
                  width: 36, height: 36, borderRadius: 10,
                  background: info.web.available ? 'rgba(0, 22, 32,0.15)' : 'rgba(255,255,255,0.06)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                }}>
                  <Icons.globe style={{ width: 18, height: 18 }} />
                </span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.75, fontFamily: 'var(--font-mono)' }}>
                    {info.web.available ? 'Acceder a la plataforma' : 'Plataforma web'}
                  </div>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, marginTop: 3 }}>
                    {info.web.label}
                  </div>
                </div>
                <Icons.arrow style={{ width: 18, height: 18 }} />
              </a>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <StoreButton kind="ios" available={info.ios.available} url={info.ios.url} />
                <StoreButton kind="android" available={info.android.available} url={info.android.url} />
              </div>
            </div>

          </div>

          {/* Device frame preview */}
          <DeviceFrame IconCmp={IconCmp} title={info.title} />
        </div>
      </div>
    </div>
  );
};

const StoreButton = ({ kind, available, url }) => {
  const isIos = kind === 'ios';
  const top = isIos ? 'Descargar en' : 'Conseguir en';
  const name = isIos ? 'App Store' : 'Google Play';
  return (
    <a
      href={url}
      target="_blank"
      rel="noopener noreferrer"
      onClick={(e) => { if (!available) e.preventDefault(); }}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '12px 14px',
        borderRadius: 12,
        background: 'rgba(0, 22, 32,0.5)',
        border: '1px solid var(--hairline-strong)',
        color: 'var(--ink)',
        textDecoration: 'none',
        opacity: available ? 1 : 0.55,
        cursor: available ? 'pointer' : 'not-allowed',
        transition: 'border-color 180ms',
      }}
      onMouseEnter={e => { if (available) e.currentTarget.style.borderColor = 'var(--accent)'; }}
      onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--hairline-strong)'; }}
    >
      <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: 22, height: 22, flexShrink: 0 }}>
        {isIos ? (
          <path d="M16.4 12.6c0-2.3 1.9-3.4 2-3.5-1.1-1.6-2.8-1.8-3.4-1.8-1.4-.1-2.8.8-3.5.8-.7 0-1.9-.8-3.1-.8-1.6 0-3.1.9-3.9 2.4-1.7 2.9-.4 7.2 1.2 9.6.8 1.2 1.7 2.5 2.9 2.4 1.2 0 1.6-.7 3-.7 1.4 0 1.8.7 3.1.7 1.3 0 2.1-1.2 2.9-2.4.9-1.4 1.3-2.7 1.3-2.8-.1 0-2.5-1-2.5-3.9zM14.1 5.7c.6-.8 1.1-1.9 1-3-1 0-2.1.7-2.8 1.5-.6.7-1.2 1.8-1 2.9 1.1 0 2.2-.6 2.8-1.4z" />
        ) : (
          <path d="M5.4 2.7c-.4.4-.6 1-.6 1.7v15.2c0 .7.2 1.3.6 1.7l8.6-9.3-8.6-9.3zm9.5 8.3l2.7-2.9-9.7-5.4 7 8.3zm0 1.2l-7 8.3 9.7-5.4-2.7-2.9zm5-2.4l-2.7-1.5-3 3 3 3 2.7-1.5c1.1-.6 1.1-2.4 0-3z" />
        )}
      </svg>
      <div style={{ lineHeight: 1.1 }}>
        <div style={{ fontSize: 9.5, color: 'var(--ink-mute)', letterSpacing: '0.08em', textTransform: 'uppercase', fontFamily: 'var(--font-mono)' }}>{top}</div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, marginTop: 2 }}>{name}</div>
        {!available && <div style={{ fontSize: 9, color: 'var(--accent)', marginTop: 2, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em' }}>PRÓXIMAMENTE</div>}
      </div>
    </a>
  );
};

const DeviceFrame = ({ IconCmp, title }) => (
  <div style={{
    position: 'relative',
    aspectRatio: '9 / 14',
    maxWidth: 240,
    margin: '0 auto',
    borderRadius: 32,
    border: '1px solid var(--hairline-strong)',
    background: 'linear-gradient(160deg, rgba(37, 50, 75,0.25), rgba(0, 22, 32,0.7))',
    padding: 10,
    boxShadow: '0 30px 60px rgba(0,0,0,0.5), 0 0 60px rgba(200, 146, 17,0.08)',
  }}>
    <div style={{
      position: 'absolute', top: 6, left: '50%', transform: 'translateX(-50%)',
      width: 60, height: 16, borderRadius: 999,
      background: 'rgba(0,12,24,0.9)',
    }} />
    <div style={{
      width: '100%', height: '100%',
      borderRadius: 24,
      background: 'linear-gradient(180deg, rgba(0, 22, 32,0.95), rgba(0,8,18,1))',
      border: '1px solid var(--hairline)',
      display: 'flex', flexDirection: 'column',
      padding: '32px 18px 18px',
      overflow: 'hidden',
      position: 'relative',
    }}>
      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 8.5,
        color: 'var(--ink-mute)', letterSpacing: '0.16em',
        textAlign: 'center', textTransform: 'uppercase', marginBottom: 18,
      }}>conecta.rugby / {title.toLowerCase()}</div>
      <div style={{
        margin: '0 auto 14px',
        width: 72, height: 72,
        borderRadius: 22,
        background: 'radial-gradient(circle at 30% 30%, var(--navy-soft), var(--navy))',
        border: '1px solid var(--hairline-strong)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: 'var(--accent)',
        boxShadow: '0 8px 24px rgba(0,0,0,0.4), 0 0 24px rgba(200, 146, 17,0.15)',
      }}>
        <IconCmp style={{ width: 32, height: 32 }} />
      </div>
      <div style={{ textAlign: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, marginBottom: 4 }}>{title}</div>
      <div style={{ textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 8, color: 'var(--ink-mute)', letterSpacing: '0.14em' }}>BY CONECTA.RUGBY</div>
      <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 6 }}>
        {[1, 2, 3].map(i => (
          <div key={i} style={{
            height: 22, borderRadius: 7,
            background: i === 1 ? 'rgba(200, 146, 17,0.15)' : 'rgba(255,255,255,0.04)',
            border: '1px solid var(--hairline)',
          }} />
        ))}
      </div>
    </div>
  </div>
);

Object.assign(window, { PartidosScreen, CursosScreen, RendimientoScreen, AccessScreen, ACCESS_INFO });
