(()=>{
'use strict';
if(window.__supervisorProfileCommercialV4323)return;
window.__supervisorProfileCommercialV4323=true;

const VERSION='4.3.25';
const db=()=>window.seniorcareSupabase;
const root=()=>document.getElementById('mainContent');
const toast=m=>window.showToast?window.showToast(m):alert(m);
const esc=v=>String(v??'').replace(/[&<>'"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c]));
const isSup=()=>String(window.currentUser?.role||'').toLowerCase()==='supervisor';
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).toLocaleDateString('es-CR'):'Sin definir';
const fmtDT=d=>d?new Date(d).toLocaleString('es-CR'):'Sin registro';
const page=(eyebrow,title,text,backScreen='home')=>`<section class="page-head supervisor-page-head">${backScreen?`<button class="back-btn supervisor-back-btn" data-go="${backScreen}" aria-label="Volver">‹<span>Volver</span></button>`:''}<div><span>${esc(eyebrow)}</span><h2>${esc(title)}</h2><p>${esc(text)}</p></div></section>`;
const statusLabel=l=>!l?'Pendiente':l.status==='suspended'?'Suspendida':l.status==='cancelled'?'Cancelada':l.payment_confirmed&&l.status==='active'?'Activa':'Pendiente';
const statusClass=l=>statusLabel(l)==='Activa'?'ok':statusLabel(l)==='Suspendida'||statusLabel(l)==='Cancelada'?'danger':'warn';
const initials=name=>String(name||'Administrador').trim().split(/\s+/).slice(0,2).map(x=>x[0]||'').join('').toUpperCase()||'AD';
const rpcMissing=e=>window.BHSC_RPC_FUNCTION_MISSING?.(e)||/could not find the function|schema cache|does not exist/i.test(String(e?.message||e||''));
async function auditEvent(orgId,action,details={}){const result=await db().from('audit_logs').insert({organization_id:orgId||null,user_id:window.currentUser?.id||null,action,table_name:'supervisor_commercial_v4325',record_id:orgId||null,details});if(result.error)throw result.error;}

let adminCache=new Map();
let orgCache=new Map();

async function fetchAdminDirectory(){
  const [profiles,orgs]=await Promise.all([
    db().from('profiles').select('id,organization_id,full_name,username,role,active,last_seen_at').eq('role','administrator'),
    db().from('organizations').select('id,name')
  ]);
  if(profiles.error)throw profiles.error;
  if(orgs.error)throw orgs.error;
  adminCache=new Map((profiles.data||[]).map(x=>[String(x.id),x]));
  orgCache=new Map((orgs.data||[]).map(x=>[String(x.id),x]));
}

function decorateAdminCards(){
  document.querySelectorAll('.supervisor-admin-list article').forEach(card=>{
    if(card.dataset.profileV4323==='1')return;
    const toggle=card.querySelector('[data-sg-admin]');
    if(!toggle)return;
    const id=String(toggle.dataset.sgAdmin||'');
    const profile=adminCache.get(id);
    if(!profile)return;
    const org=orgCache.get(String(profile.organization_id||''));
    const identity=card.firstElementChild;
    if(identity){
      identity.classList.add('admin-profile-identity-v4323');
      identity.innerHTML=`<span class="admin-avatar-v4323">${esc(initials(profile.full_name))}</span><div><h3>${esc(profile.full_name||'Administrador')}</h3><p>${esc(org?.name||'Sin organización')}</p></div>`;
    }
    const existingSmall=card.querySelector(':scope > small');
    if(existingSmall){existingSmall.remove();}
    const meta=document.createElement('div');
    meta.className='admin-profile-meta-v4323';
    meta.innerHTML=`<span><small>Usuario</small><strong>${esc(profile.username||'Sin usuario')}</strong></span><span><small>Organización</small><strong>${esc(org?.name||'Sin organización')}</strong></span><span><small>Último acceso</small><strong>${esc(fmtDT(profile.last_seen_at))}</strong></span>`;
    const status=card.querySelector(':scope > .status');
    if(status)status.insertAdjacentElement('afterend',meta);else card.appendChild(meta);
    const edit=document.createElement('button');
    edit.type='button';
    edit.className='secondary-btn admin-edit-btn-v4323';
    edit.dataset.editAdminV4323=id;
    edit.textContent='Ver y editar ficha';
    toggle.insertAdjacentElement('beforebegin',edit);
    card.dataset.profileV4323='1';
  });
}

async function enhanceAdmins(){
  if(!isSup())return;
  try{await fetchAdminDirectory();decorateAdminCards();}
  catch(e){console.warn('[BHSC V4.3.25] No se pudo enriquecer la ficha administrativa',e);}
}

function closeAdminModal(){document.getElementById('adminProfileModalV4323')?.remove();}

function openAdminModal(id){
  const p=adminCache.get(String(id));
  if(!p){toast('No se encontró la ficha del administrador.');return;}
  const org=orgCache.get(String(p.organization_id||''));
  closeAdminModal();
  const modal=document.createElement('div');
  modal.id='adminProfileModalV4323';
  modal.className='admin-modal-backdrop-v4323';
  modal.innerHTML=`<section class="admin-modal-v4323" role="dialog" aria-modal="true" aria-labelledby="adminProfileTitleV4323">
    <div class="admin-modal-head-v4323">
      <div class="admin-modal-person-v4323"><span class="admin-avatar-v4323 large">${esc(initials(p.full_name))}</span><div><span>FICHA DEL ADMINISTRADOR</span><h3 id="adminProfileTitleV4323">${esc(p.full_name||'Administrador')}</h3><p>${esc(org?.name||'Sin organización')}</p></div></div>
      <button type="button" class="admin-modal-close-v4323" data-close-admin-modal aria-label="Cerrar">×</button>
    </div>
    <div class="admin-modal-summary-v4323"><span><small>Estado</small><strong class="${p.active===false?'danger-text-v4323':'ok-text-v4323'}">${p.active===false?'Bloqueado':'Activo'}</strong></span><span><small>Último acceso</small><strong>${esc(fmtDT(p.last_seen_at))}</strong></span><span><small>Organización</small><strong>${esc(org?.name||'Sin organización')}</strong></span></div>
    <form id="adminProfileFormV4323" class="admin-profile-form-v4323">
      <input type="hidden" name="id" value="${esc(p.id)}">
      <label>Nombre completo<input name="full_name" maxlength="120" required value="${esc(p.full_name||'')}"></label>
      <label>Nombre de usuario<input name="username" maxlength="60" required value="${esc(p.username||'')}"></label>
      <label class="admin-readonly-v4323">Rol<input value="Administrador principal" readonly></label>
      <label class="admin-readonly-v4323">Organización<input value="${esc(org?.name||'Sin organización')}" readonly></label>
      <p class="admin-modal-note-v4323">La organización, el rol y el estado se gestionan por separado para evitar cambios accidentales de acceso.</p>
      <div class="admin-modal-actions-v4323"><button type="button" class="secondary-btn" data-close-admin-modal>Cancelar</button><button type="submit" class="primary-btn">Guardar cambios</button></div>
    </form>
  </section>`;
  document.body.appendChild(modal);
  modal.querySelectorAll('[data-close-admin-modal]').forEach(b=>b.onclick=closeAdminModal);
  modal.addEventListener('click',e=>{if(e.target===modal)closeAdminModal();});
  modal.querySelector('input[name="full_name"]')?.focus();
  modal.querySelector('#adminProfileFormV4323').onsubmit=saveAdminProfile;
}

async function saveAdminProfile(e){
  e.preventDefault();
  const form=e.currentTarget;
  const fd=new FormData(form);
  const id=String(fd.get('id')||'');
  const fullName=String(fd.get('full_name')||'').trim();
  const username=String(fd.get('username')||'').trim();
  if(fullName.length<3){toast('Ingrese un nombre completo válido.');return;}
  if(username.length<3){toast('Ingrese un nombre de usuario válido.');return;}
  const btn=form.querySelector('button[type="submit"]');
  try{
    btn.disabled=true;btn.textContent='Guardando…';
    let result=null;
    if(window.BHSC_CALL_RPC){
      result=await window.BHSC_CALL_RPC(['bh_update_administrator_profile_v4323'],{p_target:id,p_full_name:fullName,p_username:username});
    }
    if(!result||result.error&&rpcMissing(result.error)){
      result=await db().from('profiles').update({full_name:fullName,username,updated_at:new Date().toISOString()}).eq('id',id).eq('role','administrator').select('id').maybeSingle();
    }
    if(result?.error)throw result.error;
    await auditEvent(adminCache.get(id)?.organization_id||null,'administrator_profile_updated',{profile_id:id,full_name:fullName,username});
    toast('Ficha del administrador actualizada.');
    closeAdminModal();
    await window.renderSupervisorAdmins?.();
  }catch(err){toast(err.message||'No se pudo actualizar la ficha.');}
  finally{btn.disabled=false;btn.textContent='Guardar cambios';}
}

async function updateLicenseDraft(id,days,price){
  let q=window.BHSC_CALL_RPC?await window.BHSC_CALL_RPC(['bh_update_license_draft_v4321','update_license_draft'],{p_license_id:id,p_term_days:days,p_renews_at:new Date(Date.now()+days*86400000).toISOString(),p_plan_name:'Mensual',p_price_monthly:price}):null;
  if(!q||q.error){
    q=await db().from('licenses').update({term_days:days,price_monthly:price,updated_at:new Date().toISOString(),updated_by:window.currentUser?.id||null}).eq('id',id);
  }
  if(q.error)throw q.error;
}

async function confirmPayment(id,days){
  const q=window.BHSC_CALL_RPC?await window.BHSC_CALL_RPC(['bh_confirm_license_payment_v4331','bh_confirm_license_payment_v4330','bh_confirm_license_payment_v4329','bh_confirm_license_payment_v4325','bh_confirm_license_payment_v4321','supervisor_confirm_payment_v2','confirm_license_payment','supervisor_confirm_payment'],{p_license_id:id,p_term_days:days}):await db().rpc('supervisor_confirm_payment_v2',{p_license_id:id,p_term_days:days});
  if(q.error)throw q.error;
}

async function renderPaymentsV4323(){
  if(!isSup())return;
  const r=root();
  r.innerHTML=page('CONTROL FINANCIERO','Pagos y mensualidades','Registro de montos, confirmaciones y renovaciones','home')+'<div class="supv-loading">Cargando pagos…</div>';
  setTimeout(()=>window.setActiveNav?.('supervisorPayments'),0);
  try{
    const [orgsQ,licensesQ]=await Promise.all([
      db().from('organizations').select('id,name').order('name'),
      db().from('licenses').select('*').order('renews_at',{ascending:true})
    ]);
    if(orgsQ.error)throw orgsQ.error;
    if(licensesQ.error)throw licensesQ.error;
    const orgs=orgsQ.data||[],licenses=licensesQ.data||[],om=new Map(orgs.map(x=>[String(x.id),x]));
    const confirmed=licenses.filter(x=>x.payment_confirmed===true);
    const pending=licenses.filter(x=>x.payment_confirmed!==true);
    const monthly=licenses.reduce((s,x)=>s+Number(x.price_monthly||0),0);
    const confirmedAmount=confirmed.reduce((s,x)=>s+Number(x.price_monthly||0),0);
    r.innerHTML=page('CONTROL FINANCIERO','Pagos y mensualidades','Registro de montos, confirmaciones y renovaciones','home')+`
      <section class="commercial-tabs-v4323"><button type="button" data-go="supervisorLicenses">Licencias</button><button type="button" class="active" data-go="supervisorPayments">Pagos</button></section>
      <section class="payment-summary-v4323"><article><span>Facturación mensual</span><strong>${money(monthly)}</strong><small>Monto configurado</small></article><article><span>Pagos confirmados</span><strong>${confirmed.length}</strong><small>${money(confirmedAmount)}</small></article><article><span>Pagos pendientes</span><strong>${pending.length}</strong><small>Requieren confirmación</small></article></section>
      <section class="payment-help-v4323"><div><b>1</b><span><strong>Defina el monto</strong><small>Actualice la mensualidad y la vigencia.</small></span></div><div><b>2</b><span><strong>Confirme el pago</strong><small>La licencia queda activa desde ese momento.</small></span></div><div><b>3</b><span><strong>Renueve</strong><small>Extienda la vigencia con el siguiente pago.</small></span></div></section>
      <div class="payment-grid-v4323">${licenses.map(l=>{const org=om.get(String(l.organization_id));return `<article class="payment-card-v4323"><div class="payment-card-head-v4323"><div><span>ORGANIZACIÓN</span><h3>${esc(org?.name||'Organización')}</h3><p>${statusLabel(l)} · ${l.payment_confirmed?'Pago confirmado':'Pago pendiente'}</p></div><span class="status ${statusClass(l)}">${statusLabel(l)}</span></div><div class="payment-amount-v4323"><span>Mensualidad</span><strong>${money(l.price_monthly||0)}</strong></div><div class="payment-form-v4323"><label>Monto mensual<input type="number" min="20000" step="1000" data-payment-price="${esc(l.id)}" value="${Number(l.price_monthly||0)}"></label><label>Vigencia en días<input type="number" min="1" max="365" data-payment-days="${esc(l.id)}" value="${Number(l.term_days||30)}"></label></div><div class="payment-detail-v4323"><span><small>Próxima renovación</small><strong>${esc(fmt(l.renews_at))}</strong></span><span><small>Plan</small><strong>${esc(l.plan_name||'Mensual')}</strong></span></div><div class="payment-actions-v4323"><button type="button" class="secondary-btn" data-save-payment="${esc(l.id)}">Guardar monto</button><button type="button" class="primary-btn" data-confirm-payment="${esc(l.id)}">${l.payment_confirmed?'Renovar licencia':'Confirmar pago'}</button></div></article>`}).join('')||'<div class="empty-state"><strong>No hay licencias registradas</strong><span>Los pagos aparecerán al crear una organización.</span></div>'}</div>`;
    r.querySelectorAll('[data-save-payment]').forEach(b=>b.onclick=async()=>{
      const id=b.dataset.savePayment,days=Math.max(1,Math.min(365,Number(r.querySelector(`[data-payment-days="${id}"]`)?.value||30))),price=Math.max(0,Number(r.querySelector(`[data-payment-price="${id}"]`)?.value||0));
      try{b.disabled=true;await updateLicenseDraft(id,days,price);const lic=licenses.find(x=>String(x.id)===String(id));await auditEvent(lic?.organization_id||null,'license_price_updated',{license_id:id,days,price});toast('Monto y vigencia guardados.');await renderPaymentsV4323();}catch(e){toast(e.message||'No se pudo guardar el pago.');}finally{b.disabled=false;}
    });
    setTimeout(()=>window.setActiveNav?.('supervisorPayments'),0);
    r.querySelectorAll('[data-confirm-payment]').forEach(b=>b.onclick=async()=>{
      const id=b.dataset.confirmPayment,days=Math.max(1,Math.min(365,Number(r.querySelector(`[data-payment-days="${id}"]`)?.value||30))),price=Math.max(0,Number(r.querySelector(`[data-payment-price="${id}"]`)?.value||0));
      try{b.disabled=true;b.textContent='Procesando…';await updateLicenseDraft(id,days,price);await confirmPayment(id,days);const lic=licenses.find(x=>String(x.id)===String(id));await auditEvent(lic?.organization_id||null,'license_payment_confirmed',{license_id:id,days,price,renewal:lic?.payment_confirmed===true});toast('Pago confirmado y licencia actualizada.');await renderPaymentsV4323();}catch(e){toast(e.message||'No se pudo confirmar el pago.');}finally{b.disabled=false;}
    });
  }catch(e){r.innerHTML=page('CONTROL FINANCIERO','Pagos y mensualidades','Registro de montos, confirmaciones y renovaciones','home')+`<div class="empty-state"><strong>No se pudo cargar Pagos</strong><span>${esc(e.message)}</span></div>`;}
}

function enhanceLicenseScreen(){
  const r=root();
  if(!r||!isSup()||window.activeScreen!=='supervisorLicenses'||r.querySelector('.commercial-tabs-v4323'))return;
  const head=r.querySelector('.supervisor-page-head');
  if(head)head.insertAdjacentHTML('afterend','<section class="commercial-tabs-v4323"><button type="button" class="active" data-go="supervisorLicenses">Licencias</button><button type="button" data-go="supervisorPayments">Pagos</button></section>');
  const list=r.querySelector('.supervisor-license-list');
  if(list)list.insertAdjacentHTML('beforebegin','<section class="license-purpose-v4323"><div><strong>Licencias</strong><span>Controle estado, vigencia y suspensión de cada organización.</span></div><button type="button" class="secondary-btn" data-go="supervisorPayments">Ir al control de pagos</button></section>');
}

const originalAdmins=window.renderSupervisorAdmins;
if(typeof originalAdmins==='function'){
  window.renderSupervisorAdmins=async function(...args){const out=await originalAdmins.apply(this,args);await enhanceAdmins();return out;};
}
const originalLicenses=window.renderSupervisorLicenses;
if(typeof originalLicenses==='function'){
  window.renderSupervisorLicenses=async function(...args){const out=await originalLicenses.apply(this,args);setTimeout(enhanceLicenseScreen,0);return out;};
}
window.renderSupervisorPayments=renderPaymentsV4323;

document.addEventListener('click',e=>{
  const edit=e.target.closest?.('[data-edit-admin-v4323]');
  if(edit){e.preventDefault();e.stopImmediatePropagation();openAdminModal(edit.dataset.editAdminV4323);}
},true);

document.addEventListener('keydown',e=>{if(e.key==='Escape')closeAdminModal();});

const observer=new MutationObserver(()=>{
  if(!isSup())return;
  if(window.activeScreen==='supervisorAdmins'&&document.querySelector('.supervisor-admin-list article:not([data-profile-v4323="1"])'))enhanceAdmins();
  if(window.activeScreen==='supervisorLicenses')enhanceLicenseScreen();
});
observer.observe(document.documentElement,{subtree:true,childList:true});

console.info(`Supervisor Profile & Commercial ${VERSION} listo`);
})();
