(function(){
function q(root,s){return root.querySelector(s)} function qa(root,s){return Array.from(root.querySelectorAll(s))}
function n(v){v=parseFloat(String(v).replace(',','.')); return isFinite(v)?v:0} function r(v,d=2){return isFinite(v)?Number(v).toFixed(d).replace('.',','):'-'}
function time(decimal){ if(!isFinite(decimal)||decimal<0) return '-'; const h=Math.floor(decimal), m=Math.round((decimal-h)*60); return (h+Math.floor(m/60))+' h '+String(m%60).padStart(2,'0')+' min'; }
function post(action,data){ const fd=new FormData(); fd.append('action',action); fd.append('nonce',BRLCalc.nonce); Object.keys(data||{}).forEach(k=>fd.append(k,data[k])); return fetch(BRLCalc.ajaxUrl,{method:'POST',credentials:'same-origin',body:fd}).then(x=>x.json()); }
function init(root){
 const fields={}; qa(root,'[data-field]').forEach(el=>fields[el.dataset.field]=el); const out=(k,v)=>{const e=q(root,'[data-out="'+k+'"]'); if(e)e.textContent=v};
 let saved=Array.isArray(BRLCalc.saved)?BRLCalc.saved:JSON.parse(localStorage.getItem('brlcalc_saved')||'[]');
 function values(){ return Object.fromEntries(Object.keys(fields).map(k=>[k, fields[k].value])); }
 function calc(){
  const distRang=n(fields.distRang.value), distEntre=n(fields.distEntreRangs.value), rampes=n(fields.rampes.value)||1, debitEm=n(fields.debitEmetteur.value), surface=n(fields.surface.value);
  const maille=distRang*distEntre/rampes, pluvio=maille>0?debitEm/maille:0, debitPoste=pluvio*surface/1000;
  const dose=n(fields.dose.value), heures=n(fields.heures.value), minutes=n(fields.minutes.value), vol=n(fields.volume.value), tdec=heures+minutes/60;
  out('maille',r(maille)); out('pluvio',r(pluvio)); out('debitPoste',r(debitPoste));
  out('tempsDose', pluvio>0?time(dose/pluvio):'-'); out('volumeDose', r(dose*surface/1000));
  out('doseTemps', r(pluvio*tdec)); out('volumeTemps', r(debitPoste*tdec));
  out('doseVolume', surface>0?r(vol/surface*1000):'-'); out('tempsVolume', debitPoste>0?time(vol/debitPoste):'-');
  return {poste:fields.poste.value, distRang, distEntreRangs:distEntre, rampes, debitEmetteur:debitEm, surface, maille, pluvio, debitPoste, dose, heures, minutes, volume:vol};
 }
 function renderSaved(){ const box=q(root,'[data-saved-list]'); if(!box) return; if(!saved.length){box.innerHTML='<p>Aucune recherche sauvegardée.</p>';return} box.innerHTML=saved.map((s,i)=>'<div class="brlcalc-saved"><div><strong>'+(s.poste||'Poste sans nom')+'</strong><br><small>'+(s.date||'')+'</small><br>Pluviométrie : '+r(s.pluvio)+' mm/h - Débit poste : '+r(s.debitPoste)+' m³/h</div><button data-load="'+i+'">Recharger</button>'+(BRLCalc.isLoggedIn?'<button data-del="'+(s.id||'')+'">Supprimer</button>':'')+'</div>').join(''); }
 qa(root,'[data-field]').forEach(el=>el.addEventListener('input',calc));
 root.addEventListener('click',function(e){ if(e.target.matches('[data-load]')){ const s=saved[+e.target.dataset.load]; Object.keys(fields).forEach(k=>{if(s[k]!==undefined) fields[k].value=s[k]}); calc(); } if(e.target.matches('[data-del]')){ post('brl_calc_delete',{id:e.target.dataset.del}).then(res=>{if(res.success){saved=res.data.saved;renderSaved();}}); } });
 q(root,'[data-save]').addEventListener('click',function(){ const data=calc(); const msg=q(root,'[data-save-msg]'); if(BRLCalc.isLoggedIn){ post('brl_calc_save',{payload:JSON.stringify(data)}).then(res=>{msg.textContent=res.data&&res.data.message?res.data.message:'Sauvegardé.'; if(res.success){saved=res.data.saved;renderSaved();}}); } else { data.date=(new Date()).toLocaleString(); saved.unshift(data); saved=saved.slice(0,20); localStorage.setItem('brlcalc_saved',JSON.stringify(saved)); msg.textContent='Recherche sauvegardée sur cet appareil. Créez un compte pour la retrouver partout.'; renderSaved(); }});
 const reg=q(root,'[data-register-form]'); if(reg) reg.addEventListener('submit',e=>{e.preventDefault(); post('brl_calc_register',{email:reg.email.value,password:reg.password.value}).then(res=>{q(root,'[data-register-msg]').textContent=res.data.message; if(res.success&&res.data.reload) location.reload();});});
 const log=q(root,'[data-login-form]'); if(log) log.addEventListener('submit',e=>{e.preventDefault(); post('brl_calc_login',{login:log.login.value,password:log.password.value}).then(res=>{q(root,'[data-login-msg]').textContent=res.data.message; if(res.success&&res.data.reload) location.reload();});});
 calc(); renderSaved();
}
document.addEventListener('DOMContentLoaded',()=>document.querySelectorAll('[data-brlcalc]').forEach(init));
})();
