/* Bernard Health SeniorCare V1.4.8 — edición completa de personal y paquetes de módulos */
(function(){
  'use strict';

  const esc=v=>String(v??'').replace(/[&<>"']/g,ch=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch]));
  const db=()=>window.seniorcareSupabase;
  const toast=m=>window.showToast?.(m);
  const MODULES=[
    {key:'doctor',label:'Médico',detail:'Expediente, consultas, indicaciones, recetas y resultados'},
    {key:'nurse',label:'Enfermería',detail:'Medicamentos, curaciones, notas y seguimiento clínico'},
    {key:'assistant',label:'Asistentes',detail:'Residentes asignados, signos vitales y cuidados'},
    {key:'cook',label:'Cocina',detail:'Dietas, alimentación e hidratación'},
    {key:'cleaning',label:'Misceláneo / Limpieza',detail:'Tareas operativas y novedades de limpieza'},
    {key:'maintenance',label:'Mantenimiento',detail:'Tareas, incidencias y mantenimiento preventivo'},
    {key:'security',label:'Seguridad',detail:'Control operativo, alertas e incidentes'}
  ];
  const DEFAULT_PRICE=10000;
  const roleKey=v=>{
    const k=String(v||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'').trim();
    return ({medico:'doctor',doctor:'doctor',enfermera:'nurse',enfermeria:'nurse',asistente:'assistant',cocina:'cook',limpieza:'cleaning',miscelaneo:'cleaning',mantenimiento:'maintenance',seguridad:'security'})[k]||null;
  };
  const money=v=>new Intl.NumberFormat('es-CR',{style:'currency',currency:'CRC',maximumFractionDigits:0}).format(Number(v||0));

  /* ---------- Edición y eliminación de todas las fichas de personal ---------- */
  const oldRenderStaff=window.renderStaff;
  window.renderStaff=function(){
    oldRenderStaff();
    if(currentUser?.role!=='admin')return;
    const form=document.getElementById('staffFormFinal');
    if(form){
      if(!form.querySelector('[name="staffId"]')) form.insertAdjacentHTML('afterbegin','<input type="hidden" name="staffId">');
      const grid=form.querySelector('.form-grid');
      if(grid&&!grid.querySelector('[name="status"]')) grid.insertAdjacentHTML('beforeend','<label>Estado laboral<select name="status"><option>En turno</option><option>Próximo</option><option>Libre</option><option>Ausente</option><option>Inactivo</option></select></label>');
      const submit=form.querySelector('[type="submit"]');
      if(submit)submit.textContent='Guardar cambios';
    }
    document.querySelectorAll('.staff-profile-card').forEach((card,index)=>{
      const member=staffMembers[index];
      if(!member||card.querySelector('.staff-record-actions-v148'))return;
      card.insertAdjacentHTML('beforeend',`<div class="staff-record-actions-v148"><button type="button" class="mini-btn" data-edit-staff-v148="${member.id}">Editar ficha</button><button type="button" class="secondary-btn danger-outline" data-delete-staff-v148="${member.id}">Eliminar trabajador</button></div>`);
    });
  };

  const oldBindActions=window.bindActions;
  window.bindActions=function(){
    oldBindActions();

    document.querySelectorAll('[data-edit-staff-v148]').forEach(btn=>btn.addEventListener('click',()=>{
      const member=staffMembers.find(m=>String(m.id)===String(btn.dataset.editStaffV148));
      const form=document.getElementById('staffFormFinal');
      if(!member||!form)return;
      form.elements.staffId.value=member.id;
      form.elements.name.value=member.name||'';
      form.elements.role.value=member.role||'Asistente';
      form.elements.shift.value=member.shift||'';
      form.elements.assignment.value=member.assignment||'';
      if(form.elements.status)form.elements.status.value=member.status||'Próximo';
      form.classList.remove('hidden');
      form.scrollIntoView({behavior:'smooth',block:'start'});
    }));

    document.querySelectorAll('[data-delete-staff-v148]').forEach(btn=>btn.addEventListener('click',()=>{
      const id=String(btn.dataset.deleteStaffV148);
      const member=staffMembers.find(m=>String(m.id)===id);
      if(!member||!confirm(`¿Eliminar definitivamente la ficha laboral de ${member.name}? El historial de asistencia se conservará.`))return;
      staffMembers=staffMembers.filter(m=>String(m.id)!==id);
      if(window.residentAssignments){delete window.residentAssignments[id];window.saveResidentAssignments?.();}
      saveStaff();renderStaff();bindActions();toast('Trabajador eliminado. El historial de marcas se conservó.');
    }));

    const form=document.getElementById('staffFormFinal');
    if(form&&!form.dataset.v148Bound){
      form.dataset.v148Bound='1';
      form.addEventListener('submit',ev=>{
        ev.preventDefault();ev.stopImmediatePropagation();
        const fd=new FormData(form),id=String(fd.get('staffId')||'');
        const record={
          id:id?(Number.isNaN(Number(id))?id:Number(id)):Date.now(),
          name:String(fd.get('name')||'').trim(),
          role:String(fd.get('role')||'Asistente'),
          shift:String(fd.get('shift')||'').trim(),
          assignment:String(fd.get('assignment')||'').trim(),
          status:String(fd.get('status')||'Próximo')
        };
        if(!record.name||!record.shift){toast('Complete el nombre y el horario.');return;}
        const idx=staffMembers.findIndex(m=>String(m.id)===String(record.id));
        if(idx>=0){record.linkedUserId=staffMembers[idx].linkedUserId||null;staffMembers[idx]={...staffMembers[idx],...record};}
        else staffMembers.push(record);
        saveStaff();renderStaff();bindActions();toast(idx>=0?'Ficha del trabajador actualizada.':'Colaborador agregado.');
      },true);
    }
  };

  /* ---------- Paquetes de módulos administrados por Supervisor ---------- */
  async function loadPackage(orgId){
    const result=await db().from('organization_module_subscriptions').select('*').eq('organization_id',orgId);
    if(result.error)throw result.error;
    const map=Object.fromEntries((result.data||[]).map(x=>[x.module_key,x]));
    return MODULES.map(m=>({...m,enabled:!!map[m.key]?.enabled,monthly_price:Number(map[m.key]?.monthly_price??DEFAULT_PRICE)}));
  }

  const oldDetail=window.renderSupervisorOrganizationDetail;
  window.renderSupervisorOrganizationDetail=async function(){
    await oldDetail();
    const orgId=sessionStorage.getItem('seniorcare-selected-org');
    if(!orgId||currentUser?.role!=='supervisor')return;
    const root=document.getElementById('mainContent');
    try{
      const rows=await loadPackage(orgId);
      root.insertAdjacentHTML('beforeend',`<section class="supv-panel module-package-panel-v148">
        <div class="module-package-head-v148"><div><span>PAQUETE COMERCIAL</span><h3>Módulos habilitados para esta organización</h3><p>Seleccione los módulos que podrá activar el administrador. Cada módulo tiene un precio mensual independiente y editable.</p></div><div><small>Total módulos adicionales</small><strong id="modulePackageTotal">${money(rows.filter(x=>x.enabled).reduce((a,x)=>a+x.monthly_price,0))}</strong></div></div>
        <div class="module-package-grid-v148">${rows.map(r=>`<article data-package-module="${r.key}"><label class="module-package-toggle-v148"><input type="checkbox" ${r.enabled?'checked':''}><span></span><div><strong>${esc(r.label)}</strong><small>${esc(r.detail)}</small></div></label><label>Precio mensual (₡)<input type="number" min="0" step="500" value="${r.monthly_price}"></label></article>`).join('')}</div>
        <div class="module-package-note-v148">El panel administrativo tiene una mensualidad fija de ₡20.000. Cada módulo inicia en ₡10.000, pero el Supervisor puede ajustar su precio según el contrato.</div>
        <div class="form-actions"><button type="button" class="primary-btn" id="saveModulePackageV148">Guardar paquete de módulos</button></div>
      </section>`);
      const updateTotal=()=>{
        const total=[...document.querySelectorAll('[data-package-module]')].reduce((sum,card)=>sum+(card.querySelector('input[type="checkbox"]')?.checked?Number(card.querySelector('input[type="number"]')?.value||0):0),0);
        const el=document.getElementById('modulePackageTotal');if(el)el.textContent=money(total);
      };
      document.querySelectorAll('[data-package-module] input').forEach(x=>x.addEventListener('input',updateTotal));
      document.getElementById('saveModulePackageV148')?.addEventListener('click',async()=>{
        const btn=document.getElementById('saveModulePackageV148');btn.disabled=true;btn.textContent='Guardando…';
        try{
          const payload=[...document.querySelectorAll('[data-package-module]')].map(card=>({
            organization_id:orgId,module_key:card.dataset.packageModule,
            enabled:!!card.querySelector('input[type="checkbox"]')?.checked,
            monthly_price:Number(card.querySelector('input[type="number"]')?.value||0),
            currency:'CRC',updated_at:new Date().toISOString(),updated_by:currentUser?.id||null
          }));
          const rpcPayload=payload.map(x=>({module_key:x.module_key,enabled:x.enabled,monthly_price:Math.max(0,Number(x.monthly_price)||0),currency:'CRC'}));
          let result=window.BHSC_CALL_RPC?await window.BHSC_CALL_RPC(['bh_save_module_contract_v4331','bh_save_module_contract_v4330'],{p_org_id:orgId,p_modules:rpcPayload}):null;
          if(!result||result.error&&window.BHSC_RPC_FUNCTION_MISSING?.(result.error))result=await db().from('organization_module_subscriptions').upsert(payload,{onConflict:'organization_id,module_key'});
          if(result?.error)throw result.error;
          window.dispatchEvent(new CustomEvent('seniorcare:package-saved',{detail:{organizationId:orgId}}));
          await window.syncSeniorCareOrganization?.(orgId,{render:false,allowInitialMigration:false});
          toast('Paquete de módulos actualizado correctamente.');updateTotal();
        }catch(err){toast(`No se pudo guardar: ${err.message}`);}finally{btn.disabled=false;btn.textContent='Guardar paquete de módulos';}
      });
    }catch(err){
      root.insertAdjacentHTML('beforeend',`<section class="supv-panel module-package-panel-v148"><h3>Paquetes de módulos</h3><div class="confirmation-warning">Falta instalar la actualización SQL V1.4.8 para administrar los paquetes. Detalle: ${esc(err.message)}</div></section>`);
    }
  };

  /* ---------- Limitar los códigos del Administrador al paquete contratado ---------- */
  const oldRenderUsersAccess=window.renderUsersAccess;
  window.renderUsersAccess=function(){
    oldRenderUsersAccess();
    if(currentUser?.role!=='admin'||!currentUser?.organizationId)return;
    const form=document.getElementById('accessCodeForm');
    if(!form)return;
    const roleSelect=form.elements.role;
    const help=document.createElement('section');
    help.className='admin-package-summary-v148';
    help.innerHTML='<strong>Paquete de módulos contratado</strong><span>Cargando módulos habilitados…</span>';
    form.closest('.form-card')?.insertAdjacentElement('beforebegin',help);
    loadPackage(currentUser.organizationId).then(rows=>{
      const enabled=new Set(rows.filter(x=>x.enabled).map(x=>x.key));
      [...roleSelect.options].forEach(opt=>{
        if(MODULES.some(m=>m.key===opt.value)&&!enabled.has(opt.value))opt.remove();
      });
      const names=rows.filter(x=>x.enabled).map(x=>x.label);
      help.innerHTML=`<strong>Paquete de módulos contratado</strong><span>${names.length?esc(names.join(' · ')):'No hay módulos operativos habilitados. Solicite la activación al Supervisor.'}</span>`;
      if(![...roleSelect.options].some(o=>MODULES.some(m=>m.key===o.value))){
        const submit=form.querySelector('[type="submit"]');if(submit){submit.disabled=true;submit.title='No hay módulos contratados';}
      }
    }).catch(err=>{help.innerHTML=`<strong>Paquete de módulos</strong><span>No se pudo consultar la configuración: ${esc(err.message)}</span>`;});
  };

  window.renderStaff=window.renderStaff;
  window.bindActions=window.bindActions;
})();
