document.addEventListener('DOMContentLoaded',()=>{
 const event=document.querySelector('#id_event'),member=document.querySelector('#id_member');if(!event||!member)return;
 const endpoint=`${window.location.pathname.split('/attendance/')[0]}/attendance/member-options/`;
 const render=(rows,selected='')=>{member.innerHTML='';member.add(new Option(rows.length?'Select an eligible member':'Select an event with eligible members',''));rows.forEach(row=>member.add(new Option(row.label,row.id,false,String(row.id)===String(selected))));member.disabled=!rows.length};
 const load=async()=>{const selected=member.value;if(!event.value){render([]);return}member.disabled=true;member.innerHTML='';member.add(new Option('Loading eligible members…',''));try{const response=await fetch(`${endpoint}?event=${encodeURIComponent(event.value)}`,{headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw new Error();render((await response.json()).members,selected)}catch{render([]);member.options[0].text='Unable to load members'}};
 event.addEventListener('change',load);if(!member.value)load();
});
