/* BernardHealth Medical Care V7.9.2
   Ajuste de examen físico segmentario completo. No modifica notificaciones, agenda, facturación ni documentos existentes. */

const CLINICAL_SYSTEM_FIELDS=[
  ['head','Cabeza'],
  ['neck','Cuello'],
  ['thorax','Tórax'],
  ['abdomen','Abdomen'],
  ['pelvis','Pelvis'],
  ['spine','Columna vertebral'],
  ['back','Dorso'],
  ['lumbar_region','Región lumbar'],
  ['upper_limbs','Miembros superiores'],
  ['lower_limbs','Miembros inferiores']
];
const CLINICAL_APPARATUS_FIELDS=[
  ['respiratory','Aparato respiratorio'],
  ['cardiovascular','Aparato cardiovascular'],
  ['digestive','Aparato digestivo'],
  ['genitourinary','Aparato genitourinario'],
  ['nervous','Aparato nervioso'],
  ['locomotor','Aparato locomotor'],
  ['sensory','Órganos de los sentidos']
];

function clinicalPersonKey(patient){
  return patient?.family_member_id?`family:${patient.family_member_id}`:`patient:${patient?.id||''}`;
}
function clinicalFamilyFilter(query,patient){
  return patient?.family_member_id?query.eq('family_member_id',patient.family_member_id):query.is('family_member_id',null);
}
function clinicalWorkspaceMarkup(patient){
  return `<section class="clinical-workspace" id="clinicalWorkspace">
    <div class="clinical-workspace-head">
      <div><span class="eyebrow">EXPEDIENTE CLÍNICO</span><h2>Atención de ${esc(patient?.full_name||'Paciente')}</h2><p>Historia, consulta, diagnóstico y seguimiento reunidos en un solo lugar.</p></div>
      <span class="clinical-head-mark">${ICONS.controls}</span>
    </div>
    <div class="clinical-tabs" role="tablist" aria-label="Expediente clínico">
      <button type="button" class="active" data-clinical-tab="summary">Resumen</button>
      <button type="button" data-clinical-tab="consultation">Nueva consulta</button>
      <button type="button" data-clinical-tab="history">Historial</button>
      <button type="button" data-clinical-tab="documents">Órdenes y recetas</button>
    </div>
    <div class="clinical-panel active" data-clinical-panel="summary"><div class="clinical-loading">Cargando resumen clínico…</div></div>
    <div class="clinical-panel" data-clinical-panel="consultation">${clinicalConsultationFormMarkup()}</div>
    <div class="clinical-panel" data-clinical-panel="history"><div class="clinical-loading">Cargando consultas…</div></div>
    <div class="clinical-panel" data-clinical-panel="documents">${clinicalDocumentLinksMarkup()}</div>
  </section>`;
}
function clinicalConsultationFormMarkup(){
  return `<form id="clinicalConsultationForm" class="clinical-consultation-form">
    <div class="clinical-form-heading"><div><span class="eyebrow">NOTA MÉDICA</span><h3>Desarrollar consulta</h3></div><span class="clinical-save-state" id="clinicalSaveState">Sin guardar</span></div>
    <div class="form-grid clinical-form-grid">
      <div class="field"><label>Tipo de consulta</label><select id="clinicalConsultationType"><option value="first">Primera consulta</option><option value="followup">Control o seguimiento</option></select></div>
      <div class="field"><label>Fecha de consulta</label><input id="clinicalConsultationDate" type="datetime-local"></div>
      <div class="field field-full"><label>Motivo de consulta</label><textarea id="clinicalReason" class="auto-grow" rows="3" required placeholder="Describa el motivo principal de la atención."></textarea></div>
    </div>
    <section id="clinicalFirstConsultationFields" class="clinical-form-section">
      <div class="clinical-section-title"><span>01</span><div><h4>Historia clínica</h4><p>Se guarda como información general permanente del paciente.</p></div></div>
      <div class="form-grid clinical-form-grid">
        <div class="field field-full"><label>Antecedentes personales patológicos</label><textarea id="clinicalPersonalHistory" class="auto-grow" rows="3"></textarea></div>
        <div class="field field-full"><label>Antecedentes personales no patológicos</label><textarea id="clinicalNonPathologicalHistory" class="auto-grow" rows="3"></textarea></div>
        <div class="field field-full"><label>Antecedentes quirúrgicos</label><textarea id="clinicalSurgicalHistory" class="auto-grow" rows="3"></textarea></div>
        <div class="field field-full"><label>Alergias a medicamentos</label><textarea id="clinicalDrugAllergies" class="auto-grow" rows="2"></textarea></div>
        <div class="field field-full"><label>Medicamentos actuales</label><textarea id="clinicalCurrentMedications" class="auto-grow" rows="3"></textarea></div>
      </div>
    </section>
    <section class="clinical-form-section">
      <div class="clinical-section-title"><span>02</span><div><h4>Signos vitales</h4><p>Registre únicamente los datos disponibles.</p></div></div>
      <div class="clinical-vitals-grid">
        <div class="field"><label>Presión arterial</label><input id="clinicalBp" placeholder="120/80"></div>
        <div class="field"><label>Frecuencia cardiaca</label><input id="clinicalHr" inputmode="numeric" placeholder="lpm"></div>
        <div class="field"><label>Frecuencia respiratoria</label><input id="clinicalRr" inputmode="numeric" placeholder="rpm"></div>
        <div class="field"><label>Temperatura</label><input id="clinicalTemp" inputmode="decimal" placeholder="°C"></div>
        <div class="field"><label>SpO₂</label><input id="clinicalSpo2" inputmode="numeric" placeholder="%"></div>
        <div class="field"><label>Peso</label><input id="clinicalWeight" inputmode="decimal" placeholder="kg"></div>
        <div class="field"><label>Glucemia</label><input id="clinicalGlucose" inputmode="numeric" placeholder="mg/dL"></div>
      </div>
    </section>
    <section class="clinical-form-section">
      <div class="clinical-section-title"><span>03</span><div><h4>Examen físico</h4><p>Seleccione examen segmentario o por aparatos.</p></div></div>
      <div class="field clinical-model-select"><label>Modelo de examen</label><select id="clinicalExamModel"><option value="systems">Segmentario</option><option value="apparatus">Por aparatos</option></select></div>
      <div id="clinicalExamFields" class="clinical-exam-grid"></div>
      <div class="field field-full"><label>Hallazgos generales adicionales</label><textarea id="clinicalExamGeneralNotes" class="auto-grow" rows="3"></textarea></div>
    </section>
    <section class="clinical-form-section">
      <div class="clinical-section-title"><span>04</span><div><h4>Diagnóstico y plan</h4><p>Complete la impresión clínica y las indicaciones de seguimiento.</p></div></div>
      <div class="form-grid clinical-form-grid">
        <div class="field field-full"><label>Diagnósticos</label><textarea id="clinicalDiagnoses" class="auto-grow" rows="3" required></textarea></div>
        <div class="field field-full"><label>Tratamiento y plan</label><textarea id="clinicalTreatment" class="auto-grow" rows="4"></textarea></div>
        <div class="field field-full"><label>Observaciones</label><textarea id="clinicalObservations" class="auto-grow" rows="3"></textarea></div>
        <div class="field"><label>Próxima consulta</label><input id="clinicalNextConsultation" type="date"></div>
      </div>
    </section>
    <div class="clinical-form-actions">
      <button type="submit" class="btn primary" id="clinicalSaveBtn">Guardar consulta</button>
      <button type="button" class="btn secondary" id="clinicalSaveSendBtn">Guardar y enviar resumen PDF</button>
    </div>
  </form>`;
}
function clinicalDocumentLinksMarkup(){
  return `<div class="clinical-document-hub">
    <div class="clinical-document-intro"><span>${ICONS.documents}</span><div><h3>Órdenes, recetas y documentos</h3><p>Use los generadores ya existentes; continúan funcionando sin cambios.</p></div></div>
    <div class="clinical-document-grid">
      <button type="button" data-clinical-document="prescription"><span>${ICONS.documents}</span><strong>Receta médica</strong><small>Crear y enviar PDF</small></button>
      <button type="button" data-clinical-document="lab_order"><span>${ICONS.controls}</span><strong>Orden de laboratorio</strong><small>Seleccionar exámenes</small></button>
      <button type="button" data-clinical-document="image_order"><span>${ICONS.documents}</span><strong>Estudios de imagen</strong><small>Crear orden membretada</small></button>
      <button type="button" data-clinical-document="instructions"><span>${ICONS.inbox}</span><strong>Indicaciones médicas</strong><small>Tratamiento y recomendaciones</small></button>
    </div>
    <p class="clinical-document-note">Los documentos generados quedan en el expediente del paciente y conservan la notificación existente.</p>
  </div>`;
}
function clinicalExamFieldsMarkup(model,values={}){
  const fields=model==='apparatus'?CLINICAL_APPARATUS_FIELDS:CLINICAL_SYSTEM_FIELDS;
  return fields.map(([key,label])=>`<div class="field clinical-exam-field"><label>${label}</label><textarea class="auto-grow clinical-exam-input" data-exam-key="${key}" rows="2" placeholder="Hallazgos, normalidad o no evaluado.">${esc(values?.[key]||'')}</textarea></div>`).join('');
}
function clinicalSetTab(name){
  document.querySelectorAll('[data-clinical-tab]').forEach(b=>b.classList.toggle('active',b.dataset.clinicalTab===name));
  document.querySelectorAll('[data-clinical-panel]').forEach(p=>p.classList.toggle('active',p.dataset.clinicalPanel===name));
  setTimeout(()=>clinicalResizeAll(),0);
}
function clinicalResizeTextarea(el){
  if(!el||el.tagName!=='TEXTAREA')return;
  el.style.height='auto';
  el.style.height=`${Math.max(el.scrollHeight,88)}px`;
}
function clinicalResizeAll(root=document){root.querySelectorAll('textarea').forEach(clinicalResizeTextarea)}
function installClinicalAutoGrow(){
  if(window.__clinicalAutoGrowInstalled)return;
  window.__clinicalAutoGrowInstalled=true;
  document.addEventListener('input',e=>{if(e.target?.tagName==='TEXTAREA')clinicalResizeTextarea(e.target)});
  const observer=new MutationObserver(mutations=>{for(const m of mutations){m.addedNodes.forEach(n=>{if(n.nodeType!==1)return;if(n.matches?.('textarea'))clinicalResizeTextarea(n);n.querySelectorAll?.('textarea').forEach(clinicalResizeTextarea)})}});
  observer.observe(document.body,{childList:true,subtree:true});
}
function clinicalNowLocal(){const d=new Date(),pad=n=>String(n).padStart(2,'0');return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`}
function clinicalValue(id){return (document.getElementById(id)?.value||'').trim()}
function clinicalVitalsFromForm(){return {blood_pressure:clinicalValue('clinicalBp'),heart_rate:clinicalValue('clinicalHr'),respiratory_rate:clinicalValue('clinicalRr'),temperature:clinicalValue('clinicalTemp'),spo2:clinicalValue('clinicalSpo2'),weight:clinicalValue('clinicalWeight'),glucose:clinicalValue('clinicalGlucose')}}
function clinicalExamFromForm(){const values={};document.querySelectorAll('.clinical-exam-input').forEach(el=>{values[el.dataset.examKey]=el.value.trim()});return values}
function clinicalHistoryFromForm(){return {personal_history:clinicalValue('clinicalPersonalHistory'),non_pathological_history:clinicalValue('clinicalNonPathologicalHistory'),surgical_history:clinicalValue('clinicalSurgicalHistory'),drug_allergies:clinicalValue('clinicalDrugAllergies'),current_medications:clinicalValue('clinicalCurrentMedications')}}
function clinicalFormatVitals(v={}){return [['PA',v.blood_pressure],['FC',v.heart_rate&&`${v.heart_rate} lpm`],['FR',v.respiratory_rate&&`${v.respiratory_rate} rpm`],['Temp.',v.temperature&&`${v.temperature} °C`],['SpO₂',v.spo2&&`${v.spo2}%`],['Peso',v.weight&&`${v.weight} kg`],['Glucemia',v.glucose&&`${v.glucose} mg/dL`]].filter(x=>x[1]).map(([k,vv])=>`<span><b>${k}</b>${esc(vv)}</span>`).join('')||'<span class="muted">Sin signos registrados</span>'}
function clinicalSummaryMarkup(history,last){
  const h=history||{};
  return `<div class="clinical-summary-grid">
    <article class="clinical-summary-card"><small>ANTECEDENTES PERSONALES</small><p>${esc(h.personal_history||'Sin registrar')}</p></article>
    <article class="clinical-summary-card"><small>NO PATOLÓGICOS</small><p>${esc(h.non_pathological_history||'Sin registrar')}</p></article>
    <article class="clinical-summary-card"><small>QUIRÚRGICOS</small><p>${esc(h.surgical_history||'Sin registrar')}</p></article>
    <article class="clinical-summary-card alert"><small>ALERGIAS A MEDICAMENTOS</small><p>${esc(h.drug_allergies||'Sin registrar')}</p></article>
    <article class="clinical-summary-card wide"><small>MEDICAMENTOS ACTUALES</small><p>${esc(h.current_medications||'Sin registrar')}</p></article>
  </div>
  <div class="clinical-last-consultation">
    <div class="clinical-last-head"><div><span class="eyebrow">ÚLTIMA CONSULTA</span><h3>${last?esc(last.reason||'Consulta médica'):'Sin consultas registradas'}</h3></div>${last?`<span>${fmtDate(last.consultation_date||last.created_at)}</span>`:''}</div>
    ${last?`<div class="clinical-vital-pills">${clinicalFormatVitals(last.vital_signs||{})}</div><div class="clinical-last-grid"><div><small>Diagnósticos</small><p>${esc(last.diagnoses||'—')}</p></div><div><small>Tratamiento y plan</small><p>${esc(last.treatment_plan||'—')}</p></div><div><small>Observaciones</small><p>${esc(last.observations||'—')}</p></div><div><small>Próxima consulta</small><p>${last.next_consultation?fmtDate(last.next_consultation):'No indicada'}</p></div></div>`:'<div class="empty polished">Inicie la primera consulta para crear el resumen clínico.</div>'}
  </div>`;
}
function clinicalHistoryMarkup(rows=[]){
  if(!rows.length)return '<div class="empty polished">No hay consultas guardadas.</div>';
  return `<div class="clinical-timeline">${rows.map(row=>`<details class="clinical-history-card"><summary><div><small>${row.consultation_type==='first'?'PRIMERA CONSULTA':'CONTROL / SEGUIMIENTO'}</small><strong>${esc(row.reason||'Consulta médica')}</strong><span>${fmtDate(row.consultation_date||row.created_at)}</span></div><b>⌄</b></summary><div class="clinical-history-body"><div class="clinical-vital-pills">${clinicalFormatVitals(row.vital_signs||{})}</div><section><small>Examen físico</small><p>${esc(clinicalExamText(row))}</p></section><section><small>Diagnósticos</small><p>${esc(row.diagnoses||'—')}</p></section><section><small>Tratamiento y plan</small><p>${esc(row.treatment_plan||'—')}</p></section><section><small>Observaciones</small><p>${esc(row.observations||'—')}</p></section><div class="clinical-history-actions"><button type="button" class="btn secondary" data-clinical-pdf="${row.id}">PDF</button><button type="button" class="btn primary" data-clinical-send="${row.id}">Enviar resumen al paciente</button></div></div></details>`).join('')}</div>`;
}
function clinicalExamText(row){
  const entries=Object.entries(row.physical_exam||{}).filter(([,v])=>String(v||'').trim());
  const model=row.physical_exam_model==='apparatus'?CLINICAL_APPARATUS_FIELDS:CLINICAL_SYSTEM_FIELDS;
  const labels=new Map(model);
  const text=entries.map(([k,v])=>`${labels.get(k)||k}: ${v}`).join('\n');
  return [text,row.physical_exam_notes].filter(Boolean).join('\n')||'—';
}
async function clinicalLoadData(patient){
  const key=clinicalPersonKey(patient);
  const [historyQ,consultQ]=await Promise.all([
    sb.from('medical_care_clinical_histories').select('*').eq('person_key',key).maybeSingle(),
    sb.from('medical_care_consultations').select('*').eq('person_key',key).eq('active',true).order('consultation_date',{ascending:false}).limit(100)
  ]);
  if(historyQ.error)throw historyQ.error;if(consultQ.error)throw consultQ.error;
  return {history:historyQ.data||null,consultations:consultQ.data||[]};
}
function clinicalFillHistory(history){
  if(!history)return;
  const map={clinicalPersonalHistory:'personal_history',clinicalNonPathologicalHistory:'non_pathological_history',clinicalSurgicalHistory:'surgical_history',clinicalDrugAllergies:'drug_allergies',clinicalCurrentMedications:'current_medications'};
  Object.entries(map).forEach(([id,key])=>{const el=document.getElementById(id);if(el)el.value=history[key]||''});
  clinicalResizeAll(document.getElementById('clinicalFirstConsultationFields')||document);
}
async function initClinicalWorkspace(patient){
  installClinicalAutoGrow();
  const root=document.getElementById('clinicalWorkspace');if(!root)return;
  root.querySelectorAll('[data-clinical-tab]').forEach(b=>b.onclick=()=>clinicalSetTab(b.dataset.clinicalTab));
  const date=document.getElementById('clinicalConsultationDate');if(date&&!date.value)date.value=clinicalNowLocal();
  const type=document.getElementById('clinicalConsultationType');
  const firstFields=document.getElementById('clinicalFirstConsultationFields');
  const examModel=document.getElementById('clinicalExamModel');
  const examFields=document.getElementById('clinicalExamFields');
  const drawExam=values=>{examFields.innerHTML=clinicalExamFieldsMarkup(examModel.value,values);clinicalResizeAll(examFields)};
  drawExam();
  examModel.onchange=()=>drawExam();
  type.onchange=()=>firstFields.classList.toggle('hidden',type.value!=='first');
  root.querySelectorAll('[data-clinical-document]').forEach(btn=>btn.onclick=()=>{
    const builder=document.getElementById('medicalDocBuilder');const select=document.getElementById('medicalDocType');
    if(!builder||!select)return toast('El generador de documentos todavía está cargando.');
    builder.open=true;select.value=btn.dataset.clinicalDocument;select.dispatchEvent(new Event('change'));
    builder.scrollIntoView({behavior:'smooth',block:'start'});
  });
  let state;
  try{state=await clinicalLoadData(patient)}catch(error){
    console.error('Expediente clínico:',error);
    const message=String(error.message||'');
    const friendly=message.includes('medical_care_')?'Falta ejecutar el SQL del expediente clínico.':'No se pudo cargar el expediente clínico.';
    root.querySelector('[data-clinical-panel="summary"]').innerHTML=`<div class="alert-banner"><strong>${friendly}</strong><br><span class="muted">${esc(message)}</span></div>`;
    root.querySelector('[data-clinical-panel="history"]').innerHTML='<div class="empty">El historial estará disponible al completar la configuración.</div>';
    return;
  }
  clinicalFillHistory(state.history);
  if(state.consultations.length){type.value='followup';firstFields.classList.add('hidden');}
  root.querySelector('[data-clinical-panel="summary"]').innerHTML=clinicalSummaryMarkup(state.history,state.consultations[0]);
  root.querySelector('[data-clinical-panel="history"]').innerHTML=clinicalHistoryMarkup(state.consultations);
  root.querySelectorAll('[data-clinical-pdf]').forEach(b=>b.onclick=()=>{const w=window.open('about:blank','_blank');clinicalOpenPdf(patient,state.consultations.find(x=>x.id===b.dataset.clinicalPdf),false,w)});
  root.querySelectorAll('[data-clinical-send]').forEach(b=>b.onclick=()=>clinicalOpenPdf(patient,state.consultations.find(x=>x.id===b.dataset.clinicalSend),true));
  document.getElementById('clinicalConsultationForm').onsubmit=async e=>{e.preventDefault();await clinicalSaveConsultation(patient,false)};
  document.getElementById('clinicalSaveSendBtn').onclick=()=>clinicalSaveConsultation(patient,true);
  setTimeout(()=>clinicalResizeAll(root),0);
}
async function clinicalSaveConsultation(patient,sendPdf){
  const reason=clinicalValue('clinicalReason'),diagnoses=clinicalValue('clinicalDiagnoses');
  if(!reason)return toast('Escriba el motivo de consulta.');
  if(!diagnoses)return toast('Escriba el diagnóstico o impresión clínica.');
  const saveBtn=document.getElementById('clinicalSaveBtn'),sendBtn=document.getElementById('clinicalSaveSendBtn');
  const button=sendPdf?sendBtn:saveBtn;const original=button.textContent;button.disabled=true;button.textContent='Guardando…';
  try{
    const type=document.getElementById('clinicalConsultationType').value;
    const personKey=clinicalPersonKey(patient),familyId=patient.family_member_id||null,consultationDate=document.getElementById('clinicalConsultationDate').value?new Date(document.getElementById('clinicalConsultationDate').value).toISOString():new Date().toISOString();
    const history=clinicalHistoryFromForm();
    if(type==='first'){
      const historyPayload={person_key:personKey,patient_id:patient.id,family_member_id:familyId,patient_name:patient.full_name||'Paciente',doctor_id:session.user.id,...history,updated_at:new Date().toISOString()};
      const h=await sb.from('medical_care_clinical_histories').upsert(historyPayload,{onConflict:'person_key'});if(h.error)throw h.error;
    }
    const payload={person_key:personKey,patient_id:patient.id,family_member_id:familyId,patient_name:patient.full_name||'Paciente',doctor_id:session.user.id,consultation_type:type,consultation_date:consultationDate,reason,vital_signs:clinicalVitalsFromForm(),physical_exam_model:document.getElementById('clinicalExamModel').value,physical_exam:clinicalExamFromForm(),physical_exam_notes:clinicalValue('clinicalExamGeneralNotes'),diagnoses,treatment_plan:clinicalValue('clinicalTreatment'),observations:clinicalValue('clinicalObservations'),next_consultation:clinicalValue('clinicalNextConsultation')||null,history_snapshot:type==='first'?history:{},active:true};
    const result=await sb.from('medical_care_consultations').insert(payload).select('*').single();if(result.error)throw result.error;
    document.getElementById('clinicalSaveState').textContent='Guardado';
    if(sendPdf)await clinicalOpenPdf(patient,result.data,true);
    else toast('Consulta guardada correctamente.');
    document.getElementById('clinicalConsultationForm')?.reset();
    await initClinicalWorkspace(patient);clinicalSetTab('history');
  }catch(error){console.error(error);toast(error.message||'No se pudo guardar la consulta.');}
  finally{button.disabled=false;button.textContent=original;}
}
async function clinicalBuildPdf(patient,row){
  const {jsPDF}=window.jspdf;const doc=new jsPDF({unit:'pt',format:'letter'});const purple=[91,61,145],ink=[42,39,48],muted=[100,92,115];
  let logo=null,signature=null,stamp=null;try{[logo,signature,stamp]=await Promise.all([assetDataUrl('assets/doctor-letterhead-logo.png'),assetDataUrl('assets/doctor-signature.png'),assetDataUrl('assets/doctor-stamp.png')])}catch(e){}
  if(logo)doc.addImage(logo,'PNG',42,32,130,46);doc.setTextColor(...purple);doc.setFont('helvetica','bold');doc.setFontSize(18);doc.text('RESUMEN DE CONSULTA MÉDICA',570,55,{align:'right'});doc.setFontSize(9);doc.setTextColor(...muted);doc.text(DOCTOR_PROFILE.business,570,70,{align:'right'});doc.setDrawColor(220,214,234);doc.line(42,92,570,92);
  let y=118;const line=(label,value)=>{doc.setFont('helvetica','bold');doc.setTextColor(...purple);doc.setFontSize(9);doc.text(label.toUpperCase(),42,y);y+=14;doc.setFont('helvetica','normal');doc.setTextColor(...ink);doc.setFontSize(10.5);const lines=doc.splitTextToSize(String(value||'—'),520);doc.text(lines,42,y);y+=lines.length*14+14;if(y>680){doc.addPage();y=52;}};
  doc.setFont('helvetica','bold');doc.setFontSize(12);doc.setTextColor(...ink);doc.text(patient.full_name||'Paciente',42,y);doc.setFont('helvetica','normal');doc.setFontSize(9);doc.text(`Fecha: ${fmtDate(row.consultation_date||row.created_at)} · ${row.consultation_type==='first'?'Primera consulta':'Control o seguimiento'}`,42,y+16);y+=42;
  line('Motivo de consulta',row.reason);line('Signos vitales',clinicalFormatVitals(row.vital_signs||{}).replace(/<[^>]+>/g,' ').replace(/\s+/g,' ').trim());line('Examen físico',clinicalExamText(row));line('Diagnósticos',row.diagnoses);line('Tratamiento y plan',row.treatment_plan);line('Observaciones',row.observations);line('Próxima consulta',row.next_consultation?fmtDate(row.next_consultation):'No indicada');
  if(y<570)y=570;doc.setDrawColor(220,214,234);doc.line(42,y,570,y);if(signature)doc.addImage(signature,'PNG',52,y+18,120,72);if(stamp)doc.addImage(stamp,'PNG',185,y+18,190,66);doc.setFont('helvetica','bold');doc.setFontSize(9);doc.setTextColor(...ink);doc.text(DOCTOR_PROFILE.name,52,y+112);doc.setFont('helvetica','normal');doc.text(`${DOCTOR_PROFILE.title} · Cód. ${DOCTOR_PROFILE.code}`,52,y+125);doc.setFontSize(7);doc.setTextColor(...muted);doc.text('Documento confidencial emitido electrónicamente por Doctor Benard Consulta Médica.',306,770,{align:'center'});return doc;
}
async function clinicalOpenPdf(patient,row,sendToPatient,previewWindow=null){
  if(!row)return toast('No se encontró la consulta.');
  try{
    const pdf=await clinicalBuildPdf(patient,row);
    if(!sendToPatient){const url=URL.createObjectURL(pdf.output('blob'));if(previewWindow&&!previewWindow.closed)previewWindow.location.href=url;else{const a=document.createElement('a');a.href=url;a.target='_blank';a.rel='noopener noreferrer';a.click();}setTimeout(()=>URL.revokeObjectURL(url),60000);return;}
    const blob=pdf.output('blob'),code=medicalDocCode(),path=`${patient.id}/generated/${Date.now()}-Resumen_Consulta.pdf`;
    let result=await sb.storage.from('medical-documents').upload(path,blob,{contentType:'application/pdf',cacheControl:'3600',upsert:false});if(result.error)throw result.error;
    const content={consultation_id:row.id,reason:row.reason,diagnoses:row.diagnoses,treatment_plan:row.treatment_plan,observations:row.observations};
    result=await sb.from('generated_medical_documents').insert({patient_id:patient.id,family_member_id:patient.family_member_id||null,doctor_id:session.user.id,document_code:code,document_type:'consultation_summary',title:'Resumen de Consulta',content_json:content,status:'active',storage_path:path});if(result.error)throw result.error;
    result=await sb.from('documents').insert({patient_id:patient.id,family_member_id:patient.family_member_id||null,uploaded_by:session.user.id,title:'Resumen de Consulta',document_type:'consultation_summary',storage_path:path,reviewed:true});if(result.error)throw result.error;
    await sb.from('notifications').insert({user_id:patient.id,title:'Resumen de consulta disponible',body:'Su médico agregó el resumen de la consulta.'});
    const push=await sendPatientPush(patient.id,'Resumen de consulta disponible','Su médico agregó el resumen de la consulta.');
    toast(push.ok?'Resumen PDF enviado al paciente.':`Resumen guardado; la notificación no se entregó: ${push.error}`);
  }catch(error){console.error(error);toast(error.message||'No se pudo generar el resumen PDF.');}
}

installClinicalAutoGrow();
