(()=>{
  'use strict';
  const LABEL='Médico';
  const VALUE='Médico';
  const ensureDoctorOption=()=>{
    document.querySelectorAll('select[name="role"]').forEach(sel=>{
      const inStaffForm=sel.closest('#staffForm, .staff-form, form') || sel.closest('.form-card');
      if(!inStaffForm) return;
      const has=[...sel.options].some(o=>/^(m[eé]dico|doctor)$/i.test((o.value||o.textContent||'').trim()));
      if(!has){
        const opt=document.createElement('option');
        opt.value=VALUE;
        opt.textContent=LABEL;
        const admin=[...sel.options].find(o=>/administraci[oó]n|admin/i.test(o.textContent||o.value||''));
        if(admin) sel.insertBefore(opt,admin); else sel.appendChild(opt);
      }
    });
  };
  const observer=new MutationObserver(ensureDoctorOption);
  const start=()=>{
    ensureDoctorOption();
    observer.observe(document.documentElement,{childList:true,subtree:true});
  };
  if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',start,{once:true}); else start();
  document.addEventListener('click',e=>{
    if(e.target.closest('[data-screen="staff"], [data-action="add-staff"], #addStaff, #openStaffForm')) setTimeout(ensureDoctorOption,0);
  },true);
  window.addEventListener('seniorcare:user-ready',()=>{
    const role=String(window.currentUser?.role||'').toLowerCase();
    if(role==='doctor' && typeof window.go==='function') setTimeout(()=>window.go('medicalDashboard',{scope:'global'},{replace:true}),300);
  });
})();
