async function j(url, opts={}){
  const r = await fetch(url, opts);
  if (!r.ok) {
    const t = await r.text().catch(()=>'');
    throw new Error(`HTTP ${r.status} ${t}`);
  }
  const ct = r.headers.get('content-type')||'';
  return ct.includes('application/json') ? r.json() : r.text();
}
const $ = (s)=>document.querySelector(s);

async function loadTournaments(){
  const data = await j('/api/tournaments');
  const opts = ['<option value="">— choisir —</option>']
    .concat(data.map(t=>`<option value="${t.id}">#${t.id} — ${t.name}</option>`));
  $('#t-list').innerHTML = opts.join('');
  $('#p-tournament').innerHTML = opts.join('');
  $('#m-tournament').innerHTML = opts.join('');
  $('#tournaments-box').textContent = JSON.stringify(data, null, 2);
  const tid = Number($('#p-tournament').value || data[0]?.id || 0);
  if (tid) await refreshParticipants(tid);
}

async function refreshParticipants(tid){
  try{
    const data = await j(`/api/tournaments/${tid}/participants`);
    $('#participants-box').textContent = JSON.stringify(data, null, 2);
  }catch(e){
    $('#participants-box').textContent = 'Erreur: '+e.message;
  }
}

async function createTournament(e){
  e.preventDefault();
  const payload = {
    name: $('#t-name').value.trim(),
    location: $('#t-location').value.trim(),
    start_date: $('#t-start').value,
    end_date: $('#t-end').value
  };
  try{
    await j('/api/tournaments', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify(payload)
    });
    $('#t-create-status').textContent = 'OK ✅';
    await loadTournaments();
  }catch(err){
    $('#t-create-status').textContent = err.message;
  }
}

async function deleteTournament(){
  const id = Number($('#t-list').value||'0');
  if (!id) return;
  if (!confirm('Supprimer le tournoi #' + id + ' ?')) return;
  try{
    await j(`/api/tournaments/${id}`, { method:'DELETE' });
    await loadTournaments();
  }catch(e){
    alert(e.message);
  }
}

async function createParticipant(e){
  e.preventDefault();
  const tid = Number($('#p-tournament').value||'0');
  const name = $('#p-name').value.trim();
  if (!tid || !name) return;
  try{
    await j('/api/participants', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ tournament_id: tid, full_name: name })
    });
    $('#p-create-status').textContent = 'OK ✅';
    await refreshParticipants(tid);
  }catch(e){
    $('#p-create-status').textContent = e.message;
  }
}

async function scoreMatch(e){
  e.preventDefault();
  const id = Number($('#m-id').value||'0');
  const sa = Number($('#m-score-a').value||'0');
  const sb = Number($('#m-score-b').value||'0');
  const finished = $('#m-finished').checked;
  if (!id) return;
  try{
    await j(`/api/matches/${id}/score`, {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ score_a: sa, score_b: sb, finished })
    });
    $('#m-score-status').textContent = 'OK ✅';
  }catch(e){
    $('#m-score-status').textContent = e.message;
  }
}

async function ping(){
  try{ await j('/api/health'); $('#health').textContent = 'OK ✅'; }
  catch(e){ $('#health').textContent = e.message; }
}

document.addEventListener('DOMContentLoaded', () => {
  $('#t-create-form').addEventListener('submit', createTournament);
  $('#btn-del-t').addEventListener('click', deleteTournament);
  $('#btn-refresh-t').addEventListener('click', loadTournaments);
  $('#p-create-form').addEventListener('submit', createParticipant);
  $('#m-score-form').addEventListener('submit', scoreMatch);
  $('#btn-health').addEventListener('click', ping);
  loadTournaments();
  ping();
});
