// Screens for Reale 2027 app.

// ────────────────────────────────────────────────────────────────────
// HOME — Hero + próximo partido + noticias
// ────────────────────────────────────────────────────────────────────
function ScreenHome({ onMatchClick, onNewsClick }) {
  return (
    <div style={{ padding: '12px 0 0', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div>
          <h2 style={{
            fontSize: 15, fontWeight: 700, color: '#0A1F47',
            margin: '4px 0 10px', letterSpacing: -0.3,
          }}>
            Próximo Partido
          </h2>
          <NextMatchCard match={window.NEXT_MATCH} onClick={() => onMatchClick(window.NEXT_MATCH)} />
        </div>

        <div>
          <NewsCard item={window.NEWS[0]} onClick={() => onNewsClick(window.NEWS[0])} />
        </div>
      </div>

      <SocialFooter />
      <div style={{ height: 60 }} />
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// FIXTURE — Filtros por torneo + listado (con expand/collapse por grupo)
// ────────────────────────────────────────────────────────────────────
const FIXTURE_COLLAPSED_LIMIT = 3;

function ScreenFixture({ onMatchClick }) {
  const WC = 'https://upload.wikimedia.org/wikipedia/commons/thumb';
  const groups = [
    {
      key: 'liga',
      title: 'Liga Profesional',
      logo: `${WC}/0/02/Liga_Profesional_de_F%C3%BAtbol_%28Argentina%29_logo.svg/120px-Liga_Profesional_de_F%C3%BAtbol_%28Argentina%29_logo.svg.png`,
      items: window.FIXTURE.liga,
    },
    {
      key: 'copa',
      title: 'Copa Argentina',
      logo: `${WC}/2/29/Copa_Argentina_logo.svg/120px-Copa_Argentina_logo.svg.png`,
      items: window.FIXTURE.copa,
    },
    {
      key: 'internacional',
      title: 'Copa Internacional',
      sub: '(Libertadores/Sudamericana)',
      logo: `${WC}/6/66/Copa_Libertadores_logo.svg/120px-Copa_Libertadores_logo.svg.png`,
      items: window.FIXTURE.internacional,
    },
  ];

  // Estado local: que grupos estan expandidos (mostrando todos) vs colapsados
  const [expanded, setExpanded] = React.useState({ liga: false, copa: false, internacional: false });
  const toggle = (key) => setExpanded((s) => ({ ...s, [key]: !s[key] }));

  return (
    <div style={{ padding: '4px 0 120px' }}>
      {/* Foto del plantel placeholder */}
      <TeamPhotoBanner />

      {/* Separador después de la foto */}
      <div style={{
        margin: '14px 16px 16px',
        borderTop: '1px dashed rgba(0,0,0,0.22)',
      }} />

      {/* Grupos */}
      {groups.map((g, gi) => (
        <React.Fragment key={g.key}>
          {gi > 0 && (
            <div style={{
              margin: '18px 16px 14px',
              borderTop: '1px dashed rgba(0,0,0,0.22)',
            }} />
          )}
          <div style={{
            display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
            padding: '0 16px', marginBottom: 10,
          }}>
            <h3 style={{
              fontSize: 15, fontWeight: 600, color: '#0A1F47', margin: 0,
              letterSpacing: -0.2,
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {g.logo && (
                <img
                  src={g.logo}
                  alt={g.title}
                  onError={(e) => { e.currentTarget.style.display = 'none'; }}
                  style={{
                    width: 16, height: 16, objectFit: 'contain',
                    flexShrink: 0, transform: 'translateY(2px)',
                  }}
                />
              )}
              <span>{g.title}</span>
              {g.sub && <span style={{ fontSize: 11, fontWeight: 400, color: 'rgba(0,0,0,0.55)', marginLeft: 4 }}>{g.sub}</span>}
            </h3>
            {g.items.length > FIXTURE_COLLAPSED_LIMIT && (
              <button
                type="button"
                onClick={() => toggle(g.key)}
                style={{
                  appearance: 'none', border: 'none', background: 'transparent',
                  fontSize: 12, color: '#E8A200', fontWeight: 500,
                  cursor: 'pointer', padding: 0, fontFamily: 'inherit',
                }}
              >
                {expanded[g.key] ? 'Ver menos' : `Ver todos (${g.items.length})`}
              </button>
            )}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, padding: '0 16px' }}>
            {(expanded[g.key] ? g.items : g.items.slice(0, FIXTURE_COLLAPSED_LIMIT)).map(m => (
              <MatchRow key={m.id} match={m} onClick={() => onMatchClick(m)} />
            ))}
            {g.items.length === 0 && (
              <div style={{
                padding: '16px', textAlign: 'center', color: 'rgba(0,0,0,0.45)',
                fontSize: 12.5, border: '1px dashed rgba(0,0,0,0.15)', borderRadius: 10,
              }}>Sin partidos programados en esta competencia.</div>
            )}
          </div>
        </React.Fragment>
      ))}
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// RESULTADOS
// ────────────────────────────────────────────────────────────────────
function ScreenResultados({ onMatchClick }) {
  return (
    <div style={{ padding: '0 16px 120px' }}>
      <h2 style={{
        fontSize: 18, fontWeight: 600, color: '#0A1F47',
        margin: '20px 0 16px', textAlign: 'center', letterSpacing: -0.3,
      }}>
        Ultimos Resultados
      </h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {window.RESULTS.map(r => (
          <MatchRow
            key={r.id}
            match={r}
            score={{ h: r.hs, a: r.as }}
            onClick={() => onMatchClick(r)}
          />
        ))}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// TABLA — ordenable (Pos, Pts, DG)
// ────────────────────────────────────────────────────────────────────
function ScreenTabla() {
  const rows = [...window.STANDINGS].sort((a, b) => a.pos - b.pos);

  return (
    <div style={{ padding: '0 14px 120px' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: '34px 1fr 36px 44px 44px',
        alignItems: 'center',
        padding: '14px 6px 8px',
      }}>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: '#0A1F47', textAlign: 'left' }}>Pos</div>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: '#0A1F47', textAlign: 'center' }}>Equipo</div>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: '#0A1F47', textAlign: 'center' }}>PJ</div>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: '#0A1F47', textAlign: 'center' }}>DG</div>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: '#0A1F47', textAlign: 'center' }}>Pts</div>
      </div>

      {rows.map((r, i) => (
        <div
          key={r.team}
          style={{
            display: 'grid',
            gridTemplateColumns: '34px 1fr 36px 44px 44px',
            alignItems: 'center',
            padding: '7px 6px',
            position: 'relative',
          }}
        >
          {i === 0 && (
            <div style={{
              position: 'absolute', left: -14, top: 0, bottom: 0, width: 4,
              background: '#0A1F47',
            }} />
          )}
          <div style={{
            fontSize: 12.5, fontWeight: 500, textAlign: 'left', color: '#111',
          }}>
            {r.pos}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <MiniCrest team={r.team} size={18} />
            <div style={{
              fontSize: 12.5, fontWeight: 500, color: '#111', letterSpacing: -0.1,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>
              {window.TEAMS[r.team]?.short || r.team}
            </div>
          </div>
          <div style={{ fontSize: 12, color: '#111', textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>
            {r.pj}
          </div>
          <div style={{
            fontSize: 12, textAlign: 'center', fontVariantNumeric: 'tabular-nums', color: '#111',
          }}>
            {r.dg > 0 ? '+' : ''}{r.dg}
          </div>
          <div style={{
            fontSize: 12.5, fontWeight: 600, textAlign: 'center',
            color: '#111', fontVariantNumeric: 'tabular-nums',
          }}>
            {r.pts}
          </div>
        </div>
      ))}
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// ESTADÍSTICA — secciones con título + lista
// ────────────────────────────────────────────────────────────────────
function StatList({ title, data, fmt = v => v }) {
  const [showAll, setShowAll] = React.useState(false);
  const visible = showAll ? data : data.slice(0, 5);
  return (
    <div style={{ padding: '14px 16px 10px' }}>
      <div style={{
        fontSize: 13, fontWeight: 600, color: '#111', marginBottom: 8,
        letterSpacing: -0.1,
      }}>
        {title}
      </div>
      <div>
        {visible.map((p, i) => (
          <div key={i} style={{
            display: 'grid',
            gridTemplateColumns: '36px 1fr auto',
            alignItems: 'center',
            gap: 10,
            padding: '7px 0',
          }}>
            <PlayerAvatar name={p.name} size={32} photo={p.photo} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 12.5, color: '#111', lineHeight: 1.2 }}>
                <span style={{ fontWeight: 700 }}>{p.name}</span>
                <span style={{ color: 'rgba(0,0,0,0.6)', marginLeft: 6 }}>{p.role}</span>
              </div>
              <div style={{ fontSize: 11, color: 'rgba(0,0,0,0.55)', marginTop: 1 }}>
                {p.country}
              </div>
            </div>
            <div style={{
              fontSize: 14, fontWeight: 700, color: '#111',
              fontVariantNumeric: 'tabular-nums',
            }}>
              {fmt(p.val)}
            </div>
          </div>
        ))}
      </div>
      {data.length > 5 && (
        <button
          type="button"
          onClick={() => setShowAll(s => !s)}
          style={{
            width: '100%', appearance: 'none', border: 'none',
            background: 'transparent', padding: '6px 0 0',
            fontFamily: 'inherit', fontSize: 11.5, fontWeight: 500,
            color: 'rgba(0,0,0,0.6)', cursor: 'pointer',
            textAlign: 'center',
          }}
        >
          {showAll ? 'Ver menos ⌃' : 'Ver más ⌄'}
        </button>
      )}
    </div>
  );
}

function ScreenEstadistica() {
  const stats = window.STATS || { goles: [], asistencias: [], amarillas: [] };
  const empty = (stats.goles?.length || 0) === 0
             && (stats.asistencias?.length || 0) === 0
             && (stats.amarillas?.length || 0) === 0;

  return (
    <div style={{ padding: '0 0 120px' }}>
      {/* Header: equipo + torneo */}
      <div style={{
        width: '100%', padding: '14px 16px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 22, height: 22, borderRadius: 4,
            background: 'linear-gradient(180deg, #0D2E6B, #0A2457)',
            color: '#F5B01E',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: '"Archivo Black", system-ui', fontSize: 9, fontWeight: 900,
          }}>CAB</div>
          <span style={{ fontSize: 13.5, fontWeight: 700, color: '#0A1F47', lineHeight: 1.2 }}>
            Boca Juniors
            <span style={{
              display: 'block', fontSize: 10.5, fontWeight: 500,
              color: 'rgba(0,0,0,0.55)', letterSpacing: 0.2,
            }}>
              Liga Profesional Argentina · 2024
            </span>
          </span>
        </span>
      </div>

      <div style={{ borderTop: '1px solid rgba(0,0,0,0.08)' }} />

      {empty ? (
        <div style={{
          margin: '20px 16px', padding: '20px 16px',
          border: '1px dashed rgba(0,0,0,0.15)', borderRadius: 10,
          textAlign: 'center', color: 'rgba(0,0,0,0.55)',
          fontSize: 12.5, lineHeight: 1.5,
        }}>
          No hay estadisticas disponibles para Boca en esta temporada.
          <br />
          <span style={{ fontSize: 11, opacity: 0.7 }}>
            (Verifica que el backend este conectado a la API)
          </span>
        </div>
      ) : (
        <>
          <StatList title="Goles" data={stats.goles || []} />
          <div style={{ borderTop: '1px solid rgba(0,0,0,0.08)', margin: '0 16px' }} />
          <StatList title="Asistencias" data={stats.asistencias || []} />
          <div style={{ borderTop: '1px solid rgba(0,0,0,0.08)', margin: '0 16px' }} />
          <StatList title="Tarjetas amarillas" data={stats.amarillas || []} />
        </>
      )}
    </div>
  );
}

Object.assign(window, { ScreenHome, ScreenFixture, ScreenResultados, ScreenTabla, ScreenEstadistica });
