/* Bernard Health SeniorCare V1.7.4 — guardado persistente de colaboradores en Supabase */
(function(){
  'use strict';
  if(window.__staffSaveStayV174) return;
  window.__staffSaveStayV174=true;

  const getClient=()=>window.seniorcareSupabase||null;
  const getOrgId=()=>window.currentUser?.organizationId||window.getSeniorCareActiveOrganizationId?.()||null;

  async function persistStaffRecord(record){
    const client=getClient();
    const org=getOrgId();
    if(!client) throw new Error('No hay conexión con Supabase.');
    if(!org) throw new Error('No se pudo identificar la organización.');

    const payload={
      organization_id:org,
      staff_key:String(record.id),
      active:true,
      data:record,
      updated_at:new Date().toISOString(),
      updated_by:window.currentUser?.id||null
    };

    const {error:upsertError}=await client
      .from('seniorcare_staff_records')
      .upsert(payload,{onConflict:'organization_id,staff_key'});
    if(upsertError) throw upsertError;

    const {data:confirmed,error:confirmError}=await client
      .from('seniorcare_staff_records')
      .select('staff_key,data,active')
      .eq('organization_id',org)
      .eq('staff_key',String(record.id))
      .eq('active',true)
      .maybeSingle();
    if(confirmError) throw confirmError;
    if(!confirmed) throw new Error('Supabase no confirmó el colaborador guardado.');
    return confirmed;
  }

  document.addEventListener('submit',async function(event){
    const form=event.target;
    if(!(form instanceof HTMLFormElement)||form.id!=='staffFormFinal') return;

    event.preventDefault();
    event.stopImmediatePropagation();

    const submitButton=form.querySelector('button[type="submit"],button:not([type])');
    const originalLabel=submitButton?.textContent||'Guardar colaborador';
    if(submitButton){submitButton.disabled=true;submitButton.textContent='Guardando…';}

    try{
      const fd=new FormData(form);
      const rawId=String(fd.get('staffId')||'').trim();
      const id=rawId?(Number.isNaN(Number(rawId))?rawId:Number(rawId)):Date.now();
      const idx=staffMembers.findIndex(m=>String(m.id)===String(id));
      const previous=idx>=0?staffMembers[idx]:null;
      const record={
        ...(previous||{}),
        id,
        name:String(fd.get('name')||'').trim(),
        role:String(fd.get('role')||'Asistente'),
        shift:String(fd.get('shift')||'').trim(),
        assignment:String(fd.get('assignment')||'').trim(),
        status:String(fd.get('status')||previous?.status||'Próximo'),
        linkedUserId:previous?.linkedUserId||null
      };

      if(!record.name||!record.shift) throw new Error('Complete el nombre y el horario.');

      await persistStaffRecord(record);

      if(idx>=0) staffMembers[idx]=record;
      else staffMembers.push(record);
      localStorage.setItem('seniorcare-staff',JSON.stringify(staffMembers));

      activeScreen='staff';
      residentScoped=false;
      renderStaff();
      bindActions();
      if(typeof setActiveNav==='function') setActiveNav('more');
      window.showToast?.(idx>=0?'Ficha del trabajador actualizada.':'Colaborador agregado y guardado.');
    }catch(error){
      console.error('Error guardando colaborador:',error);
      window.showToast?.(`No se guardó el colaborador: ${error?.message||error}`);
      form.classList.remove('hidden');
    }finally{
      if(submitButton&&document.body.contains(submitButton)){
        submitButton.disabled=false;
        submitButton.textContent=originalLabel;
      }
    }
  },true);
})();
