(()=>{
  'use strict';
  const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
  const toast=msg=>{ if(typeof window.showToast==='function') window.showToast(msg); else alert(msg); };
  function getDialog(){
    let d=document.getElementById('staffCodeDialog');
    if(!d){ d=document.createElement('dialog'); d.id='staffCodeDialog'; d.className='staff-code-dialog'; document.body.appendChild(d); }
    return d;
  }
  function openDialog(btn){
    const card=btn.closest('.staff-profile-card');
    const name=card?.querySelector('.staff-profile-title strong')?.textContent?.trim()||'colaborador';
    const staffId=btn.dataset.createStaffCode||card?.dataset.staffId||'';
    const role=btn.dataset.role||'';
    if(!role){ toast('Este colaborador no tiene un perfil válido para crear código.'); return; }
    const labels={nurse:'Enfermería',assistant:'Asistente',cook:'Cocina',cleaning:'Limpieza',maintenance:'Mantenimiento',security:'Seguridad',doctor:'Médico',administrator:'Administración'};
    const d=getDialog();
    d.innerHTML=`<form method="dialog" class="staff-code-modal" id="staffCodeFormFinal184">
      <button type="button" class="dialog-close" id="staffCodeClose184" aria-label="Cerrar">×</button>
      <span class="eyebrow">ACCESO DE PERSONAL</span><h3>Crear código para ${esc(name)}</h3>
      <p>Este código permitirá que el colaborador se registre una sola vez y abra el panel correspondiente a su puesto.</p>
      <div class="code-validity-note"><strong>Vigencia fija: 7 días</strong><span>El código sirve únicamente para activar la cuenta una vez.</span></div>
      <div id="staffGeneratedCode184" class="generated-code-panel hidden"></div>
      <div class="form-actions" id="staffCodeActions184"><button type="button" class="secondary-btn" id="staffCodeCancel184">Cancelar</button><button type="button" class="primary-btn" id="staffCodeGenerate184">Generar código</button></div>
    </form>`;
    const close=()=>{ try{d.close();}catch(_){d.removeAttribute('open');} };
    d.querySelector('#staffCodeClose184').onclick=close;
    d.querySelector('#staffCodeCancel184').onclick=close;
    try{ if(!d.open)d.showModal(); }catch(_){ d.setAttribute('open',''); }
    d.querySelector('#staffCodeGenerate184').onclick=async ev=>{
      ev.preventDefault(); ev.stopPropagation();
      const action=ev.currentTarget;
      const days=7;
      const client=window.seniorcareSupabase;
      if(!client?.rpc){ toast('No hay conexión disponible con Supabase.'); return; }
      action.disabled=true; action.textContent='Generando...';
      try{
        const rpcResult=window.BHSC_CALL_RPC
          ?await window.BHSC_CALL_RPC(['bh_create_staff_code_v4375','bh_create_staff_code_v4325','bh_create_staff_code_v4321','administrator_create_staff_code_v433','administrator_create_staff_code_v3'],{p_staff_key:String(staffId),p_role:role,p_days:days})
          :await client.rpc('administrator_create_staff_code_v433',{p_staff_key:String(staffId),p_role:role,p_days:days});
        let {data,error}=rpcResult;
        if(error) throw error;
        const row=Array.isArray(data)?data[0]:data;
        const result=row?.result||row||{};
        const code=result.code;
        if(!code) throw new Error('Supabase no devolvió el código.');
        const expires=result.expires_at||new Date(Date.now()+days*86400000).toISOString();
        let links={}; try{links=JSON.parse(localStorage.getItem('seniorcare-staff-code-links')||'{}')||{};}catch(_){links={};}
        links[String(staffId)]={code,role,expires,createdAt:new Date().toISOString(),activated:false};
        localStorage.setItem('seniorcare-staff-code-links',JSON.stringify(links));
        const box=d.querySelector('#staffGeneratedCode184');
        box.classList.remove('hidden');
        box.innerHTML=`<span>CÓDIGO DE REGISTRO</span><strong>${esc(code)}</strong><small>${esc(name)} · ${esc(labels[role]||role)} · Vigencia 7 días</small><button type="button" class="secondary-btn" id="staffCodeCopy184">Copiar código</button><button type="button" class="primary-btn" id="staffCodeDone184">Listo</button>`;
        d.querySelector('#staffCodeActions184').classList.add('hidden');
        d.querySelector('#staffCodeCopy184').onclick=async()=>{try{await navigator.clipboard.writeText(code);toast('Código copiado.');}catch(_){toast(`Código: ${code}`);}};
        d.querySelector('#staffCodeDone184').onclick=()=>{ close(); btn.textContent='Reenviar código'; };
      }catch(err){ toast(err?.message||'No fue posible crear el código.'); action.disabled=false; action.textContent='Generar código'; }
    };
  }
  document.addEventListener('click',e=>{
    const btn=e.target.closest?.('[data-create-staff-code]');
    if(!btn)return;
    e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation();
    openDialog(btn);
  },true);
})();
