(()=>{const $=s=>document.querySelector(s),form=$('#reduction-form');if(!form)return;const condition=$('#red-condition'),type=$('#red-type'),value=$('#red-value'),free=$('#red-free'),code=$('#red-code'),label=$('#red-label'),threshold=$('#red-threshold');const clean=v=>(v||'').normalize('NFD').replace(/[\u0300-\u036f]/g,'').toUpperCase().replace(/[^A-Z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40);function refresh(){const exceptional=condition.value==='exceptionnelle';$('#red-free-field').hidden=!exceptional;if(!exceptional)free.checked=false;value.disabled=free.checked;value.required=!free.checked;$('#red-value-field').style.opacity=free.checked?'.45':'1';$('#red-unit').textContent=type.value==='pourcentage'?'%':'€';if(!code.dataset.manual)code.value=exceptional&&free.checked?'EXCEPTIONNELLE-LIBRE':clean(label.value||condition.selectedOptions[0].textContent);}condition.addEventListener('change',refresh);type.addEventListener('change',refresh);free.addEventListener('change',refresh);label.addEventListener('input',refresh);code.addEventListener('input',()=>code.dataset.manual='1');const templates={second:{condition:'plusieurs_membres',label:'Réduction plusieurs membres',type:'montant_fixe',threshold:2},multi:{condition:'multi_activites',label:'Réduction seconde activité',type:'montant_fixe',threshold:2},territory:{condition:'residence',label:'Réduction territoriale',type:'montant_fixe',threshold:''},exceptional:{condition:'exceptionnelle',label:'Réduction exceptionnelle à définir',type:'montant_fixe',threshold:'',free:true}};document.querySelectorAll('[data-template]').forEach(b=>b.addEventListener('click',()=>{const t=templates[b.dataset.template];condition.value=t.condition;label.value=t.label;type.value=t.type;threshold.value=t.threshold;free.checked=!!t.free;delete code.dataset.manual;refresh();form.scrollIntoView({behavior:'smooth'});}));$('#red-search')?.addEventListener('input',e=>document.querySelectorAll('.rule-list article').forEach(a=>a.hidden=!a.dataset.search.includes(e.target.value.toLowerCase())));refresh();})();
