document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('.category-widget').forEach(w=>{const d=JSON.parse(w.querySelector('.category-data').textContent),all=d.all,lms=d.lms_mode,sel=new Set(d.selected),name=w.dataset.name,srch=w.querySelector('.category-search'),left=w.querySelector('[data-panel="left"]'),right=w.querySelector('[data-panel="right"]'),inputs=w.querySelector('.hidden-inputs');const upd=()=>{left.innerHTML=all.filter(c=>!sel.has(c.id)&&(!srch.value||c.title.toLowerCase().includes(srch.value.toLowerCase()))).map(c=>`<div class="category-item" data-id="${c.id}"><span>${c.title}</span><button class="add-btn" type="button">+</button></div>`).join('')||(lms?'<div class="empty-message">No courses available</div>':'<div class="empty-message">No categories available</div>');right.innerHTML=[...sel].map(id=>all.find(c=>c.id==id)).filter(Boolean).map(c=>`<div class="category-item" data-id="${c.id}"><span>${c.title}</span><button class="remove-btn" type="button">&times;</button></div>`).join('')||(lms?'<div class="empty-message">No courses selected</div>':'<div class="empty-message">No categories selected</div>');inputs.innerHTML=[...sel].map(id=>`<input type="hidden" name="${name}" value="${id}">`).join('')};srch.oninput=upd;left.onclick=e=>{const item=e.target.closest('.category-item');if(item){sel.add(item.dataset.id);upd()}};right.onclick=e=>{const item=e.target.closest('.category-item');if(item){sel.delete(item.dataset.id);upd()}};upd()})});
