(()=>{
'use strict';
const VERSION='4.3.61';
const TABLE='seniorcare_medications';
const db=()=>window.seniorcareSupabase||null;
const user=()=>window.currentUser||null;
const org=()=>user()?.organizationId||user()?.organization_id||null;
const toast=m=>window.showToast?.(m);
const clean=v=>String(v??'').trim();
const to24=value=>{const raw=clean(value).toUpperCase().replace(/\s+/g,' ');let m=raw.match(/^(\d{1,2}):(\d{2})\s*(AM|PM)$/);if(m){let h=Number(m[1]),min=Number(m[2]);if(h<1||h>12||min>59)throw new Error(`Hora no válida: ${value}`);if(m[3]==='AM')h=h===12?0:h;else h=h===12?12:h+12;return `${String(h).padStart(2,'0')}:${String(min).padStart(2,'0')}`;}m=raw.match(/^([01]?\d|2[0-3]):([0-5]\d)$/);if(m)return `${String(Number(m[1])).padStart(2,'0')}:${m[2]}`;throw new Error(`Hora no válida: ${value}. Use por ejemplo 8:00 AM o 2:30 PM.`);};
const uuid=()=>crypto.randomUUID?.()||`${Date.now()}-${Math.random().toString(16).slice(2)}`;
const residents=()=>window.residents||[];
const residentKey=r=>clean(r?.resident_key||r?.residentKey||r?.id);
const residentByName=name=>residents().find(r=>clean(r.name||r.full_name)===clean(name));
const meds=()=>Array.isArray(window.meds)?window.meds:[];
function persist(){localStorage.setItem('seniorcare-medications',JSON.stringify(meds()));}
function medicationFormIsOpen(){
 const form=document.getElementById('medicationForm');
 if(!form||form.classList.contains('hidden'))return false;
 return true;
}
function renderIfNeeded(){
 if(window.activeScreen==='medications'&&medicationFormIsOpen())return;
 if(['medications','home','alerts','resident'].includes(window.activeScreen))window.render?.();
}
async function pull({render=true}={}){
 if(!db()||!org())return;
 const {data,error}=await db().from(TABLE).select('*').eq('organization_id',org()).eq('active',true).order('updated_at',{ascending:false});
 if(error)throw error;
 const list=(data||[]).map(row=>{const d=row.data||{};return {...d,id:row.medication_key,resident:row.resident_name||d.resident||'',drug:row.drug_name||d.drug||'',frequency:row.frequency||d.frequency||'Horarios específicos',times:Array.isArray(row.schedule_times)?row.schedule_times:(d.times||[]),time:(Array.isArray(row.schedule_times)&&row.schedule_times[0])||d.time||'',route:row.route||d.route||'VO',status:row.status||d.status||'Pendiente',immediate:row.immediate===true||d.immediate===true,treatmentType:d.treatmentType||d.treatment_type||(d.endDate||d.end_date?'period':'continuous'),startDate:d.startDate||d.start_date||'',endDate:d.endDate||d.end_date||''};});
 window.meds=list;persist();if(render)renderIfNeeded();
}
async function upsertFromForm(form){
 const fd=new FormData(form);const id=clean(fd.get('medicationId'))||uuid();const residentName=clean(fd.get('resident'));const resident=residentByName(residentName);if(!residentName||!resident)throw new Error('Seleccione un residente válido.');
 const frequency=clean(fd.get('frequency'))||'Horarios específicos';const immediate=frequency==='Inmediato';
 const treatmentType=clean(fd.get('treatmentType'))||'continuous';
 const startDate=clean(fd.get('startDate'))||new Intl.DateTimeFormat('en-CA',{timeZone:'America/Costa_Rica'}).format(new Date());
 const endDate=treatmentType==='period'?clean(fd.get('endDate')):'';
 if(treatmentType==='period'&&!endDate)throw new Error('Ingrese la fecha de finalización del tratamiento.');
 if(treatmentType==='period'&&endDate<startDate)throw new Error('La fecha final no puede ser anterior a la fecha inicial.');
 const rawTimes=immediate?[]:clean(fd.get('times')).split(',').map(x=>x.trim()).filter(Boolean);
 const times=immediate?[]:[...new Set(rawTimes.map(to24))];
 if(!immediate&&!times.length)throw new Error('Ingrese al menos una hora de administración.');
 if(treatmentType==='single'&&times.length!==1)throw new Error('La opción Única dosis requiere una sola hora.');
 const item={id,resident:residentName,drug:clean(fd.get('drug')),dose:clean(fd.get('dose')),frequency,immediate,times,time:times[0]||'Ahora',route:clean(fd.get('route'))||'VO',status:clean(fd.get('status'))||'Pendiente',treatmentType,startDate,endDate,remindersEnabled:fd.has('remindersEnabled'),preAlertMinutes:Number(fd.get('preAlertMinutes')||10),repeatMinutes:Number(fd.get('repeatMinutes')||5),instructions:clean(fd.get('instructions'))};
 const row={organization_id:org(),resident_key:residentKey(resident),resident_name:residentName,medication_key:id,drug_name:item.drug,frequency:item.frequency,schedule_times:item.times,route:item.route,status:item.status,immediate:item.immediate,data:item,active:true,updated_at:new Date().toISOString(),updated_by:user()?.id||null};
 const {error}=await db().from(TABLE).upsert(row,{onConflict:'organization_id,resident_key,medication_key'});if(error)throw error;await pull({render:false});try{await window.BHSC_MED_ALERTS_AFTER_MED_SAVE?.(item,resident);}catch(alertError){console.warn('[BHSC medication alerts] No se regeneraron las dosis',alertError);}form.reset();form.classList.add('hidden');renderIfNeeded();toast('Medicamento, horarios y recordatorios guardados.');
}
async function updateStatus(id,status){const {error}=await db().from(TABLE).update({status,updated_at:new Date().toISOString(),updated_by:user()?.id||null}).eq('organization_id',org()).eq('medication_key',clean(id));if(error)throw error;await pull({render:false});renderIfNeeded();toast(status==='Administrado'?'Dosis registrada y sincronizada.':'Medicamento actualizado.');}
async function remove(id){const {error}=await db().from(TABLE).update({active:false,updated_at:new Date().toISOString(),updated_by:user()?.id||null}).eq('organization_id',org()).eq('medication_key',clean(id));if(error)throw error;await pull({render:false});renderIfNeeded();toast('Medicamento eliminado.');}
let busy=false;async function guarded(fn){if(busy)return;busy=true;try{await fn();}catch(e){console.error('[BHSC medications]',e);toast(window.BHSC_FRIENDLY_ERROR?.(e,'No se pudo guardar.')||e.message||'No se pudo guardar.');}finally{busy=false;}}
document.addEventListener('submit',e=>{if(e.target?.id!=='medicationForm')return;e.preventDefault();e.stopImmediatePropagation();guarded(()=>upsertFromForm(e.target));},true);
document.addEventListener('click',e=>{const admin=e.target.closest?.('[data-med-admin]');const del=e.target.closest?.('[data-med-delete]');if(admin){e.preventDefault();e.stopImmediatePropagation();guarded(()=>updateStatus(admin.dataset.medAdmin,'Administrado'));}if(del){e.preventDefault();e.stopImmediatePropagation();if(confirm('¿Eliminar este medicamento?'))guarded(()=>remove(del.dataset.medDelete));}},true);
let channel=null,startedOrg=null;
async function start(){const organization=org();if(!db()||!organization)return;if(startedOrg===organization&&channel)return;if(channel)try{await db().removeChannel(channel)}catch(_){};startedOrg=organization;await pull({render:true});channel=db().channel(`bhsc-medications-${organization}`).on('postgres_changes',{event:'*',schema:'public',table:TABLE,filter:`organization_id=eq.${organization}`},()=>pull({render:true}).catch(console.warn)).subscribe();}
window.seniorcarePullMedications=pull;
window.addEventListener('seniorcare:user-ready',start);
window.addEventListener('load',()=>setTimeout(start,1200));
document.addEventListener('visibilitychange',()=>{if(!document.hidden)pull({render:true}).catch(()=>{});});
})();
