import {
  bindLoginForm, isAuthenticated, logout,
  createTournament, addParticipant, scoreMatch,
  listTournaments, listMatches
} from '/assets/api.js?v=10';

const toast = document.getElementById('toast');
const adminSection = document.getElementById('adminSection');
const loginSection = document.getElementById('loginSection');

function showToast(msg, ok=true){
  toast.textContent = msg;
  toast.style.borderColor = ok ? 'rgba(143,237,255,.45)' : 'rgba(255,120,120,.45)';
  toast.classList.add('show');
  setTimeout(()=>toast.classList.remove('show'), 2200);
}

function toggleAdminUI(){
  const logged = isAuthenticated();
  adminSection.classList.toggle('hide', !logged);
  loginSection.classList.toggle('hide', logged);
}

function disable(btn, spin, yes){
  btn.disabled = !!yes;
  spin.classList.toggle('hide', !yes);
}

async function renderTournaments(){
  const wrap = document.getElementById('listTournaments');
  const p_tid = document.getElementById('p_tid');
  const s_tid = document.getElementById('s_tid');
  try{
    const ts = await listTournaments();
    wrap.innerHTML = ts.map(t => `<div class="card"><strong>#${t.id}</strong> — ${t.name} <span class="muted">(${[t.location||'—', t.start_date].filter(Boolean).join(' • ')})</span></div>`).join('') || '<div class="empty">Aucun tournoi.</div>';
    const opts = ['<option value="">— choisir un tournoi —</option>'].concat(
      ts.map(t => `<option value="${t.id}">#${t.id} — ${t.name}</option>`)
    ).join('');
    p_tid.innerHTML = opts;
    s_tid.innerHTML = opts;
  }catch(e){
    wrap.innerHTML = `<div class="empty">Erreur chargement: ${e.message}</div>`;
  }
}

async function renderMatchesForSelectedTournament(){
  const tid = Number(document.getElementById('s_tid').value || '0');
  const s_mid = document.getElementById('s_mid');
  if(!tid){ s_mid.innerHTML = '<option value="">— choisir un match —</option>'; return; }
  try{
    const ms = await listMatches(tid);
    s_mid.innerHTML = ['<option value="">— choisir un match —</option>'].concat(
      ms.map(m => `<option value="${m.id}">#${m.id} — ${m.team_a} vs ${m.team_b} (${m.court||'—'})</option>`)
    ).join('');
  }catch(e){
    s_mid.innerHTML = '<option value="">Erreur chargement matches</option>';
  }
}

function bindAuth(){
  bindLoginForm({});
  const logoutBtn = document.getElementById('logoutBtn');
  logoutBtn?.addEventListener('click', ()=>{
    logout(); toggleAdminUI(); showToast('Déconnecté.');
  });
}

function bindAdminActions(){
  document.getElementById('createTournamentBtn')?.addEventListener('click', async (e)=>{
    const btn = e.currentTarget;
    const spin = document.getElementById('createTournamentSpin');
    const err = document.getElementById('createTournamentErr');
    err.textContent='';
    const name = document.getElementById('t_name').value.trim();
    if(!name){ err.textContent='Le nom est requis.'; return; }
    const payload = {
      name,
      location: document.getElementById('t_location').value.trim(),
      start_date: document.getElementById('t_start').value || null,
      end_date: document.getElementById('t_end').value || null
    };
    try{
      disable(btn, spin, true);
      await createTournament(payload);
      showToast('Tournoi créé ✔');
      document.getElementById('t_name').value='';
      document.getElementById('t_location').value='';
      document.getElementById('t_start').value='';
      document.getElementById('t_end').value='';
      renderTournaments();
    }catch(e){
      err.textContent = e?.payload?.error || e.message;
      showToast('Erreur création tournoi', false);
    }finally{
      disable(btn, spin, false);
    }
  });

  document.getElementById('addParticipantBtn')?.addEventListener('click', async (e)=>{
    const btn = e.currentTarget;
    const spin = document.getElementById('addParticipantSpin');
    const err = document.getElementById('addParticipantErr');
    err.textContent='';
    const tid = Number(document.getElementById('p_tid').value || '0');
    const full_name = document.getElementById('p_fullname').value.trim();
    if(!tid){ err.textContent='Choisis un tournoi.'; return; }
    if(!full_name){ err.textContent='Nom du joueur requis.'; return; }
    try{
      disable(btn, spin, true);
      await addParticipant(tid, { full_name });
      showToast('Joueur ajouté ✔');
      document.getElementById('p_fullname').value='';
    }catch(e){
      err.textContent = e?.payload?.error || e.message;
      showToast('Erreur ajout joueur', false);
    }finally{
      disable(btn, spin, false);
    }
  });

  document.getElementById('s_tid')?.addEventListener('change', renderMatchesForSelectedTournament);

  document.getElementById('scoreBtn')?.addEventListener('click', async (e)=>{
    const btn = e.currentTarget;
    const spin = document.getElementById('scoreSpin');
    const err = document.getElementById('scoreErr');
    err.textContent='';
    const mid = Number(document.getElementById('s_mid').value || '0');
    if(!mid){ err.textContent='Choisis un match.'; return; }
    const payload = {
      score_a: Number(document.getElementById('m_a').value||'0'),
      score_b: Number(document.getElementById('m_b').value||'0'),
      done: document.getElementById('m_done').checked
    };
    try{
      disable(btn, spin, true);
      await scoreMatch(mid, payload);
      showToast('Score enregistré ✔');
      document.getElementById('m_a').value='';
      document.getElementById('m_b').value='';
      document.getElementById('m_done').checked=false;
    }catch(e){
      err.textContent = e?.payload?.error || e.message;
      showToast('Erreur scoring', false);
    }finally{
      disable(btn, spin, false);
    }
  });

  document.getElementById('refreshTournaments')?.addEventListener('click', renderTournaments);
}

function init(){
  toggleAdminUI();
  bindAuth();
  bindAdminActions();
  if(isAuthenticated()) renderTournaments();
}

document.addEventListener('DOMContentLoaded', init);
