document.addEventListener('DOMContentLoaded',()=>{
 const lines=document.querySelector('#lines'),add=document.querySelector('#add-line'); if(!lines||!add)return;
 const box=document.createElement('div'); box.className='panel grid';
 box.innerHTML='<label>Réduction globale multi-activité<input id="global-discount" type="number" step="0.01" min="0" value="0"></label><label>Ventilation<select id="discount-method"><option value="proportional">Proportionnelle aux montants</option><option value="equal">Égale entre les lignes</option></select></label><button type="button" class="btn secondary" id="spread-discount">Répartir par pôle</button>';
 lines.before(box);
 box.querySelector('#spread-discount').addEventListener('click',()=>{
  const rows=[...lines.querySelectorAll('.line')],total=Number(box.querySelector('#global-discount').value)||0;
  const gross=rows.map(r=>(Number(r.querySelector('[name="quantity[]"]').value)||0)*(Number(r.querySelector('[name="unit_price[]"]').value)||0)),sum=gross.reduce((a,b)=>a+b,0),equal=box.querySelector('#discount-method').value==='equal'; let used=0;
  rows.forEach((r,i)=>{let value=i===rows.length-1?total-used:Math.round((equal?total/rows.length:(sum?total*gross[i]/sum:0))*100)/100;value=Math.min(gross[i],Math.max(0,value));used+=value;r.querySelector('[name="discount[]"]').value=value.toFixed(2)});
 });
 add.addEventListener('click',()=>{const n=lines.firstElementChild.cloneNode(true);n.querySelectorAll('input').forEach(i=>{if(i.name==='quantity[]')i.value='1';else if(i.name==='discount[]')i.value='0';else i.value=''});lines.appendChild(n)});
 lines.addEventListener('click',e=>{if(e.target.classList.contains('remove')&&lines.children.length>1)e.target.closest('.line').remove()});
});
