document.addEventListener('DOMContentLoaded',()=>{
 if(location.pathname!=='/accounting')return;
 const filterForm=document.querySelector('form[action="/accounting"]');
 const invoiceForm=document.querySelector('form[action="/accounting/save"]');
 if(filterForm&&invoiceForm)invoiceForm.closest('.card')?.after(filterForm);
 const structuresTitle=[...document.querySelectorAll('.card-title')].find(node=>node.textContent.trim()==='Coût et paiements par structure');
 structuresTitle?.closest('.col-xl-7')?.classList.add('accounting-dashboard-structures');
 const canvas=document.getElementById('accountingAnnualChart');
 if(canvas&&window.Chart){const rows=JSON.parse(canvas.dataset.series||'[]');new Chart(canvas,{type:'bar',data:{labels:rows.map(r=>r.year),datasets:[{label:'Payé',data:rows.map(r=>(r.billed-r.due)/100),backgroundColor:'rgba(47,179,68,.72)'},{label:'Reste dû',data:rows.map(r=>r.due/100),backgroundColor:'rgba(245,159,0,.75)'}]},options:{responsive:true,maintainAspectRatio:false,scales:{x:{stacked:true},y:{stacked:true,beginAtZero:true,ticks:{callback:v=>v.toLocaleString('fr-FR')+' €'}}},plugins:{tooltip:{callbacks:{label:c=>c.dataset.label+' : '+c.parsed.y.toLocaleString('fr-FR',{minimumFractionDigits:2})+' €'}}}}});}
 document.querySelectorAll('.table tbody tr').forEach(row=>{
  const reference=row.cells[1]?.textContent.trim();if(!reference)return;
  row.classList.add('cursor-pointer');row.tabIndex=0;
  const open=event=>{if(event.target.closest('a,button,input,select'))return;if(event.type==='keydown'&&!['Enter',' '].includes(event.key))return;location.href='/accounting/edit-by-reference?reference='+encodeURIComponent(reference);};
  row.addEventListener('click',open);row.addEventListener('keydown',open);
 });
});
