(function(){
  var API=document.body.dataset.api;
  var PRODS=(document.body.dataset.products||'').split(',').filter(Boolean);
  function esc(x){ return String(x==null?'':x).replace(/[&<>]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;'}[c];}); }
  function token(){ return decodeURIComponent((location.hash||'').replace('#','')); }
  function load(prod,t,box){
    fetch(API+'/'+prod+'/admin?token='+encodeURIComponent(t)).then(function(r){return r.json()}).then(function(d){
      if(d.status==='error'){ box.innerHTML='<p style="color:#c0392b">'+esc(d.message)+'</p>'; return; }
      var h='<h3>'+esc(d.brand)+' — '+d.count+' inscrits'+(d.founder_cap?(' · '+d.founder_remaining+' places fondatrices restantes'):'')+'</h3>';
      h+='<table class="tiertable"><tr><th>#</th><th>Email</th><th>Prénom</th><th>Pays</th><th>Région</th><th>Fond.</th><th>Détails</th><th>Date</th></tr>';
      d.rows.forEach(function(r,i){ h+='<tr><td>'+(r.rank_at_signup||i+1)+'</td><td>'+esc(r.email)+'</td><td>'+esc(r.first_name)+'</td><td>'+esc(r.country_code)+'</td><td>'+esc(r.region)+'</td><td>'+(r.founder_status?'✓':'')+'</td><td>'+esc(JSON.stringify(r.details||{}))+'</td><td>'+esc(r.signed_up_at)+'</td></tr>'; });
      h+='</table>'; box.innerHTML=h;
    }).catch(function(e){ box.innerHTML='<p>Erreur: '+esc(e)+'</p>'; });
  }
  function showData(t){
    var root=document.getElementById('staffroot'); root.innerHTML='';
    PRODS.forEach(function(p){
      var box=document.createElement('div'); box.className='formwrap'; box.style.margin='20px 0';
      box.innerHTML='<p class="muted">Chargement '+esc(p)+'…</p>'; root.appendChild(box); load(p,t,box);
    });
  }
  function showPrompt(){
    var root=document.getElementById('staffroot');
    root.innerHTML='<div class="formwrap"><label>Token staff</label><input id="tok" type="password" placeholder="Collez le token"><p style="margin-top:12px"><button class="btn" id="go">Ouvrir le tableau de bord</button></p></div>';
    document.getElementById('go').addEventListener('click',function(){
      location.hash=encodeURIComponent(document.getElementById('tok').value); showData(token());
    });
  }
  document.addEventListener('DOMContentLoaded',function(){ var t=token(); if(t){ showData(t); } else { showPrompt(); } });
})();