(function(){
  const $=(q,el=document)=>el.querySelector(q);
  const $$=(q,el=document)=>Array.from(el.querySelectorAll(q));
  const cards=$$('.opt[data-credit]');
  const totalEl=$('#totalCredit');
  const priEl=$('#priorityInput');
  const priBtns=$$('.prBtn[data-pr]');
  const search=$('#matrixSearch');
  function fmt(n){return (Math.round(n*100)/100).toFixed(2);}
  function recalc(){
    let total=0;
    cards.forEach(c=>{ if(c.classList.contains('active')) total+=parseFloat(c.getAttribute('data-credit')||'0')||0; });
    const pr=priEl?priEl.value:'NORMAL';
    if(pr==='FAST') total+=10.0;
    if(pr==='URGENT') total+=30.0;
    if(totalEl) totalEl.textContent=fmt(total);
    const hidden=$('#totalCreditInput'); if(hidden) hidden.value=fmt(total);
  }
  cards.forEach(c=>c.addEventListener('click', ()=>{
    c.classList.toggle('active');
    const chk=c.querySelector('input[type=checkbox]');
    if(chk) chk.checked=c.classList.contains('active');
    recalc();
  }));
  priBtns.forEach(b=>b.addEventListener('click', ()=>{
    priBtns.forEach(x=>x.classList.remove('active'));
    b.classList.add('active');
    if(priEl) priEl.value=b.getAttribute('data-pr');
    recalc();
  }));
  if(search){
    search.addEventListener('input', ()=>{
      const v=search.value.trim().toLowerCase();
      cards.forEach(c=>{
        const t=(c.getAttribute('data-name')||'').toLowerCase();
        c.style.display=(!v||t.includes(v))?'':'none';
      });
    });
  }
  const drop=$('#dropZone'), file=$('#ecuFile');
  if(drop && file){
    ['dragenter','dragover'].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.style.borderColor='rgba(6,182,212,.70)';}));
    ['dragleave','drop'].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.style.borderColor='rgba(124,58,237,.45)';}));
    drop.addEventListener('drop', e=>{
      if(e.dataTransfer?.files?.length){
        file.files=e.dataTransfer.files;
        const lbl=$('#fileLabel'); if(lbl) lbl.textContent=e.dataTransfer.files[0].name;
      }
    });
    file.addEventListener('change', ()=>{
      const lbl=$('#fileLabel'); lbl.textContent=(file.files?.[0]?.name)||'Drag & drop or click';
    });
  }
  recalc();
})();
