/* Bernard Health SeniorCare Enterprise 3.2.9 — plan nutricional individual y Realtime */
(function(){
  'use strict';
  const TABLE='seniorcare_nutrition_plans';
  const SECTIONS=['General','Desayuno','Merienda AM','Almuerzo','Merienda PM','Cena','Hidratación'];
  const CATALOG={
    General:['Dieta corriente','Dieta blanda','Dieta diabética','Dieta hiposódica','Dieta licuada','Dieta triturada','Textura modificada','Sin azúcar añadida','Sin lactosa','Alimentación asistida','Supervisión durante la alimentación'],
    Desayuno:['Desayuno completo','Porción reducida','Evitar alimentos sólidos','Incluir suplemento nutricional'],
    'Merienda AM':['Merienda regular','Fruta suave','Yogur o lácteo permitido','Suplemento nutricional'],
    Almuerzo:['Almuerzo completo','Porción reducida','Proteína blanda','Verduras trituradas','Sopa o crema'],
    'Merienda PM':['Merienda regular','Fruta suave','Yogur o lácteo permitido','Suplemento nutricional'],
    Cena:['Cena completa','Cena liviana','Porción reducida','Sopa o crema','Evitar sólidos'],
    Hidratación:['Ofrecer agua con frecuencia','Meta 1000 ml/día','Meta 1500 ml/día','Meta 2000 ml/día','Líquidos espesados','Registrar balance hídrico']
  };
  let selectedSection=localStorage.getItem('seniorcare-nutrition-plan-section')||'General';
  let editing=false, channel=null, pulling=false, saving=false, lastSignature='';
  const esc=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
  const db=()=>window.seniorcareSupabase||null;
  const user=()=>window.currentUser||null;
  const org=()=>user()?.organizationId||user()?.organization_id||null;
  const isAdmin=()=>user()?.role==='admin';
  const canRecord=()=>['admin','nurse','assistant'].includes(user()?.role);
  const residentKey=r=>String(window.residentKey?.(r)||r?.resident_key||r?.id||'').trim();
  const currentResident=()=>window.selectedResident||window.residents?.[0]||null;
  const planStore=()=>{window.nutritionPlans=window.nutritionPlans||{};return window.nutritionPlans;};
  const planKey=(r,section=selectedSection)=>`${residentKey(r)}:${section}`;
  const itemsFor=(r,section=selectedSection)=>Array.isArray(planStore()[planKey(r,section)])?planStore()[planKey(r,section)]:[];
  const persist=()=>localStorage.setItem('seniorcare-nutrition-plans',JSON.stringify(planStore()));
  const slug=v=>String(v||'indicacion').normalize('NFD').replace(/[\u0300-\u036f]/g,'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||`indicacion-${Date.now()}`;
  const signature=rows=>JSON.stringify((rows||[]).map(r=>[r.resident_key,r.section_name,r.item_key,r.item_text,r.active,r.updated_at]).sort());

  function renderPlan(r){
    const list=itemsFor(r), assigned=new Set(list.map(x=>x.text));
    const editor=isAdmin()&&editing?`<section class="form-card"><div class="toolbar-copy"><strong>Editar plan nutricional — ${esc(selectedSection)}</strong><span>Seleccione únicamente las indicaciones que corresponden a este residente.</span></div><div class="checklist">${[...new Set([...(CATALOG[selectedSection]||[]),...list.map(x=>x.text)])].map(text=>`<label class="check-item"><input type="checkbox" data-nutrition329-option value="${esc(text)}" ${assigned.has(text)?'checked':''}><span class="checkmark">${window.svg.check}</span><div><strong>${esc(text)}</strong><small>${assigned.has(text)?'Asignada':'Disponible'}</small></div></label>`).join('')}</div><div class="form-actions"><button class="secondary-btn" type="button" data-nutrition329-add>Añadir indicación</button><button class="secondary-btn" type="button" data-nutrition329-cancel>Cancelar</button><button class="primary-btn" type="button" data-nutrition329-save>Guardar plan</button></div></section>`:'';
    return `<section class="care-resident-strip"><div><strong>${esc(r.name)}</strong><span>${esc(r.room||'')} · Plan nutricional</span></div><span class="status ok">${list.length} indicaciones</span></section>
      <div class="care-controls">${isAdmin()?`<select data-nutrition329-resident>${(window.residents||[]).map(x=>`<option value="${esc(residentKey(x))}" ${residentKey(x)===residentKey(r)?'selected':''}>${esc(x.name)}</option>`).join('')}</select>`:''}<select data-nutrition329-section>${SECTIONS.map(s=>`<option value="${esc(s)}" ${s===selectedSection?'selected':''}>${esc(s)}</option>`).join('')}</select>${isAdmin()&&!editing?'<button class="primary-btn" type="button" data-nutrition329-edit>Editar plan</button>':''}</div>${editor}
      <section class="history-card"><h3>Indicaciones guardadas — ${esc(selectedSection)}</h3>${list.length?list.map(x=>`<article class="note-card"><div><b>${esc(x.text)}</b><span>Asignada por Administración</span>${x.notes?`<p>${esc(x.notes)}</p>`:''}</div></article>`).join(''):window.empty(isAdmin()?'No hay indicaciones asignadas. Pulse “Editar plan”.':'No hay indicaciones nutricionales asignadas para esta sección.')}</section>`;
  }

  function renderNutrition329(){
    const r=currentResident();
    if(!r){window.main.innerHTML=window.empty('No hay residentes disponibles.');return;}
    const records=window.getNutritionRecords?.(r.id)||[];
    const recordForm=canRecord()?`<form class="form-card" id="nutritionForm"><div class="form-grid"><label>Tiempo de comida<select name="meal"><option>Desayuno</option><option>Merienda</option><option>Almuerzo</option><option>Cena</option></select></label><label>Porcentaje consumido<select name="percent"><option>100%</option><option>75%</option><option>50%</option><option>25%</option><option>No consumió</option></select></label><label>Líquidos (ml)<input name="liquids" type="number"></label><label>Suplemento<select name="supplement"><option>No</option><option>Sí</option></select></label><label class="wide">Observaciones<textarea name="obs" rows="3"></textarea></label></div><div class="form-actions"><button class="primary-btn">Guardar registro</button></div></form>`:'';
    window.main.innerHTML=window.pageHeader('NUTRICIÓN E HIDRATACIÓN','Plan nutricional',isAdmin()?'Configuración individual por residente':'Indicaciones definidas por Administración')+renderPlan(r)+recordForm+`<section class="history-card"><h3>Historial de ingesta de ${esc(r.name)}</h3>${records.length?records.map((x,i)=>`<article class="note-card"><div><b>${window.fmtDate(x.date)} · ${esc(x.meal)}</b><span>${esc(x.percent)} · ${esc(x.liquids)} ml · Suplemento: ${esc(x.supplement)}</span><p>${esc(x.obs||'Sin observaciones')}</p></div>${canRecord()?`<button class="icon-delete" data-nutrition-delete="${i}">×</button>`:''}</article>`).join(''):window.empty('No hay registros de alimentación.')}</section>`;
  }
  window.renderNutrition=renderNutrition329;

  async function pull({render=true}={}){
    if(pulling||!db()||!org())return; pulling=true;
    try{
      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 grouped={}; for(const row of data||[]){const key=`${row.resident_key}:${row.section_name||'General'}`;(grouped[key]??=[]).push({id:row.item_key,text:row.item_text,notes:row.notes||'',section:row.section_name||'General'});}
      const store=planStore();Object.keys(store).forEach(k=>delete store[k]);Object.assign(store,grouped);persist();
      const sig=signature(data||[]),changed=sig!==lastSignature;lastSignature=sig;
      if(render&&changed&&window.activeScreen==='nutrition'&&!editing){renderNutrition329();window.bindActions?.();}
    }finally{pulling=false;}
  }

  async function savePlan(r,section,texts){
    if(saving)throw new Error('Ya se está guardando el plan.');if(!db()||!org())throw new Error('No hay conexión con Supabase.');
    const rid=residentKey(r),now=new Date().toISOString();if(!rid)throw new Error('No se pudo identificar al residente.');saving=true;
    try{
      const {error:off}=await db().from(TABLE).update({active:false,updated_at:now,updated_by:user()?.id||null}).eq('organization_id',org()).eq('resident_key',rid).eq('section_name',section);if(off)throw off;
      if(texts.length){const rows=texts.map(text=>({organization_id:org(),resident_key:rid,resident_name:r.name||'',section_name:section,item_key:slug(text),item_text:text,notes:'',data:{text,section},active:true,updated_at:now,updated_by:user()?.id||null}));const {error}=await db().from(TABLE).upsert(rows,{onConflict:'organization_id,resident_key,section_name,item_key'});if(error)throw error;}
      await pull({render:false});
    }finally{saving=false;}
  }

  async function startRealtime(){if(!db()||!org())return;await pull({render:false}).catch(console.warn);if(channel)await db().removeChannel(channel);channel=db().channel(`bhsc-nutrition-plan-329-${org()}`).on('postgres_changes',{event:'*',schema:'public',table:TABLE,filter:`organization_id=eq.${org()}`},()=>pull({render:true}).catch(console.warn)).subscribe();}

  document.addEventListener('change',e=>{
    const section=e.target.closest?.('[data-nutrition329-section]');if(section){e.preventDefault();e.stopImmediatePropagation();selectedSection=section.value;localStorage.setItem('seniorcare-nutrition-plan-section',selectedSection);editing=false;renderNutrition329();window.bindActions?.();return;}
    const resident=e.target.closest?.('[data-nutrition329-resident]');if(resident){e.preventDefault();e.stopImmediatePropagation();window.selectedResident=(window.residents||[]).find(r=>residentKey(r)===String(resident.value))||window.selectedResident;editing=false;renderNutrition329();window.bindActions?.();}
  },true);
  document.addEventListener('click',async e=>{
    if(e.target.closest?.('[data-nutrition329-edit]')){e.preventDefault();e.stopImmediatePropagation();editing=true;renderNutrition329();window.bindActions?.();return;}
    if(e.target.closest?.('[data-nutrition329-cancel]')){e.preventDefault();e.stopImmediatePropagation();editing=false;renderNutrition329();window.bindActions?.();return;}
    if(e.target.closest?.('[data-nutrition329-add]')){e.preventDefault();e.stopImmediatePropagation();const text=prompt(`Nueva indicación para ${selectedSection}:`);if(text?.trim()){const list=planStore()[planKey(currentResident())]||[];list.push({id:slug(text),text:text.trim(),section:selectedSection});planStore()[planKey(currentResident())]=list;persist();renderNutrition329();window.bindActions?.();const box=[...document.querySelectorAll('[data-nutrition329-option]')].find(x=>x.value===text.trim());if(box)box.checked=true;}return;}
    const save=e.target.closest?.('[data-nutrition329-save]');if(save){e.preventDefault();e.stopImmediatePropagation();const r=currentResident(),texts=[...document.querySelectorAll('[data-nutrition329-option]:checked')].map(x=>x.value.trim()).filter(Boolean);save.disabled=true;try{await savePlan(r,selectedSection,texts);editing=false;window.showToast?.(`Plan nutricional de ${selectedSection} guardado y sincronizado.`);renderNutrition329();window.bindActions?.();}catch(err){window.showToast?.(err.message||String(err));}finally{if(save.isConnected)save.disabled=false;}return;}
  },true);
  window.addEventListener('seniorcare:user-ready',startRealtime);window.addEventListener('load',()=>setTimeout(startRealtime,1300));document.addEventListener('visibilitychange',()=>{if(!document.hidden)pull({render:true}).catch(()=>{});});
})();
