/* Bernard Health SeniorCare V3.3.4 — asistencia global incluida para administrador */
(function(){
  'use strict';

  const TABLE='attendance_records';
  let channel=null;
  let busy=false;
  let startedKey='';
  const db=()=>window.seniorcareSupabase||null;
  const user=()=>window.currentUser||null;
  const org=()=>user()?.organizationId||user()?.organization_id||null;
  const role=()=>String(user()?.role||'').toLowerCase();
  const isAdmin=()=>['admin','administrator','supervisor'].includes(role());
  const today=()=>new Date().toLocaleDateString('en-CA',{timeZone:'America/Costa_Rica'});
  const staffKey=()=>`user:${user()?.id||''}`;
  const list=()=>Array.isArray(window.attendanceLog)?window.attendanceLog:(window.attendanceLog=[]);
  const persist=()=>localStorage.setItem('seniorcare-attendance-log',JSON.stringify(list()));
  const toast=message=>window.showToast?.(message);
  const roleLabel=()=>({nurse:'Enfermería',assistant:'Asistente',guard:'Guarda de seguridad',security:'Guarda de seguridad',cook:'Cocina',kitchen:'Cocina',cleaning:'Miscelánea',miscellaneous:'Miscelánea'}[role()]||user()?.role||'Personal');

  function rowToLocal(row){
    return {
      id:row.client_id||Date.parse(row.updated_at)||Date.now(),
      remoteId:row.id,
      staffId:row.staff_key,
      userId:row.user_id||null,
      name:row.staff_name,
      role:row.role_name,
      date:row.work_date,
      clockIn:row.clock_in,
      clockOut:row.clock_out
    };
  }

  function mergeRows(rows){
    const target=list();
    for(const row of rows||[]){
      const incoming=rowToLocal(row);
      const idx=target.findIndex(x=>String(x.staffId)===String(incoming.staffId)&&String(x.date)===String(incoming.date));
      if(idx<0)target.push(incoming);
      else target[idx]={...target[idx],...incoming,id:target[idx].id||incoming.id};
    }
    persist();
  }

  function myTodayLog(){
    const uid=String(user()?.id||'');
    const key=staffKey();
    return [...list()].reverse().find(x=>String(x.date)===today()&&(String(x.staffId)===key||String(x.userId||'')===uid))||null;
  }

  async function pullAttendance(){
    const client=db(); if(!client||!org()||!user()?.id)return [];
    let query=client.from(TABLE).select('*').eq('organization_id',org()).order('work_date',{ascending:false}).limit(1500);
    if(!isAdmin())query=query.eq('user_id',user().id);
    const {data,error}=await query;
    if(error)throw error;
    mergeRows(data||[]);
    refreshVisibleAttendance();
    return data||[];
  }

  function refreshVisibleAttendance(){
    try{
      const screen=String(window.activeScreen||'');
      if(isAdmin()&&screen==='staff'&&typeof window.renderStaff==='function'){
        const y=window.scrollY; window.renderStaff(); window.bindActions?.(); requestAnimationFrame(()=>window.scrollTo(0,y));
      }else if(role()==='nurse'&&screen==='staff'&&typeof window.renderStaff==='function'){
        const y=window.scrollY; window.renderStaff(); window.bindActions?.(); requestAnimationFrame(()=>window.scrollTo(0,y));
      }else if(['home','staff'].includes(screen)&&typeof window.render==='function'){
        const y=window.scrollY; window.render(); requestAnimationFrame(()=>window.scrollTo(0,y));
      }
    }catch(err){console.warn('No se pudo refrescar asistencia:',err);}
  }

  async function saveMark(action){
    if(busy||!db()||!org()||!user()?.id)return;
    busy=true;
    try{
      const {data:rows,error:readError}=await db().from(TABLE)
        .select('*')
        .eq('organization_id',org())
        .eq('user_id',user().id)
        .eq('work_date',today())
        .order('updated_at',{ascending:false});
      if(readError)throw readError;
      const open=(rows||[]).find(r=>r.clock_in&&!r.clock_out)||null;
      const closed=(rows||[]).find(r=>r.clock_in&&r.clock_out)||null;
      const now=new Date().toISOString();

      if(action==='in'){
        if(open||closed){mergeRows(rows||[]);toast(closed?'La jornada de hoy ya está cerrada.':'La entrada ya está registrada.');refreshVisibleAttendance();return;}
        const payload={organization_id:org(),user_id:user().id,staff_key:staffKey(),staff_name:user().name||user().full_name||'Personal',role_name:roleLabel(),work_date:today(),clock_in:now,clock_out:null,client_id:Date.now(),updated_at:now};
        const {error}=await db().from(TABLE).upsert(payload,{onConflict:'organization_id,staff_key,work_date'});
        if(error)throw error;
      }else{
        if(closed&&!open){mergeRows(rows||[]);toast('La jornada de hoy ya está cerrada.');refreshVisibleAttendance();return;}
        if(!open)throw new Error('No existe una entrada abierta para registrar la salida.');
        const {error}=await db().from(TABLE).update({clock_out:now,updated_at:now}).eq('id',open.id).eq('user_id',user().id);
        if(error)throw error;
      }

      await pullAttendance();
      toast(action==='in'?'Entrada registrada y sincronizada.':'Salida registrada y sincronizada.');
    }catch(err){
      console.error('Asistencia global V3.3.4:',err);
      toast(`No se guardó la marca: ${err?.message||String(err)}`);
    }finally{busy=false;}
  }

  async function subscribe(){
    const client=db(); if(!client||!org()||!user()?.id)return;
    if(channel){try{await client.removeChannel(channel);}catch(_e){}channel=null;}
    channel=client.channel(`attendance-global-v334-${org()}-${user().id}`);
    channel.on('postgres_changes',{event:'*',schema:'public',table:TABLE,filter:`organization_id=eq.${org()}`},async()=>{
      try{await pullAttendance();}catch(err){console.warn('Realtime asistencia:',err);}
    });
    channel.subscribe(status=>{window.SENIORCARE_ATTENDANCE_REALTIME_STATUS=status;});
  }

  async function start(){
    if(!db()||!org()||!user()?.id)return;
    const key=`${org()}:${user().id}`;
    if(startedKey===key)return;
    startedKey=key;
    try{await pullAttendance();await subscribe();window.SENIORCARE_ATTENDANCE_GLOBAL_VERSION='3.3.4';}
    catch(err){console.error('Inicio asistencia global:',err);toast(`Asistencia pendiente de sincronizar: ${err?.message||String(err)}`);}
  }

  document.addEventListener('click',event=>{
    const button=event.target.closest?.('#nurseStaffClockInV168,#nurseStaffClockOutV168,#assistantClockIn,#assistantClockOut,#selfClockIn,#selfClockOut,[data-self-clock-in],[data-self-clock-out]');
    if(!button)return;
    // El Asistente ya usa guardado directo en el núcleo V2.0.4; dejamos que ese flujo opere.
    if(role()==='assistant'&&['assistantClockIn','assistantClockOut','selfClockIn','selfClockOut'].includes(button.id))return;
    event.preventDefault();event.stopImmediatePropagation();
    const action=/out/i.test(button.id||'')||button.hasAttribute('data-self-clock-out')?'out':'in';
    saveMark(action);
  },true);

  window.syncSeniorCareAttendanceGlobal=pullAttendance;
  window.addEventListener('seniorcare:user-ready',()=>{startedKey='';start();});
  window.addEventListener('focus',()=>{if(user()?.id)pullAttendance().catch(()=>{});});
  window.addEventListener('online',()=>{if(user()?.id)pullAttendance().catch(()=>{});});
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',()=>setTimeout(start,500),{once:true});
  else setTimeout(start,500);
})();
