/* Bernard Health SeniorCare V4.3.31 — privacidad, sesión e historial financiero administrable */
(()=>{
'use strict';
if(window.__BHSC_HARDENING_V4325)return;
window.__BHSC_HARDENING_V4325=true;

const VERSION='4.3.31';
const IDLE_LIMIT_MS=30*60*1000;
const PAGE_SIZE=12;
const ARCHIVE_PAGE_SIZE=8;
let idleTimer=null;
let historyTimer=null;
const db=()=>window.seniorcareSupabase;
const esc=v=>String(v??'').replace(/[&<>'"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c]));
const money=n=>new Intl.NumberFormat('es-CR',{style:'currency',currency:'CRC',maximumFractionDigits:0}).format(Number(n||0));
const fmt=d=>d?new Date(d).toLocaleString('es-CR',{dateStyle:'medium',timeStyle:'short'}):'Sin registro';
const toast=m=>window.showToast?window.showToast(m):alert(m);
const periodLabel=value=>{
 const text=String(value||'').trim();
 if(/^\d{4}-\d{2}-\d{2}$/.test(text)){
  const date=new Date(`${text}T12:00:00`);
  return date.toLocaleDateString('es-CR',{month:'long',year:'numeric'});
 }
 return text||'Período registrado';
};

async function expireIdleSession(){
 if(!window.currentUser?.id)return;
 try{window.BHSC_CLEAR_PRIVATE_STORAGE?.();}catch(_){ }
 try{await db()?.auth?.signOut();}catch(_){ }
 try{sessionStorage.clear();}catch(_){ }
 alert('La sesión se cerró por 30 minutos de inactividad para proteger la información de los residentes.');
 location.reload();
}

function resetIdle(){
 if(!window.currentUser?.id)return;
 clearTimeout(idleTimer);
 idleTimer=setTimeout(expireIdleSession,IDLE_LIMIT_MS);
}
['pointerdown','keydown','touchstart','scroll'].forEach(type=>window.addEventListener(type,resetIdle,{passive:true}));
window.addEventListener('seniorcare:user-ready',resetIdle);
window.addEventListener('beforeunload',()=>clearTimeout(idleTimer));

async function paymentAction(action,id){
 const names={
  archive:['bh_archive_payment_record_v4331'],
  restore:['bh_restore_payment_record_v4331'],
  delete:['bh_delete_payment_record_v4331']
 }[action];
 if(!names)throw new Error('Acción financiera no válida.');
 const args={p_payment_id:id};
 const result=window.BHSC_CALL_RPC
  ?await window.BHSC_CALL_RPC(names,args)
  :await db().rpc(names[0],args);
 if(result?.error){
  const missing=window.BHSC_RPC_FUNCTION_MISSING?.(result.error)||/function .* does not exist|schema cache/i.test(String(result.error.message||''));
  throw new Error(missing?'Ejecute el SQL V4.3.31 en Supabase para habilitar Archivar y Eliminar.':String(result.error.message||'No se pudo completar la acción.'));
 }
 return result?.data;
}

function paymentCard(row,orgMap,archived=false){
 const org=orgMap.get(String(row.organization_id));
 const method=row.payment_method||'Confirmación de licencia';
 const detail=row.data&&typeof row.data==='object'?row.data:{};
 const adminBase=Number(detail.administrative_base??0);
 const modulesTotal=Number(detail.modules_total??0);
 const moduleCount=Number(detail.module_count??0);
 const breakdown=(adminBase||modulesTotal)
  ?`<span class="payment-history-breakdown-v4330">Panel ${money(adminBase)} + ${moduleCount} módulo${moduleCount===1?'':'s'} ${money(modulesTotal)}</span>`
  :'';
 const controls=archived
  ?`<button type="button" class="mini-btn" data-payment-restore-v4331="${esc(row.id)}">Restaurar</button><button type="button" class="mini-btn payment-history-delete-v4331" data-payment-delete-v4331="${esc(row.id)}">Eliminar</button>`
  :`<button type="button" class="mini-btn" data-payment-archive-v4331="${esc(row.id)}">Archivar</button><button type="button" class="mini-btn payment-history-delete-v4331" data-payment-delete-v4331="${esc(row.id)}">Eliminar</button>`;
 return `<article class="payment-history-card-v4331${archived?' is-archived':''}"><div class="payment-history-copy-v4331"><small>${esc(periodLabel(row.billing_period))}</small><h3>${esc(org?.name||'Organización')}</h3><p>${esc(method)}${row.reference?` · Ref. ${esc(row.reference)}`:''} · ${archived?'Archivado':'Confirmado'}</p>${breakdown}</div><div class="payment-history-side-v4331"><strong>${money(row.amount)}</strong><small>${esc(fmt(row.confirmed_at))}</small><div class="payment-history-actions-v4331">${controls}</div></div></article>`;
}

async function appendPaymentHistory(){
 if(String(window.currentUser?.role||'').toLowerCase()!=='supervisor')return;
 if(window.activeScreen!=='supervisorPayments')return;
 const root=document.getElementById('mainContent');
 if(!root)return;
 if(root.querySelector('[data-payment-history-v4331]'))return;
 root.querySelectorAll('[data-payment-history-v4329],[data-payment-history-v4325]').forEach(node=>node.remove());

 const section=document.createElement('section');
 section.dataset.paymentHistoryV4331='1';
 section.className='payment-history-v4325';
 section.innerHTML='<div class="supv-loading">Cargando historial financiero…</div>';
 root.appendChild(section);

 const [result,orgResult]=await Promise.all([
   db().from('seniorcare_payment_records')
     .select('id,organization_id,billing_period,amount,currency,payment_method,reference,notes,status,confirmed_at,archived_at,data')
     .in('status',['confirmed','archived'])
     .order('confirmed_at',{ascending:false}).limit(500),
   db().from('organizations').select('id,name')
 ]);
 if(window.activeScreen!=='supervisorPayments'||!section.isConnected)return;
 if(orgResult.error){
   section.innerHTML=`<div class="empty-state"><strong>No se pudieron cargar las organizaciones</strong><span>${esc(orgResult.error.message)}</span></div>`;
   return;
 }
 if(result.error){
   const missing=/could not find the table|relation .* does not exist|schema cache|archived_at/i.test(result.error.message||'');
   section.innerHTML=`<div class="empty-state"><strong>${missing?'Falta instalar la actualización financiera':'No se pudo cargar el historial financiero'}</strong><span>${missing?'Ejecute el SQL V4.3.31 en Supabase y vuelva a abrir Pagos.':esc(result.error.message)}</span></div>`;
   return;
 }

 const orgMap=new Map((orgResult.data||[]).map(o=>[String(o.id),o]));
 const all=result.data||[];
 const confirmed=all.filter(row=>String(row.status||'confirmed').toLowerCase()==='confirmed');
 const archived=all.filter(row=>String(row.status||'').toLowerCase()==='archived');
 let confirmedVisible=PAGE_SIZE;
 let archivedVisible=ARCHIVE_PAGE_SIZE;

 const render=()=>{
  const visibleConfirmed=confirmed.slice(0,confirmedVisible);
  const visibleArchived=archived.slice(0,archivedVisible);
  const total=confirmed.reduce((sum,row)=>sum+Number(row.amount||0),0);
  section.innerHTML=`
   <div class="payment-history-head-v4325"><div><span>REGISTRO FINANCIERO</span><h2>Historial de pagos confirmados</h2><p>Se muestran los pagos vigentes. Los registros archivados permanecen disponibles sin alargar la página.</p></div><strong>${confirmed.length}</strong></div>
   ${confirmed.length?`<div class="payment-history-total-v4329"><span>Total histórico visible</span><strong>${money(total)}</strong></div>`:''}
   <div class="payment-history-list-v4325">${visibleConfirmed.map(row=>paymentCard(row,orgMap,false)).join('')||'<div class="empty-state compact-v4324"><strong>Aún no hay pagos confirmados</strong><span>El primer registro se creará al confirmar una mensualidad.</span></div>'}</div>
   ${confirmedVisible<confirmed.length?`<button type="button" class="secondary-btn payment-history-more-v4331" data-payment-more-v4331>Mostrar ${Math.min(PAGE_SIZE,confirmed.length-confirmedVisible)} pagos más</button>`:''}
   ${archived.length?`<details class="payment-history-archive-v4331"><summary>Pagos archivados (${archived.length})</summary><div class="payment-history-list-v4325">${visibleArchived.map(row=>paymentCard(row,orgMap,true)).join('')}</div>${archivedVisible<archived.length?`<button type="button" class="secondary-btn payment-history-more-v4331" data-payment-more-archived-v4331>Mostrar ${Math.min(ARCHIVE_PAGE_SIZE,archived.length-archivedVisible)} archivados más</button>`:''}</details>`:''}`;

  section.querySelector('[data-payment-more-v4331]')?.addEventListener('click',()=>{confirmedVisible+=PAGE_SIZE;render();});
  section.querySelector('[data-payment-more-archived-v4331]')?.addEventListener('click',()=>{archivedVisible+=ARCHIVE_PAGE_SIZE;render();});
  section.querySelectorAll('[data-payment-archive-v4331]').forEach(button=>button.addEventListener('click',async()=>{
   try{button.disabled=true;await paymentAction('archive',button.dataset.paymentArchiveV4331);toast('Pago archivado.');await window.BHSC_REFRESH_PAYMENT_HISTORY_V4331();}catch(error){toast(error.message);}finally{button.disabled=false;}
  }));
  section.querySelectorAll('[data-payment-restore-v4331]').forEach(button=>button.addEventListener('click',async()=>{
   try{button.disabled=true;await paymentAction('restore',button.dataset.paymentRestoreV4331);toast('Pago restaurado.');await window.BHSC_REFRESH_PAYMENT_HISTORY_V4331();}catch(error){toast(error.message);}finally{button.disabled=false;}
  }));
  section.querySelectorAll('[data-payment-delete-v4331]').forEach(button=>button.addEventListener('click',async()=>{
   if(!confirm('¿Eliminar este pago del historial? Ya no aparecerá en la aplicación.'))return;
   try{button.disabled=true;await paymentAction('delete',button.dataset.paymentDeleteV4331);toast('Pago eliminado del historial.');await window.BHSC_REFRESH_PAYMENT_HISTORY_V4331();}catch(error){toast(error.message);}finally{button.disabled=false;}
  }));
 };
 render();
}

function schedulePaymentHistory(){
 clearTimeout(historyTimer);
 historyTimer=setTimeout(()=>appendPaymentHistory().catch(error=>console.error('[BHSC V4.3.31] Historial de pagos',error)),80);
}

const previousPayments=window.renderSupervisorPayments;
if(typeof previousPayments==='function'){
 window.renderSupervisorPayments=async function(...args){
   const out=await previousPayments.apply(this,args);
   await appendPaymentHistory().catch(error=>console.error('[BHSC V4.3.31] Historial de pagos',error));
   return out;
 };
}

const observer=new MutationObserver(()=>{
 if(window.activeScreen!=='supervisorPayments')return;
 const root=document.getElementById('mainContent');
 if(root&&!root.querySelector('[data-payment-history-v4331]'))schedulePaymentHistory();
});
observer.observe(document.documentElement,{subtree:true,childList:true});

window.BHSC_REFRESH_PAYMENT_HISTORY_V4331=async()=>{
 const root=document.getElementById('mainContent');
 root?.querySelectorAll('[data-payment-history-v4331],[data-payment-history-v4329],[data-payment-history-v4325]').forEach(node=>node.remove());
 await appendPaymentHistory();
};
window.BHSC_REFRESH_PAYMENT_HISTORY_V4330=window.BHSC_REFRESH_PAYMENT_HISTORY_V4331;
window.BHSC_REFRESH_PAYMENT_HISTORY_V4329=window.BHSC_REFRESH_PAYMENT_HISTORY_V4331;
window.BHSC_SECURITY_VERSION=VERSION;
window.BHSC_IDLE_LIMIT_MINUTES=30;
console.info(`Endurecimiento SeniorCare ${VERSION} listo`);
})();
