// ═══════════════ EQUIPE DETAIL PAGE (LIVE) ═══════════════
// Reads ?team=<name> from URL hash → fetches /public/teams-full + matches
const EquipeDetailPage = () => {
  const { data: teams, loading: lt } = useApi('/public/teams-full', []);
  const { data: matches } = useApi('/public/matches', []);

  // team name from hash like "#equipe?team=Iron+Howl"
  const params = new URLSearchParams((location.hash.split('?')[1] || ''));
  const teamName = params.get('team');

  if (lt) return <div className="page-frame grain" data-screen-label="EquipeDetail"><CZFHeader active="equipes" /><main style={{ padding: '2rem 2.5rem' }}><Loading /></main></div>;

  const team = (teams || []).find(t => t.team_name === teamName) || (teams || [])[0];
  if (!team) return (
    <div className="page-frame grain" data-screen-label="EquipeDetail">
      <CZFHeader active="equipes" />
      <main style={{ padding: '2rem 2.5rem' }}>
        <Empty title="ÉQUIPE INTROUVABLE" sub="Cette équipe n'existe pas ou n'a pas encore été créée." />
        <div style={{ marginTop: '1rem', textAlign: 'center' }}><a href="#equipes" style={{ fontFamily: 'var(--fc)', color: 'var(--gold)', textDecoration: 'none', letterSpacing: '.1em', textTransform: 'uppercase', fontSize: '.75rem' }}>← Retour aux équipes</a></div>
      </main>
    </div>
  );

  const divKey = (team.division || 'Y')[0].toLowerCase();
  const divColor = DIV_COLOR[team.division] || 'var(--gold)';
  const { w, l, wr, tag, divHex } = teamMetrics(team);
  const roster = team.roster || [];
  const allMatches = (matches || []).filter(m => m.team1 === team.team_name || m.team2 === team.team_name);
  const recent = allMatches.slice(0, 5);
  const form = recent.map(m => m.winner === team.team_name ? 'W' : (m.winner ? 'L' : '—'));
  const nextMatch = (matches || []).find(m => (m.team1 === team.team_name || m.team2 === team.team_name) && !m.winner);

  return (
    <div className="page-frame grain" data-screen-label="EquipeDetail">
      <CZFHeader active="equipes" />
      <main style={{ padding: '2rem 2.5rem 3rem' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '.5rem', marginBottom: '1rem',
          fontFamily: 'var(--fc)', fontSize: '.7rem', letterSpacing: '.12em', textTransform: 'uppercase' }}>
          <a href="#equipes" style={{ color: 'var(--cream-2)', textDecoration: 'none' }}>← Équipes</a>
          <span style={{ color: 'var(--muted-2)' }}>/</span>
          <span style={{ color: 'var(--bone)' }}>{team.team_name}</span>
        </div>

        <div className="card-paper grain" style={{ padding: '2rem 2.25rem', position: 'relative', overflow: 'hidden', marginBottom: '1.5rem' }}>
          <div style={{
            position: 'absolute', top: -40, right: -60, width: 360, height: 360, pointerEvents: 'none',
            background: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 200'%3E%3Cpath d='M40 30 Q100 50 80 100 T140 180' stroke='${divHex}' stroke-width='28' fill='none' stroke-linecap='round' opacity='.35'/%3E%3C/svg%3E") center/contain no-repeat`,
          }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: '1.5rem', position: 'relative' }}>
            <div style={{
              width: 110, height: 110, borderRadius: 6, flexShrink: 0,
              background: 'var(--paper-ink)', color: divColor,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--fd)', fontSize: '3.2rem', letterSpacing: '.06em',
              boxShadow: 'inset 0 -8px 16px rgba(0,0,0,.4)',
            }}>{tag}</div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '.5rem', marginBottom: '.5rem' }}>
                <span className={`chip chip-${divKey}`}>{team.division}</span>
                <span style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', fontWeight: 700, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--red-2)' }}>{w+l > 0 ? `${w}W·${l}L · ${wr}%` : 'Aucun match joué'}</span>
              </div>
              <div style={{ fontFamily: 'var(--fd)', fontSize: '3.4rem', color: 'var(--paper-ink)', letterSpacing: '.04em', lineHeight: .95 }}>{team.team_name.toUpperCase()}</div>
              <div style={{ fontFamily: 'var(--fc)', fontSize: '.85rem', color: 'var(--paper-mut)', marginTop: '.5rem', maxWidth: 480 }}>
                Équipe {team.division} · CZF saison en cours
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '.75rem', minWidth: 220 }}>
              <div style={{ display: 'flex', gap: '1rem' }}>
                <BigStat l="Wins" v={w} c="var(--paper-ink)" />
                <BigStat l="Losses" v={l} c="var(--paper-mut)" />
                <BigStat l="Winrate" v={`${wr}%`} c="var(--red-2)" />
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: '.5rem', marginTop: '1.25rem', paddingTop: '1.25rem', borderTop: '1px solid rgba(0,0,0,.08)', position: 'relative' }}>
            <MultiGG roster={roster} />
            {nextMatch && (
              <a className="btn btn-red" href="#matchs" style={{ padding: '.55rem 1rem', marginLeft: 'auto' }}>
                Prochain match · {nextMatch.date} <Icon.ChevronR />
              </a>
            )}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '1.5rem' }}>
          <div>
            <div className="section-head"><h2>Roster</h2><span className="sub">{roster.length} joueur{roster.length > 1 ? 's' : ''}</span></div>
            {roster.length === 0
              ? <Empty title="ROSTER VIDE" sub="Pas encore de joueur dans cette équipe." />
              : (
                <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.max(1, Math.min(5, roster.length))}, 1fr)`, gap: '.75rem' }}>
                  {roster.map((p, i) => <DetailPlayerCard key={i} p={p} divColor={divColor} />)}
                </div>
              )}

            {recent.length > 0 && (
              <>
                <div className="section-head" style={{ marginTop: '2rem' }}>
                  <h2>Forme récente</h2>
                  <span className="sub">{recent.length} derniers</span>
                </div>
                <div style={{ display: 'flex', gap: '.4rem', marginBottom: '1.25rem' }}>
                  {form.map((r, i) => (
                    <div key={i} style={{
                      width: 36, height: 36, borderRadius: 3,
                      background: r === 'W' ? 'rgba(74,222,128,.15)' : r === 'L' ? 'rgba(248,113,113,.15)' : 'rgba(0,0,0,.08)',
                      border: `1px solid ${r === 'W' ? 'var(--ok)' : r === 'L' ? 'var(--err)' : 'var(--border-2)'}`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: 'var(--fd)', fontSize: '1.1rem',
                      color: r === 'W' ? 'var(--ok)' : r === 'L' ? 'var(--err)' : 'var(--muted)',
                    }}>{r}</div>
                  ))}
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '.5rem' }}>
                  {recent.map((m, i) => {
                    const win = m.winner === team.team_name;
                    const opp = m.team1 === team.team_name ? m.team2 : m.team1;
                    return (
                      <div key={i} style={{
                        display: 'flex', alignItems: 'center', gap: '.75rem',
                        background: 'var(--char)', border: '1px solid var(--border)', borderRadius: 3,
                        padding: '.55rem .85rem', position: 'relative',
                      }}>
                        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: win ? 'var(--ok)' : 'var(--err)' }} />
                        <div style={{ fontFamily: 'var(--fc)', fontSize: '.62rem', color: 'var(--muted)', letterSpacing: '.1em', minWidth: 70 }}>{m.date}</div>
                        <span style={{
                          fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.14em',
                          padding: '.12rem .35rem', borderRadius: 2,
                          background: win ? 'rgba(74,222,128,.12)' : 'rgba(248,113,113,.12)',
                          color: win ? 'var(--ok)' : 'var(--err)',
                        }}>{win ? 'VICTOIRE' : 'DÉFAITE'}</span>
                        <span style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', color: 'var(--muted)' }}>vs</span>
                        <span style={{ fontFamily: 'var(--fc)', fontSize: '.85rem', fontWeight: 700, color: 'var(--bone)', flex: 1 }}>{opp}</span>
                        <div style={{ fontFamily: 'var(--fd)', fontSize: '1rem', color: 'var(--bone)' }}>{m.score || '—'}</div>
                      </div>
                    );
                  })}
                </div>
              </>
            )}
          </div>

          <aside>
            <div className="section-head"><h2>Stats équipe</h2></div>
            <div style={{
              background: 'var(--char)', border: '1px solid var(--border)', borderRadius: 3,
              padding: '.85rem 1rem', textAlign: 'center',
            }}>
              <div style={{ fontFamily: 'var(--fc)', fontSize: '.65rem', color: 'var(--muted)', letterSpacing: '.06em', lineHeight: 1.4 }}>
                Stats détaillées à venir (KDA, drakes, first blood…).
              </div>
            </div>

            {nextMatch && (
              <>
                <div className="section-head" style={{ marginTop: '1.5rem' }}><h2>Prochain match</h2></div>
                <div style={{
                  background: 'linear-gradient(135deg, rgba(230,57,70,.15), var(--char))',
                  border: '1px solid var(--red-deep)', borderRadius: 4, padding: '1rem 1.1rem',
                }}>
                  <div className="eyebrow" style={{ color: 'var(--red)', marginBottom: '.55rem' }}>{nextMatch.date}</div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div style={{ fontFamily: 'var(--fd)', fontSize: '1.2rem', color: 'var(--bone)', letterSpacing: '.04em' }}>{nextMatch.team1.toUpperCase()}</div>
                    <div style={{ fontFamily: 'var(--fd)', fontSize: '1rem', color: 'var(--muted)' }}>VS</div>
                    <div style={{ fontFamily: 'var(--fd)', fontSize: '1.2rem', color: 'var(--bone)', letterSpacing: '.04em' }}>{nextMatch.team2.toUpperCase()}</div>
                  </div>
                  <div style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', color: 'var(--muted)', letterSpacing: '.06em', textAlign: 'center', marginTop: '.4rem' }}>{nextMatch.phase || 'Poules'} · {nextMatch.bo_type || 'BO1'}</div>
                </div>
              </>
            )}
          </aside>
        </div>
      </main>
    </div>
  );
};

const BigStat = ({ l, v, c }) => (
  <div>
    <div style={{ fontFamily: 'var(--fc)', fontSize: '.58rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--paper-mut)' }}>{l}</div>
    <div style={{ fontFamily: 'var(--fd)', fontSize: '2rem', color: c, lineHeight: 1, marginTop: 2 }}>{v}</div>
  </div>
);

const DetailPlayerCard = ({ p, divColor }) => {
  const name = (p.player_tag || '?').split('#')[0];
  const icon = p.profile_icon_id
    ? `https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/profile-icons/${p.profile_icon_id}.jpg`
    : null;
  const role = ({ TOP:'TOP', JUNGLE:'JGL', MIDDLE:'MID', BOTTOM:'ADC', UTILITY:'SUP' }[p.position] || p.position || '?');
  const rankLabel = p.tier ? `${p.tier.charAt(0) + p.tier.slice(1).toLowerCase()}${p.rank_division ? ' ' + p.rank_division : ''}` : '—';
  return (
    <div style={{
      background: 'var(--char)', border: '1px solid var(--border)', borderRadius: 4,
      padding: '.85rem', position: 'relative', overflow: 'hidden',
      display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: '.5rem',
    }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 2, background: divColor }} />
      <div style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--muted)' }}>
        {role}{p.is_captain ? ' · ★' : ''}
      </div>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: icon ? `url(${icon}) center/cover` : `linear-gradient(135deg, ${divColor}aa, var(--char-3))`,
        border: `2px solid ${divColor}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'var(--fd)', fontSize: '1.55rem', color: '#0a0805', letterSpacing: '.04em',
      }}>{!icon && name[0]?.toUpperCase()}</div>
      <div style={{ fontFamily: 'var(--fd)', fontSize: '1.1rem', color: 'var(--bone)', letterSpacing: '.04em', lineHeight: 1 }}>{name.toUpperCase()}</div>
      <div style={{ fontFamily: 'var(--fc)', fontSize: '.65rem', fontWeight: 700, letterSpacing: '.08em', color: TIER_COLOR[p.tier] || 'var(--muted)', textTransform: 'uppercase' }}>{rankLabel}</div>
    </div>
  );
};

Object.assign(window, { EquipeDetailPage });
