/* Bernard Health SeniorCare V4.3.73 — archivo histórico aislado de resultados médicos */
(function(){
'use strict';
const originalRenderMedicalResults=window.renderMedicalResults;
if(typeof originalRenderMedicalResults!=='function')return;
const db=()=>window.seniorcareSupabase;
const user=()=>window.currentUser||{};
const org=()=>user().organizationId||user().organization_id;
const role=()=>String(user().role||'').toLowerCase();
const main=()=>window.main||document.getElementById('mainContent');
const esc=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
const toast=t=>window.showToast?.(t);
const header=(e,t,s)=>window.pageHeader?.(e,t,s)||`<h2>${esc(t)}</h2>`;
const missing=e=>e?.code==='PGRST205'||/schema cache|could not find the table/i.test(String(e?.message||''));
async function q(table,build){const r=await build(db().from(table));if(r.error){if(missing(r.error))return[];throw r.error}return r.data||[]}
let residents=[];
let results=[];
let archiveRows=[];
let state={tab:'recent',residentKey:'',search:''};
const data=r=>r?.data||{};
const rname=r=>r?.full_name||r?.resident_name||r?.name||data(r)?.name||data(r)?.full_name||'Residente';
const residentKey=r=>String(r?.resident_key??data(r)?.resident_key??r?.id??data(r)?.id??'');
const resident=k=>residents.find(r=>residentKey(r)===String(k));
const resultId=r=>String(r?.id??'');
const normalize=v=>String(v??'').normalize('NFD').replace(/[\u0300-\u036f]/g,'').toLowerCase().trim();
const dateLabel=v=>{if(!v)return'Fecha no registrada';const raw=String(v);const d=new Date(raw.length<=10?`${raw}T12:00:00`:raw);return Number.isNaN(d.getTime())?raw:d.toLocaleDateString('es-CR',{day:'numeric',month:'long',year:'numeric'})};
const initials=v=>String(v||'R').trim().split(/\s+/).slice(0,2).map(x=>x[0]||'').join('').toUpperCase();
const fileIcon=()=>`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 3.75h6.7L18.25 8.3V20.25H7z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><path d="M13.5 3.9v4.7h4.6M9.5 13h6M9.5 16h4.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>`;
const folderIcon=()=>`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3.75 7.5h6l1.7 2h8.8v8.75a2 2 0 0 1-2 2H5.75a2 2 0 0 1-2-2z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><path d="M3.75 9.5V6.25a2 2 0 0 1 2-2h3.2l1.6 2h7.7a2 2 0 0 1 2 2V9.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></svg>`;
async function load(){
 residents=await q('seniorcare_residents',x=>x.select('*').eq('organization_id',org()).eq('active',true));
 results=await q('seniorcare_medical_results',x=>x.select('*').eq('organization_id',org()).eq('active',true).order('result_date',{ascending:false}));
 for(const r of results){if(r.file_path){const sg=await db().storage.from('medical-results').createSignedUrl(r.file_path,3600);if(!sg.error)r.file_url=sg.data.signedUrl}}
 archiveRows=await q('seniorcare_medical_result_archive',x=>x.select('*').eq('organization_id',org()).eq('active',true).order('archived_at',{ascending:false}));
}
function resultCard(r,{archived=false}={}){
 const patient=rname(resident(r.resident_key)),name=r.study_name||r.result_type||'Estudio clínico',search=normalize(`${patient} ${name} ${r.result_type||''} ${r.summary||''} ${r.file_name||''} ${r.result_date||''}`);
 return `<article class="bhra-result-card" data-bhra-search="${esc(search)}">
  <div class="bhra-result-avatar">${esc(initials(patient))}</div>
  <div class="bhra-result-copy">
   <div class="bhra-result-topline"><strong>${esc(name)}</strong><span class="bhra-status ${normalize(r.status).includes('revis')?'is-reviewed':'is-pending'}">${esc(r.status||'Pendiente')}</span></div>
   <h4>${esc(patient)}</h4>
   <div class="bhra-meta"><span>${esc(r.result_type||'Estudio')}</span><span>${esc(dateLabel(r.result_date))}</span>${r.uploaded_by_name?`<span>Enviado por ${esc(r.uploaded_by_name)}</span>`:''}</div>
   ${r.summary?`<p>${esc(r.summary)}</p>`:''}
   ${r.interpretation?`<div class="bhra-interpretation"><b>Interpretación médica</b><span>${esc(r.interpretation)}</span></div>`:''}
   ${r.file_name?`<small class="bhra-file-name">${fileIcon()} ${esc(r.file_name)}</small>`:''}
  </div>
  <div class="bhra-actions">
   ${r.file_url?`<a class="bhra-btn bhra-btn-light" href="${esc(r.file_url)}" target="_blank" rel="noopener">Abrir archivo</a>`:''}
   <button type="button" class="bhra-btn bhra-btn-light" data-bhra-review="${esc(resultId(r))}">${r.interpretation?'Editar interpretación':'Interpretar'}</button>
   ${archived?`<button type="button" class="bhra-btn bhra-btn-restore" data-bhra-restore="${esc(resultId(r))}">Restaurar a recientes</button>`:`<button type="button" class="bhra-btn bhra-btn-primary" data-bhra-archive="${esc(resultId(r))}">Archivar</button>`}
  </div>
 </article>`;
}
function resultFolders(archived){
 const grouped=new Map();
 for(const r of archived){const key=String(r.resident_key||'');if(!grouped.has(key))grouped.set(key,[]);grouped.get(key).push(r)}
 const folders=[...grouped.entries()].map(([key,items])=>{items.sort((a,b)=>String(b.result_date||'').localeCompare(String(a.result_date||'')));const patient=rname(resident(key)),last=items[0],types=[...new Set(items.map(x=>x.result_type).filter(Boolean))].slice(0,3);return {key,items,patient,last,types}}).sort((a,b)=>a.patient.localeCompare(b.patient,'es'));
 if(!folders.length)return`<div class="bhra-empty">${folderIcon()}<h3>Aún no hay estudios archivados</h3><p>Cuando archive un resultado, aparecerá dentro de la carpeta del paciente.</p></div>`;
 return `<div class="bhra-folder-grid">${folders.map(f=>`<button type="button" class="bhra-folder-card" data-bhra-folder="${esc(f.key)}" data-bhra-search="${esc(normalize(`${f.patient} ${f.types.join(' ')} ${f.last?.result_date||''}`))}"><span class="bhra-folder-icon">${folderIcon()}</span><span class="bhra-folder-copy"><strong>${esc(f.patient)}</strong><small>${f.items.length} ${f.items.length===1?'estudio archivado':'estudios archivados'}</small><em>Último: ${esc(dateLabel(f.last?.result_date))}</em>${f.types.length?`<span>${esc(f.types.join(' · '))}</span>`:''}</span><b>›</b></button>`).join('')}</div>`;
}
function bindSearch(root){
 const input=root.querySelector('[data-bhra-search-input]'),empty=root.querySelector('[data-bhra-search-empty]');if(!input)return;
 input.value=state.search||'';
 const apply=()=>{state.search=input.value;const term=normalize(input.value);let visible=0;root.querySelectorAll('[data-bhra-search]').forEach(el=>{const show=!term||String(el.dataset.bhraSearch||'').includes(term);el.hidden=!show;if(show)visible++});if(empty)empty.hidden=visible>0||!term};
 input.addEventListener('input',apply);apply();
}
function bindActions(root,redraw){
 root.querySelectorAll('[data-bhra-tab]').forEach(b=>b.onclick=()=>{state.tab=b.dataset.bhraTab;state.residentKey='';state.search='';redraw()});
 root.querySelectorAll('[data-bhra-folder]').forEach(b=>b.onclick=()=>{state.residentKey=b.dataset.bhraFolder;state.search='';redraw()});
 root.querySelector('[data-bhra-folder-back]')?.addEventListener('click',()=>{state.residentKey='';state.search='';redraw()});
 root.querySelectorAll('[data-bhra-review]').forEach(b=>b.onclick=async()=>{const r=results.find(x=>resultId(x)===String(b.dataset.bhraReview));if(!r)return;const text=prompt('Interpretación médica:',r.interpretation||'');if(text===null)return;const {error}=await db().from('seniorcare_medical_results').update({interpretation:text,status:'Revisado',reviewed_by:user().id,reviewed_by_name:user().name||user().email,updated_at:new Date().toISOString()}).eq('id',r.id);if(error)return toast(error.message);toast('Resultado revisado.');window.renderMedicalResults()});
 root.querySelectorAll('[data-bhra-archive]').forEach(b=>b.onclick=async()=>{const r=results.find(x=>resultId(x)===String(b.dataset.bhraArchive));if(!r)return;if(!confirm(`¿Archivar ${r.study_name||'este estudio'} dentro de la carpeta de ${rname(resident(r.resident_key))}?`))return;const now=new Date().toISOString(),row={organization_id:org(),result_id:resultId(r),resident_key:String(r.resident_key),archived_by:user().id,archived_by_name:user().name||user().email,archived_at:now,active:true,updated_at:now,unarchived_at:null,unarchived_by:null};const {error}=await db().from('seniorcare_medical_result_archive').upsert(row,{onConflict:'organization_id,result_id'});if(error)return toast(error.message);toast('Estudio archivado en la carpeta del paciente.');window.renderMedicalResults()});
 root.querySelectorAll('[data-bhra-restore]').forEach(b=>b.onclick=async()=>{const r=results.find(x=>resultId(x)===String(b.dataset.bhraRestore));if(!r)return;const now=new Date().toISOString();const {error}=await db().from('seniorcare_medical_result_archive').update({active:false,unarchived_at:now,unarchived_by:user().id,updated_at:now}).eq('organization_id',org()).eq('result_id',resultId(r));if(error)return toast(error.message);toast('Estudio restaurado a Resultados recientes.');window.renderMedicalResults()});
 bindSearch(root);
}
function renderDoctorResults(m){
 const archivedIds=new Set(archiveRows.filter(x=>x.active!==false).map(x=>String(x.result_id)));
 const recent=results.filter(r=>!archivedIds.has(resultId(r)));
 const archived=results.filter(r=>archivedIds.has(resultId(r)));
 const draw=()=>{
  const tab=state.tab==='archive'?'archive':'recent';
  const folderKey=state.residentKey;
  let body='';
  if(tab==='recent'){
   body=`<div class="bhra-section-head"><div><span>ENTRADA CLÍNICA</span><h3>Resultados recientes</h3><p>Estudios pendientes, revisados y aún no archivados.</p></div><div class="bhra-count">${recent.length}</div></div><div class="bhra-toolbar"><label>Buscar resultado<input data-bhra-search-input type="search" placeholder="Paciente, estudio o fecha"></label></div><div class="bhra-list">${recent.map(r=>resultCard(r)).join('')||`<div class="bhra-empty">${fileIcon()}<h3>No hay resultados recientes</h3><p>Los nuevos estudios enviados aparecerán aquí.</p></div>`}<div class="bhra-empty bhra-search-empty" data-bhra-search-empty hidden><h3>Sin coincidencias</h3><p>Pruebe con otro nombre, estudio o fecha.</p></div></div>`;
  }else if(folderKey){
   const patientResults=archived.filter(r=>String(r.resident_key)===String(folderKey));const patientName=rname(resident(folderKey));
   body=`<button type="button" class="bhra-folder-back" data-bhra-folder-back>‹ Volver a las carpetas</button><div class="bhra-patient-archive-head"><div class="bhra-result-avatar large">${esc(initials(patientName))}</div><div><span>HISTORIAL DE ESTUDIOS</span><h3>${esc(patientName)}</h3><p>${patientResults.length} ${patientResults.length===1?'estudio archivado':'estudios archivados'} en orden cronológico.</p></div></div><div class="bhra-toolbar"><label>Buscar en esta carpeta<input data-bhra-search-input type="search" placeholder="Estudio, tipo o fecha"></label></div><div class="bhra-list">${patientResults.map(r=>resultCard(r,{archived:true})).join('')}<div class="bhra-empty bhra-search-empty" data-bhra-search-empty hidden><h3>Sin coincidencias</h3><p>Pruebe con otro estudio o fecha.</p></div></div>`;
  }else{
   body=`<div class="bhra-section-head"><div><span>ARCHIVO CLÍNICO</span><h3>Carpetas por paciente</h3><p>Histórico organizado sin mover ni eliminar los archivos originales.</p></div><div class="bhra-count">${new Set(archived.map(r=>String(r.resident_key))).size}</div></div><div class="bhra-toolbar"><label>Buscar paciente<input data-bhra-search-input type="search" placeholder="Nombre del paciente o tipo de estudio"></label></div>${resultFolders(archived)}<div class="bhra-empty bhra-search-empty" data-bhra-search-empty hidden><h3>Sin coincidencias</h3><p>Pruebe con otro paciente o tipo de estudio.</p></div>`;
  }
  m.innerHTML=header('RESULTADOS','Resultados médicos','Revise los estudios recientes y consulte el historial organizado por paciente')+`<section class="bhra-shell"><nav class="bhra-tabs" aria-label="Vistas de resultados"><button type="button" data-bhra-tab="recent" class="${tab==='recent'?'active':''}">Recientes <span>${recent.length}</span></button><button type="button" data-bhra-tab="archive" class="${tab==='archive'?'active':''}">Archivo por paciente <span>${archived.length}</span></button></nav><div class="bhra-content">${body}</div></section>`;
  bindActions(m,draw);
 };
 draw();
}
window.renderMedicalResults=async function(){
 if(role()!=='doctor')return originalRenderMedicalResults.apply(this,arguments);
 try{await load()}catch(e){return toast(e.message)}
 const m=main();if(!m)return;
 renderDoctorResults(m);
};
})();
