(function(){
  const params = new URLSearchParams(location.search);
  const id = Number(params.get('id') || '0');
  if(!id){
    document.getElementById('info').innerHTML = '<p>Tournoi introuvable (id manquant)</p>';
    return;
  }
  async function load(){
    const t = await SSAPI.get('/tournaments/'+id).catch(()=>null);
    if(!t){ document.getElementById('info').innerHTML = '<p>Tournoi introuvable</p>'; return; }
    document.getElementById('info').innerHTML = `
      <h2>${t.name}</h2>
      <div><strong>Lieu:</strong> ${t.location || '—'}</div>
      <div><strong>Dates:</strong> ${t.start_date} → ${t.end_date}</div>
      <div class="grid">
        <div class="card"><strong>Inscrits</strong><br>${t.enrollment_count}</div>
        <div class="card"><strong>Équipes</strong><br>${t.team_count}</div>
        <div class="card"><strong>Matches</strong><br>${t.match_count}</div>
      </div>
      ${t.next_match ? `<div class="card mt"><strong>Prochain match</strong><br>${t.next_match.round || ''} — ${t.next_match.court || ''}<br>${t.next_match.scheduled_at ? new Date(t.next_match.scheduled_at).toLocaleString() : ''}</div>` : ''}
    `;
    const parts = await SSAPI.get('/enrollments?tournament_id='+id).catch(()=>[]);
    document.getElementById('participants').innerHTML = parts.map(p=>`
      <div class="card">
        ${p.first_name} ${p.last_name} <span class="muted">(#${p.ranking || '—'})</span>
      </div>
    `).join('') || '<p class="muted">Aucun inscrit</p>';
    const matches = await SSAPI.get('/matches?tournament_id='+id).catch(()=>[]);
    document.getElementById('matchlist').innerHTML = matches.map(m=>`
      <div class="card">
        <div><strong>${m.round || 'Match'}</strong> — ${m.court || 'Court ?'}</div>
        <div>Teams: ${m.team_a_id || '?'} vs ${m.team_b_id || '?'}</div>
        <div>Score: ${m.score_a} - ${m.score_b} (${m.status})</div>
        <div>${m.scheduled_at ? new Date(m.scheduled_at).toLocaleString() : ''}</div>
      </div>
    `).join('') || '<p class="muted">Aucun match</p>';
  }
  load();
})();