/* Bernard Health SeniorCare V1.4.7 — historial de asistencia y asignación de residentes */
(function(){
  'use strict';

  const esc=v=>String(v??'').replace(/[&<>'"]/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[m]));
  const assignmentsKey='seniorcare-resident-assignments';
  let residentAssignments=JSON.parse(localStorage.getItem(assignmentsKey)||'{}');
  window.residentAssignments=residentAssignments;
  window.saveResidentAssignments=()=>localStorage.setItem(assignmentsKey,JSON.stringify(residentAssignments));

  const roleKey=role=>String(role||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'').trim();
  const isAssistant=m=>roleKey(m?.role).includes('asistente');
  const staffAccessKey=m=>String(m?.id??'');
  const assignedIdsFor=m=>Array.isArray(residentAssignments[staffAccessKey(m)])?residentAssignments[staffAccessKey(m)].map(String):[];
  window.getAssignedResidentsForStaff=m=>residents.filter(r=>assignedIdsFor(m).includes(String(r?.resident_key??r.id))||assignedIdsFor(m).includes(String(r.id)));

  const fmtTime=value=>value?new Date(value).toLocaleTimeString('es-CR',{hour:'2-digit',minute:'2-digit'}):'—';
  const fmtDate=value=>{
    if(!value)return '—';
    const d=new Date(String(value).length===10?value+'T12:00:00':value);
    return Number.isNaN(d.getTime())?String(value):d.toLocaleDateString('es-CR');
  };
  const hoursFor=log=>{
    if(!log?.clockIn||!log?.clockOut)return '—';
    return ((new Date(log.clockOut)-new Date(log.clockIn))/3600000).toFixed(2);
  };
  const download=(name,content,type)=>{
    const blob=new Blob([content],{type});
    const url=URL.createObjectURL(blob);
    const a=document.createElement('a');a.href=url;a.download=name;a.click();
    setTimeout(()=>URL.revokeObjectURL(url),1000);
  };
  const attendanceFiltered=()=>{
    const from=document.getElementById('attendanceHistoryFrom')?.value||'';
    const to=document.getElementById('attendanceHistoryTo')?.value||'';
    return [...(window.attendanceLog||[])].filter(x=>(!from||x.date>=from)&&(!to||x.date<=to)).sort((a,b)=>String(b.date).localeCompare(String(a.date))||Number(b.id)-Number(a.id));
  };
  const attendanceRowsHtml=logs=>logs.length?logs.map(x=>`<tr><td>${esc(fmtDate(x.date))}</td><td>${esc(x.name||'Sin nombre')}</td><td>${esc(x.role||'Sin puesto')}</td><td>${esc(fmtTime(x.clockIn))}</td><td>${esc(fmtTime(x.clockOut))}</td><td>${esc(hoursFor(x))}</td></tr>`).join(''):`<tr><td colspan="6" class="attendance-empty-cell">No hay marcas registradas en este periodo.</td></tr>`;

  const currentAssistantStaff=()=>{
    const uid=String(currentUser?.id||'');
    const name=String(currentUser?.name||'').toLowerCase();
    return staffMembers.find(m=>String(m.linkedUserId||'')===uid)
      || staffMembers.find(m=>String(m.name||'').toLowerCase()===name)
      || staffMembers.find(m=>name&&String(m.name||'').toLowerCase().includes(name.split(' ')[0]));
  };
  const currentAssignedResidents=()=>window.getAssignedResidentsForStaff?.(currentAssistantStaff())||[];
  const assistantResidentChooser=(kicker,title,subtitle,target,icon='users')=>{
    const list=currentAssignedResidents();
    main.innerHTML=pageHeader(kicker,title,subtitle)+`<section class="assistant-assigned-module-list">${list.length?list.map(r=>`<button class="resident-card professional-resident-card" data-assigned-module-resident="${r.id}" data-assigned-module-target="${target}"><div class="avatar">${esc(r.name.split(' ').map(x=>x[0]).slice(0,2).join(''))}</div><div class="resident-card-copy"><strong>${esc(r.name)}</strong><span>${esc(r.room)} · ${esc(r.diet)}</span><small>Abrir expediente y registrar</small></div><b class="resident-arrow">›</b></button>`).join(''):empty('No tiene residentes asignados. Administración debe realizar la asignación desde Personal y asistencia.')}</section>`;
  };
  const ensureAssistantResident=(target,kicker,title,subtitle,original)=>function(){
    if(currentUser?.role!=='assistant'){original();return;}
    const allowed=currentAssignedResidents();
    if(!residentScoped||!allowed.some(r=>String(r?.resident_key??r.id)===String(selectedResident?.resident_key??selectedResident?.id)||String(r.id)===String(selectedResident?.id))){residentScoped=false;assistantResidentChooser(kicker,title,subtitle,target);return;}
    original();
  };
  const priorRenderVitals=renderVitals,priorRenderAgenda=renderAgenda,priorRenderNutrition=renderNutrition,priorRenderIncidents=renderIncidents;
  renderVitals=ensureAssistantResident('vitals','CONTROL CLÍNICO','Signos vitales','Seleccione uno de sus residentes asignados',priorRenderVitals);
  renderAgenda=ensureAssistantResident('agenda','AGENDA Y TRASLADOS','Citas y traslados','Seleccione uno de sus residentes asignados',priorRenderAgenda);
  renderNutrition=ensureAssistantResident('nutrition','ALIMENTACIÓN E HIDRATACIÓN','Registro de alimentación','Seleccione uno de sus residentes asignados',priorRenderNutrition);
  renderIncidents=ensureAssistantResident('incidents','SEGURIDAD Y SEGUIMIENTO','Incidentes','Seleccione uno de sus residentes asignados',priorRenderIncidents);

  const previousRenderStaff=renderStaff;
  renderStaff=function(){
    previousRenderStaff();
    if(currentUser?.role!=='admin')return;

    const directory=main.querySelector('.staff-directory-pro');
    if(directory){
      [...directory.querySelectorAll('.staff-profile-card')].forEach((card,index)=>{
        const member=staffMembers[index];
        if(!member||!isAssistant(member))return;
        const ids=assignedIdsFor(member);
        const assignedNames=residents.filter(r=>ids.includes(String(r?.resident_key??r.id))||ids.includes(String(r.id))).map(r=>r.name);
        card.insertAdjacentHTML('beforeend',`<details class="assistant-assignment-box" data-assignment-box="${member.id}">
          <summary><span>RESIDENTES ASIGNADOS</span><strong>${assignedNames.length?esc(assignedNames.join(', ')):'Sin residentes asignados'}</strong></summary>
          <div class="assistant-assignment-list">
            ${residents.map(r=>`<label><input type="checkbox" value="${r.id}" ${(ids.includes(String(r?.resident_key??r.id))||ids.includes(String(r.id)))?'checked':''}><span><strong>${esc(r.name)}</strong><small>${esc(r.room)} · ${esc(r.diet)}</small></span></label>`).join('')}
          </div>
          <div class="form-actions"><button type="button" class="primary-btn" data-save-resident-assignment="${member.id}">Guardar asignación</button></div>
        </details>`);
      });
    }

    const all=[...(window.attendanceLog||[])].sort((a,b)=>String(b.date).localeCompare(String(a.date))||Number(b.id)-Number(a.id));
    main.insertAdjacentHTML('beforeend',`<section class="history-card attendance-history-admin">
      <div class="attendance-history-head"><div><span>REGISTRO PERMANENTE</span><h3>Historial de marcas del personal</h3><p>Entradas y salidas guardadas por fecha para consulta administrativa.</p></div><strong>${all.length} marcas</strong></div>
      <div class="attendance-history-toolbar">
        <label>Desde<input type="date" id="attendanceHistoryFrom"></label>
        <label>Hasta<input type="date" id="attendanceHistoryTo"></label>
        <button type="button" class="secondary-btn" id="filterAttendanceHistory">Aplicar filtro</button>
        <button type="button" class="secondary-btn" id="clearAttendanceHistoryFilter">Mostrar todo</button>
        <button type="button" class="primary-btn" id="exportAttendanceExcel">Exportar Excel</button>
        <button type="button" class="secondary-btn" id="exportAttendancePdf">Imprimir / PDF</button>
      </div>
      <div class="attendance-table-wrap"><table class="attendance-history-table"><thead><tr><th>Fecha</th><th>Colaborador</th><th>Puesto</th><th>Entrada</th><th>Salida</th><th>Horas</th></tr></thead><tbody id="attendanceHistoryBody">${attendanceRowsHtml(all)}</tbody></table></div>
    </section>`);
  };

  const previousBindActions=bindActions;
  bindActions=function(){
    previousBindActions();

    document.querySelectorAll('[data-save-resident-assignment]').forEach(btn=>btn.addEventListener('click',()=>{
      const id=String(btn.dataset.saveResidentAssignment);
      const box=document.querySelector(`[data-assignment-box="${CSS.escape(id)}"]`);
      residentAssignments[id]=[...(box?.querySelectorAll('input[type="checkbox"]:checked')||[])].map(x=>String(x.value));
      window.saveResidentAssignments();
      renderStaff();bindActions();showToast('Residentes asignados al asistente.');
    }));

    document.querySelectorAll('[data-assigned-module-resident]').forEach(btn=>btn.addEventListener('click',()=>{
      const resident=currentAssignedResidents().find(r=>String(r?.resident_key??r.id)===String(btn.dataset.assignedModuleResident)||String(r.id)===String(btn.dataset.assignedModuleResident));
      if(!resident)return;
      go(btn.dataset.assignedModuleTarget,{resident,scope:'resident'});
    }));

    const refreshHistory=()=>{
      const body=document.getElementById('attendanceHistoryBody');
      if(body)body.innerHTML=attendanceRowsHtml(attendanceFiltered());
    };
    document.getElementById('filterAttendanceHistory')?.addEventListener('click',refreshHistory);
    document.getElementById('clearAttendanceHistoryFilter')?.addEventListener('click',()=>{
      const f=document.getElementById('attendanceHistoryFrom'),t=document.getElementById('attendanceHistoryTo');
      if(f)f.value='';if(t)t.value='';refreshHistory();
    });
    document.getElementById('exportAttendanceExcel')?.addEventListener('click',()=>{
      const logs=attendanceFiltered();
      const html=`<html><head><meta charset="UTF-8"></head><body><table border="1"><tr><th>Fecha</th><th>Colaborador</th><th>Puesto</th><th>Entrada</th><th>Salida</th><th>Horas</th></tr>${attendanceRowsHtml(logs)}</table></body></html>`;
      download('historial-asistencia-seniorcare.xls',html,'application/vnd.ms-excel;charset=utf-8');
    });
    document.getElementById('exportAttendancePdf')?.addEventListener('click',()=>{
      const logs=attendanceFiltered();
      const w=window.open('','_blank','noopener');
      if(!w)return;
      w.document.write(`<html><head><title>Historial de asistencia</title><style>body{font-family:Arial;padding:28px;color:#241b33}h1{color:#5b28b8}table{width:100%;border-collapse:collapse}th,td{border:1px solid #ddd;padding:9px;text-align:left}th{background:#f3ecff}</style></head><body><h1>Historial de asistencia del personal</h1><table><tr><th>Fecha</th><th>Colaborador</th><th>Puesto</th><th>Entrada</th><th>Salida</th><th>Horas</th></tr>${attendanceRowsHtml(logs)}</table><script>window.onload=()=>window.print()<\/script></body></html>`);
      w.document.close();
    });
  };

  window.renderStaff=renderStaff;
  window.renderVitals=renderVitals;
  window.renderAgenda=renderAgenda;
  window.renderNutrition=renderNutrition;
  window.renderIncidents=renderIncidents;
  window.bindActions=bindActions;
})();
