aarnal80 commited on
Commit
e08f51d
·
verified ·
1 Parent(s): 8e5c775

Update js/proa.js

Browse files
Files changed (1) hide show
  1. js/proa.js +254 -116
js/proa.js CHANGED
@@ -1,27 +1,27 @@
1
- // js/proa.js - Lógica para el visor de Guías PROA (v10 - Un Solo Desplegable)
2
-
3
  // ======================================================================
4
  // BLOCK START: DOM Elements Selection & Initial Setup
5
  // ======================================================================
6
- console.log("[proa.js v10] Script cargado. Esperando DOMContentLoaded...");
7
-
8
  window.addEventListener('DOMContentLoaded', () => {
9
- console.log("[proa.js v10] DOMContentLoaded detectado. Iniciando setup...");
10
 
11
- // Selector ÚNICO de Guías
12
  const guideSelector = document.getElementById('guideSelector');
 
 
13
  const guideContentDisplay = document.getElementById('guide-content-display');
14
  const togglePediatricCheckbox = document.getElementById('togglePediatric');
15
 
16
  const guidesDataUrl = 'guides_data.json'; // Asume que está en proa/
17
 
18
  // Verificar elementos críticos
19
- if (!guideSelector || !guideContentDisplay || !togglePediatricCheckbox) {
20
- console.error("[proa.js v10] Error Crítico: No se encontraron elementos DOM esenciales (selector, display o checkbox).");
21
- guideContentDisplay.innerHTML = '<p class="text-red-500 font-semibold text-center py-10">Error: Interfaz no inicializada.</p>';
22
  return;
23
  }
24
- console.log("[proa.js v10] Elementos DOM encontrados.");
25
  // ======================================================================
26
  // BLOCK END: DOM Elements Selection & Initial Setup
27
  // ======================================================================
@@ -29,9 +29,9 @@ window.addEventListener('DOMContentLoaded', () => {
29
  // ======================================================================
30
  // BLOCK START: State Variables
31
  // ======================================================================
32
- let allGuides = [];
33
- let currentGuideFile = null;
34
- // Ya no necesitamos la variable 'categories' para la UI
35
  // ======================================================================
36
  // BLOCK END: State Variables
37
  // ======================================================================
@@ -40,162 +40,301 @@ window.addEventListener('DOMContentLoaded', () => {
40
  // BLOCK START: Function to Fetch Guides Data (from JSON)
41
  // ======================================================================
42
  async function loadGuidesData() {
43
- console.log(`[proa.js v10] Iniciando loadGuidesData desde: ${guidesDataUrl}`);
44
  guideSelector.innerHTML = '<option value="">Cargando...</option>';
45
- guideSelector.disabled = true; // Deshabilitar mientras carga
46
- guideContentDisplay.innerHTML = '<div class="text-center py-16 text-gray-400"><i class="fas fa-spinner fa-spin text-3xl"></i><p class="mt-2">Cargando datos...</p></div>';
47
- allGuides = [];
48
 
49
  try {
50
- console.log("[proa.js v10] Realizando fetch...");
51
- const response = await fetch(guidesDataUrl);
52
- console.log(`[proa.js v10] Fetch completado. Status: ${response.status}`);
53
- if (!response.ok) throw new Error(`Error HTTP ${response.status} al cargar ${guidesDataUrl}.`);
54
-
55
- console.log("[proa.js v10] Parseando JSON...");
56
- allGuides = await response.json();
57
- console.log("[proa.js v10] JSON parseado.");
58
-
59
- if (!Array.isArray(allGuides)) throw new Error("JSON no es un array válido.");
60
-
61
- allGuides = allGuides.filter(g => g.id && g.title && g.category && g.file);
62
- console.log(`[proa.js v10] Guías válidas filtradas: ${allGuides.length}`);
63
-
64
- if (allGuides.length === 0) throw new Error("No hay guías válidas en los datos.");
65
-
66
- // Ordenar guías (opcional, pero útil para el desplegable)
 
 
 
 
 
 
 
 
 
 
 
 
67
  allGuides.sort((a, b) => a.title.localeCompare(b.title));
68
-
69
- console.log("[proa.js v10] Llamando a populateGuideSelector para mostrar Adultos por defecto...");
70
- populateGuideSelector(); // Poblar el desplegable (mostrará Adultos por defecto)
71
- resetContentArea(); // Mostrar mensaje inicial en área de contenido
72
- guideSelector.disabled = false; // Habilitar selector
73
- console.log("[proa.js v10] Carga inicial completada.");
74
 
75
  } catch (error) {
76
- console.error("[proa.js v10] Error durante loadGuidesData:", error);
77
- guideSelector.innerHTML = '<option value="">Error carga</option>';
78
  guideSelector.disabled = true;
79
- guideContentDisplay.innerHTML = `<p class="text-red-600 font-semibold text-center py-10">Error al cargar datos: ${error.message}. Revisa la consola y el archivo JSON.</p>`;
80
  }
81
  }
82
  // ======================================================================
83
  // BLOCK END: Function to Fetch Guides Data (from JSON)
84
  // ======================================================================
85
-
86
  // ======================================================================
87
  // BLOCK START: UI Update Functions
88
  // ======================================================================
89
 
90
- function resetContentArea() {
 
91
  guideContentDisplay.innerHTML = '<div class="text-center py-16 text-gray-400"><i class="fas fa-file-alt text-5xl mb-4"></i><p>Selecciona una guía del desplegable.</p></div>';
92
- currentGuideFile = null;
 
 
 
 
 
 
 
93
  }
94
 
95
- // Llena el selector ÚNICO de guías aplicando el filtro
96
  function populateGuideSelector() {
97
  const showOnlyPediatric = togglePediatricCheckbox.checked;
98
- console.log(`[proa.js v10] Poblando selector de guías. Mostrar solo Pediátricas: ${showOnlyPediatric}`);
99
-
100
- // Limpiar selector ANTES del try-catch
101
- guideSelector.innerHTML = `<option value="">-- Seleccione Guía (${showOnlyPediatric ? 'Pediátricas' : 'Adultos'}) --</option>`;
102
- currentGuideFile = null; // Deseleccionar guía al repoblar
103
-
104
- try {
105
- // Filtrar por Adulto o Pediátrico ESTRICTAMENTE
106
- const filteredGuides = allGuides.filter(guide => guide.isPediatric === showOnlyPediatric);
107
-
108
- // Ordenar alfabéticamente las guías filtradas
109
- filteredGuides.sort((a, b) => a.title.localeCompare(b.title));
110
-
111
- if (filteredGuides.length > 0) {
112
- const fragment = document.createDocumentFragment();
113
- filteredGuides.forEach(guide => {
114
- const option = document.createElement('option');
115
- option.value = guide.file; // El valor es el nombre del archivo
116
- option.textContent = guide.title; // El texto es el título
117
- // Añadir "(PED)" al texto si es pediátrica para mayor claridad en el desplegable
118
- if (guide.isPediatric) {
119
- option.textContent += " (PED)";
120
- }
121
- fragment.appendChild(option);
122
- });
123
- guideSelector.appendChild(fragment); // Añadir opciones
124
- console.log(`[proa.js v10] Selector poblado con ${filteredGuides.length} guías.`);
125
- } else {
126
- guideSelector.innerHTML = `<option value="">-- No hay guías ${showOnlyPediatric ? 'Pediátricas' : 'Adultos'} --</option>`;
127
- console.log(`[proa.js v10] No se encontraron guías para el filtro actual.`);
128
- }
129
- } catch (e) {
130
- console.error("[proa.js v10] Error en populateGuideSelector:", e);
131
- guideSelector.innerHTML = '<option value="">Error</option>';
132
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  }
 
134
  // ======================================================================
135
  // BLOCK END: UI Update Functions
136
  // ======================================================================
137
 
138
  // ======================================================================
139
- // BLOCK START: Function to Load External Guide Content (Sin cambios v6.2->v10)
140
  // ======================================================================
141
- async function loadGuideContent(guideFileName) {
142
- if (!guideFileName) {
143
- resetContentArea();
144
- return;
 
 
145
  }
146
- console.log(`[proa.js v10] Solicitando contenido de: ${guideFileName}`);
147
- guideContentDisplay.innerHTML = '<div class="text-center py-20"><i class="fas fa-spinner fa-spin text-3xl text-gray-400"></i><p class="mt-2 text-gray-500">Cargando contenido...</p></div>';
148
- const guideUrl = guideFileName;
149
- currentGuideFile = guideFileName;
150
 
151
  try {
152
- const response = await fetch(guideUrl);
153
- if (!response.ok) throw new Error(`Error HTTP ${response.status} al cargar ${guideUrl}`);
154
  const htmlText = await response.text();
 
 
155
  const parser = new DOMParser();
156
  const doc = parser.parseFromString(htmlText, 'text/html');
157
- const contentNode = doc.querySelector('.max-w-4xl.mx-auto.px-4.py-8') || doc.body;
 
158
 
159
  if (contentNode) {
160
  const clonedContent = contentNode.cloneNode(true);
 
161
  const scripts = clonedContent.querySelectorAll('script');
162
  scripts.forEach(script => script.remove());
163
- if (scripts.length > 0) console.log(`[proa.js v10] Eliminados ${scripts.length} script(s) de ${guideFileName}.`);
164
-
165
- guideContentDisplay.innerHTML = '';
166
- guideContentDisplay.appendChild(clonedContent);
167
- console.log(`[proa.js v10] Contenido de ${guideFileName} mostrado.`);
168
- guideContentDisplay.scrollTop = 0;
169
 
 
 
 
 
170
  } else {
171
- throw new Error(`No se encontró nodo de contenido en '${guideFileName}'.`);
172
  }
173
  } catch (error) {
174
- console.error(`[proa.js v10] Error al cargar/mostrar ${guideFileName}:`, error);
175
- guideContentDisplay.innerHTML = `<div class="text-center py-20 text-red-600">Error: ${error.message}</div>`;
176
- currentGuideFile = null;
177
  }
178
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  // ======================================================================
180
- // BLOCK END: Function to Load External Guide Content
181
  // ======================================================================
182
 
183
  // ======================================================================
184
  // BLOCK START: Event Listeners Setup
185
  // ======================================================================
186
- // Cuando cambia la guía específica seleccionada
 
187
  guideSelector.addEventListener('change', (event) => {
188
- console.log("[proa.js v10] Cambió la guía seleccionada.");
189
- loadGuideContent(event.target.value); // Cargar el contenido del archivo seleccionado
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  });
191
 
192
- // Cuando cambia el filtro pediátrico
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  togglePediatricCheckbox.addEventListener('change', () => {
194
- console.log('[proa.js v10] Cambiado filtro pediátrico.');
195
- resetContentArea(); // Limpiar área de contenido
196
- populateGuideSelector(); // Repoblar el ÚNICO desplegable con las guías filtradas
 
197
  });
198
- console.log("[proa.js v10] Listeners añadidos.");
 
199
  // ======================================================================
200
  // BLOCK END: Event Listeners Setup
201
  // ======================================================================
@@ -203,11 +342,10 @@ window.addEventListener('DOMContentLoaded', () => {
203
  // ======================================================================
204
  // BLOCK START: Initial Execution
205
  // ======================================================================
206
- loadGuidesData(); // Cargar JSON, poblar desplegable (adultos por defecto) e iniciar UI
207
  // ======================================================================
208
  // BLOCK END: Initial Execution
209
  // ======================================================================
210
 
211
  }); // Fin DOMContentLoaded
212
-
213
- console.log("[proa.js v10] Script completamente definido.");
 
1
+ // js/proa.js - Lógica para el visor de Guías PROA (v12 - Con Diagnósticos)
 
2
  // ======================================================================
3
  // BLOCK START: DOM Elements Selection & Initial Setup
4
  // ======================================================================
5
+ console.log("[proa.js v12] Script cargado. Esperando DOMContentLoaded...");
 
6
  window.addEventListener('DOMContentLoaded', () => {
7
+ console.log("[proa.js v12] DOMContentLoaded detectado. Iniciando setup...");
8
 
9
+ // Selectores y Contenedores
10
  const guideSelector = document.getElementById('guideSelector');
11
+ const diagnosisSelectorContainer = document.getElementById('diagnosis-selector-container');
12
+ const diagnosisSelector = document.getElementById('diagnosisSelector');
13
  const guideContentDisplay = document.getElementById('guide-content-display');
14
  const togglePediatricCheckbox = document.getElementById('togglePediatric');
15
 
16
  const guidesDataUrl = 'guides_data.json'; // Asume que está en proa/
17
 
18
  // Verificar elementos críticos
19
+ if (!guideSelector || !diagnosisSelectorContainer || !diagnosisSelector || !guideContentDisplay || !togglePediatricCheckbox) {
20
+ console.error("[proa.js v12] Error Crítico: No se encontraron elementos DOM esenciales.");
21
+ guideContentDisplay.innerHTML = '<p class="text-red-500 font-semibold text-center py-10">Error: Interfaz no inicializada correctamente.</p>';
22
  return;
23
  }
24
+ console.log("[proa.js v12] Elementos DOM encontrados.");
25
  // ======================================================================
26
  // BLOCK END: DOM Elements Selection & Initial Setup
27
  // ======================================================================
 
29
  // ======================================================================
30
  // BLOCK START: State Variables
31
  // ======================================================================
32
+ let allGuides = []; // Almacenará todas las guías del JSON
33
+ let currentSelectedGuideData = null; // Guarda los datos completos de la guía seleccionada
34
+ let currentGuideHTMLContent = null; // Cache para el HTML de la guía actual con diagnósticos
35
  // ======================================================================
36
  // BLOCK END: State Variables
37
  // ======================================================================
 
40
  // BLOCK START: Function to Fetch Guides Data (from JSON)
41
  // ======================================================================
42
  async function loadGuidesData() {
43
+ console.log(`[proa.js v12] Iniciando loadGuidesData desde: ${guidesDataUrl}`);
44
  guideSelector.innerHTML = '<option value="">Cargando...</option>';
45
+ guideSelector.disabled = true;
46
+ resetUI(); // Limpia todo
 
47
 
48
  try {
49
+ console.log("[proa.js v12] Realizando fetch...");
50
+ const response = await fetch(guidesDataUrl);
51
+ console.log(`[proa.js v12] Fetch completado. Status: ${response.status}`);
52
+ if (!response.ok) throw new Error(`Error HTTP ${response.status} al cargar ${guidesDataUrl}. Verifica que el archivo exista y sea accesible.`);
53
+
54
+ console.log("[proa.js v12] Parseando JSON...");
55
+ const rawData = await response.json();
56
+ console.log("[proa.js v12] JSON parseado.");
57
+
58
+ if (!Array.isArray(rawData)) throw new Error("El formato del JSON no es un array válido.");
59
+
60
+ // Filtrar y validar guías
61
+ allGuides = rawData.filter(g => g.id && g.title && g.file && typeof g.isPediatric === 'boolean');
62
+ console.log(`[proa.js v12] Guías válidas iniciales: ${allGuides.length}`);
63
+
64
+ // Validar estructura de diagnóstico si existe
65
+ allGuides = allGuides.map(g => {
66
+ if (g.hasDiagnoses === true) {
67
+ if (!Array.isArray(g.diagnoses) || g.diagnoses.some(d => !d.id || !d.title)) {
68
+ console.warn(`[proa.js v12] Guía '${g.title}' marcada con 'hasDiagnoses' pero la estructura 'diagnoses' es inválida. Se tratará como guía normal.`);
69
+ return { ...g, hasDiagnoses: false, diagnoses: undefined }; // Corregir datos inválidos
70
+ }
71
+ }
72
+ return g;
73
+ });
74
+
75
+ if (allGuides.length === 0) throw new Error("No se encontraron guías válidas en los datos después de la validación.");
76
+
77
+ // Ordenar alfabéticamente para el desplegable principal
78
  allGuides.sort((a, b) => a.title.localeCompare(b.title));
79
+
80
+ console.log("[proa.js v12] Llamando a populateGuideSelector (mostrará Adultos por defecto)...");
81
+ populateGuideSelector(); // Poblar el desplegable principal
82
+ guideSelector.disabled = false; // Habilitar selector principal
83
+ console.log("[proa.js v12] Carga inicial de datos completada.");
 
84
 
85
  } catch (error) {
86
+ console.error("[proa.js v12] Error durante loadGuidesData:", error);
87
+ guideSelector.innerHTML = `<option value="">Error al cargar</option>`;
88
  guideSelector.disabled = true;
89
+ guideContentDisplay.innerHTML = `<p class="text-red-600 font-semibold text-center py-10">Error crítico al cargar datos: ${error.message}. Revisa la consola y el archivo '${guidesDataUrl}'.</p>`;
90
  }
91
  }
92
  // ======================================================================
93
  // BLOCK END: Function to Fetch Guides Data (from JSON)
94
  // ======================================================================
95
+
96
  // ======================================================================
97
  // BLOCK START: UI Update Functions
98
  // ======================================================================
99
 
100
+ // Resetea el área de contenido y el selector de diagnóstico
101
+ function resetUI(fullReset = true) {
102
  guideContentDisplay.innerHTML = '<div class="text-center py-16 text-gray-400"><i class="fas fa-file-alt text-5xl mb-4"></i><p>Selecciona una guía del desplegable.</p></div>';
103
+ diagnosisSelector.innerHTML = '<option value="">-- Seleccione Diagnóstico --</option>'; // Limpiar opciones
104
+ diagnosisSelectorContainer.classList.add('hidden'); // Ocultar contenedor
105
+ currentSelectedGuideData = null;
106
+ currentGuideHTMLContent = null; // Limpiar cache de HTML
107
+
108
+ if(fullReset && guideSelector.options.length > 1) {
109
+ guideSelector.value = ""; // Resetear también el selector principal si no es el reset inicial
110
+ }
111
  }
112
 
113
+ // Llena el selector PRINCIPAL de guías aplicando el filtro Pediátrico/Adulto
114
  function populateGuideSelector() {
115
  const showOnlyPediatric = togglePediatricCheckbox.checked;
116
+ console.log(`[proa.js v12] Poblando selector principal. Mostrar Pediátricas: ${showOnlyPediatric}`);
117
+
118
+ // Filtrar por Adulto o Pediátrico
119
+ const filteredGuides = allGuides.filter(guide => guide.isPediatric === showOnlyPediatric);
120
+
121
+ // Ordenar alfabéticamente (ya deberían estar ordenadas, pero por si acaso)
122
+ filteredGuides.sort((a, b) => a.title.localeCompare(b.title));
123
+
124
+ // Limpiar selector principal
125
+ guideSelector.innerHTML = `<option value="">-- Seleccione Guía (${showOnlyPediatric ? 'Pediátricas' : 'Adultos'}) --</option>`;
126
+
127
+ if (filteredGuides.length > 0) {
128
+ const fragment = document.createDocumentFragment();
129
+ filteredGuides.forEach(guide => {
130
+ const option = document.createElement('option');
131
+ option.value = guide.id; // Usar el ID único de la guía como valor
132
+ option.textContent = guide.isPediatric ? `${guide.title} (PED)` : guide.title;
133
+ // Guardar datos importantes en el dataset para fácil acceso
134
+ option.dataset.hasDiagnoses = guide.hasDiagnoses || false;
135
+ option.dataset.file = guide.file;
136
+ fragment.appendChild(option);
137
+ });
138
+ guideSelector.appendChild(fragment);
139
+ console.log(`[proa.js v12] Selector principal poblado con ${filteredGuides.length} guías.`);
140
+ } else {
141
+ guideSelector.innerHTML = `<option value="">-- No hay guías ${showOnlyPediatric ? 'Pediátricas' : 'Adultos'} --</option>`;
142
+ console.log(`[proa.js v12] No se encontraron guías para el filtro actual.`);
143
+ }
144
+ resetUI(false); // Resetear UI secundaria sin deseleccionar la guía principal
145
+ }
146
+
147
+ // Puebla el selector de DIAGNÓSTICOS
148
+ function populateDiagnosisSelector(guideData) {
149
+ console.log(`[proa.js v12] Poblando selector de diagnósticos para: ${guideData.title}`);
150
+ diagnosisSelector.innerHTML = '<option value="">-- Seleccione Diagnóstico --</option>'; // Limpiar
151
+
152
+ if (guideData.hasDiagnoses && Array.isArray(guideData.diagnoses)) {
153
+ const fragment = document.createDocumentFragment();
154
+ guideData.diagnoses.forEach(diagnosis => {
155
+ const option = document.createElement('option');
156
+ option.value = diagnosis.id; // Usar el ID del diagnóstico como valor
157
+ option.textContent = diagnosis.title;
158
+ fragment.appendChild(option);
159
+ });
160
+ diagnosisSelector.appendChild(fragment);
161
+ diagnosisSelectorContainer.classList.remove('hidden'); // Mostrar contenedor
162
+ console.log(`[proa.js v12] Selector de diagnósticos poblado con ${guideData.diagnoses.length} opciones.`);
163
+ } else {
164
+ console.warn("[proa.js v12] Se intentó poblar diagnósticos para una guía sin ellos o con datos inválidos.");
165
+ diagnosisSelectorContainer.classList.add('hidden'); // Asegurarse que esté oculto
166
+ }
167
  }
168
+
169
  // ======================================================================
170
  // BLOCK END: UI Update Functions
171
  // ======================================================================
172
 
173
  // ======================================================================
174
+ // BLOCK START: Content Loading Functions
175
  // ======================================================================
176
+
177
+ // Carga el CONTENIDO COMPLETO de una guía (para guías SIN diagnósticos)
178
+ async function loadFullGuideContent(guideFile) {
179
+ if (!guideFile) {
180
+ resetUI();
181
+ return;
182
  }
183
+ console.log(`[proa.js v12] Solicitando contenido COMPLETO de: ${guideFile}`);
184
+ guideContentDisplay.innerHTML = '<div class="text-center py-20"><i class="fas fa-spinner fa-spin text-3xl text-gray-400"></i><p class="mt-2 text-gray-500">Cargando guía completa...</p></div>';
185
+ currentGuideHTMLContent = null; // Limpiar cache
 
186
 
187
  try {
188
+ const response = await fetch(guideFile);
189
+ if (!response.ok) throw new Error(`Error HTTP ${response.status} al cargar ${guideFile}`);
190
  const htmlText = await response.text();
191
+
192
+ // Parsear y extraer contenido principal (mismo método que antes)
193
  const parser = new DOMParser();
194
  const doc = parser.parseFromString(htmlText, 'text/html');
195
+ // Intentar selector específico, si no, usar body
196
+ const contentNode = doc.querySelector('.max-w-4xl.mx-auto.px-4.py-8') || doc.body;
197
 
198
  if (contentNode) {
199
  const clonedContent = contentNode.cloneNode(true);
200
+ // Eliminar scripts del contenido clonado
201
  const scripts = clonedContent.querySelectorAll('script');
202
  scripts.forEach(script => script.remove());
203
+ if (scripts.length > 0) console.log(`[proa.js v12] Eliminados ${scripts.length} script(s) de ${guideFile}.`);
 
 
 
 
 
204
 
205
+ guideContentDisplay.innerHTML = ''; // Limpiar área
206
+ guideContentDisplay.appendChild(clonedContent); // Añadir contenido limpio
207
+ console.log(`[proa.js v12] Contenido COMPLETO de ${guideFile} mostrado.`);
208
+ guideContentDisplay.scrollTop = 0; // Ir al inicio del contenido
209
  } else {
210
+ throw new Error(`No se encontró nodo de contenido principal en '${guideFile}'.`);
211
  }
212
  } catch (error) {
213
+ console.error(`[proa.js v12] Error al cargar/mostrar contenido COMPLETO de ${guideFile}:`, error);
214
+ guideContentDisplay.innerHTML = `<div class="text-center py-20 text-red-600">Error al cargar contenido: ${error.message}</div>`;
 
215
  }
216
  }
217
+
218
+ // Carga y cachea el HTML de una guía CON diagnósticos, luego muestra el diagnóstico especificado
219
+ async function loadAndDisplayDiagnosisContent(guideData, diagnosisId) {
220
+ console.log(`[proa.js v12] Solicitando diagnóstico '${diagnosisId}' de la guía '${guideData.title}' (${guideData.file})`);
221
+ guideContentDisplay.innerHTML = '<div class="text-center py-20"><i class="fas fa-spinner fa-spin text-3xl text-gray-400"></i><p class="mt-2 text-gray-500">Cargando diagnóstico...</p></div>';
222
+
223
+ try {
224
+ // Si el HTML de la guía no está cacheado, cargarlo
225
+ if (!currentGuideHTMLContent) {
226
+ console.log(`[proa.js v12] HTML de ${guideData.file} no cacheado. Realizando fetch...`);
227
+ const response = await fetch(guideData.file);
228
+ if (!response.ok) throw new Error(`Error HTTP ${response.status} al cargar ${guideData.file}`);
229
+ currentGuideHTMLContent = await response.text();
230
+ console.log(`[proa.js v12] HTML de ${guideData.file} cargado y cacheado.`);
231
+ } else {
232
+ console.log(`[proa.js v12] Usando HTML cacheado de ${guideData.file}.`);
233
+ }
234
+
235
+ // Parsear el HTML (cacheado o recién cargado)
236
+ const parser = new DOMParser();
237
+ const doc = parser.parseFromString(currentGuideHTMLContent, 'text/html');
238
+
239
+ // Buscar el div específico del diagnóstico por su ID
240
+ const diagnosisNode = doc.getElementById(diagnosisId);
241
+
242
+ if (diagnosisNode) {
243
+ console.log(`[proa.js v12] Nodo para diagnóstico ID '${diagnosisId}' encontrado.`);
244
+ const clonedDiagnosisContent = diagnosisNode.cloneNode(true);
245
+
246
+ // Opcional: Limpiar scripts si los hubiera dentro del div del diagnóstico (poco probable pero seguro)
247
+ const scripts = clonedDiagnosisContent.querySelectorAll('script');
248
+ scripts.forEach(script => script.remove());
249
+ if (scripts.length > 0) console.log(`[proa.js v12] Eliminados ${scripts.length} script(s) del nodo de diagnóstico.`);
250
+
251
+ guideContentDisplay.innerHTML = ''; // Limpiar área
252
+ guideContentDisplay.appendChild(clonedDiagnosisContent); // Añadir contenido del diagnóstico
253
+ console.log(`[proa.js v12] Contenido del diagnóstico '${diagnosisId}' mostrado.`);
254
+ guideContentDisplay.scrollTop = 0; // Ir al inicio
255
+ } else {
256
+ throw new Error(`No se encontró el elemento con ID '${diagnosisId}' dentro de '${guideData.file}'. Verifica la estructura del HTML de la guía.`);
257
+ }
258
+ } catch (error) {
259
+ console.error(`[proa.js v12] Error al cargar/mostrar diagnóstico '${diagnosisId}' de ${guideData.file}:`, error);
260
+ guideContentDisplay.innerHTML = `<div class="text-center py-20 text-red-600">Error al cargar diagnóstico: ${error.message}</div>`;
261
+ // Podríamos querer limpiar el cache si falla la carga
262
+ // currentGuideHTMLContent = null;
263
+ }
264
+ }
265
+
266
  // ======================================================================
267
+ // BLOCK END: Content Loading Functions
268
  // ======================================================================
269
 
270
  // ======================================================================
271
  // BLOCK START: Event Listeners Setup
272
  // ======================================================================
273
+
274
+ // --- Listener para el selector PRINCIPAL de Guías ---
275
  guideSelector.addEventListener('change', (event) => {
276
+ const selectedOption = event.target.selectedOptions[0];
277
+ const guideId = selectedOption.value;
278
+ console.log(`[proa.js v12] Cambió la guía principal seleccionada. ID: ${guideId}`);
279
+
280
+ // Limpiar UI secundaria y cache de contenido
281
+ resetUI(false); // No resetea el selector principal
282
+
283
+ if (!guideId) {
284
+ // Si se seleccionó la opción placeholder "-- Seleccione Guía --"
285
+ return; // No hacer nada más
286
+ }
287
+
288
+ // Encontrar los datos completos de la guía seleccionada
289
+ currentSelectedGuideData = allGuides.find(g => g.id === guideId);
290
+
291
+ if (!currentSelectedGuideData) {
292
+ console.error(`[proa.js v12] No se encontraron datos para la guía con ID: ${guideId}`);
293
+ guideContentDisplay.innerHTML = '<p class="text-red-500 text-center py-10">Error: Datos de guía no encontrados.</p>';
294
+ return;
295
+ }
296
+
297
+ // Decidir si mostrar selector de diagnóstico o cargar contenido completo
298
+ if (currentSelectedGuideData.hasDiagnoses === true) {
299
+ console.log(`[proa.js v12] La guía '${currentSelectedGuideData.title}' tiene diagnósticos. Poblando selector secundario.`);
300
+ populateDiagnosisSelector(currentSelectedGuideData);
301
+ // Mostrar un mensaje inicial diferente en el área de contenido
302
+ guideContentDisplay.innerHTML = '<div class="text-center py-16 text-gray-400"><i class="fas fa-stethoscope text-5xl mb-4"></i><p>Selecciona un diagnóstico específico del desplegable superior.</p></div>';
303
+ } else {
304
+ console.log(`[proa.js v12] La guía '${currentSelectedGuideData.title}' no tiene diagnósticos. Cargando contenido completo.`);
305
+ diagnosisSelectorContainer.classList.add('hidden'); // Asegurarse que el selector de diagnóstico esté oculto
306
+ loadFullGuideContent(currentSelectedGuideData.file);
307
+ }
308
  });
309
 
310
+ // --- Listener para el selector SECUNDARIO de Diagnósticos ---
311
+ diagnosisSelector.addEventListener('change', (event) => {
312
+ const diagnosisId = event.target.value;
313
+ console.log(`[proa.js v12] Cambió el diagnóstico seleccionado. ID: ${diagnosisId}`);
314
+
315
+ if (!diagnosisId) {
316
+ // Si se seleccionó "-- Seleccione Diagnóstico --"
317
+ guideContentDisplay.innerHTML = '<div class="text-center py-16 text-gray-400"><i class="fas fa-stethoscope text-5xl mb-4"></i><p>Selecciona un diagnóstico específico del desplegable superior.</p></div>';
318
+ return;
319
+ }
320
+
321
+ if (currentSelectedGuideData && currentSelectedGuideData.hasDiagnoses) {
322
+ loadAndDisplayDiagnosisContent(currentSelectedGuideData, diagnosisId);
323
+ } else {
324
+ console.error("[proa.js v12] Se intentó cargar un diagnóstico pero no hay guía con diagnósticos seleccionada.");
325
+ guideContentDisplay.innerHTML = '<p class="text-red-500 text-center py-10">Error: Guía base no seleccionada correctamente.</p>';
326
+ }
327
+ });
328
+
329
+ // --- Listener para el checkbox Pediátrico/Adulto ---
330
  togglePediatricCheckbox.addEventListener('change', () => {
331
+ console.log('[proa.js v12] Cambiado filtro pediátrico.');
332
+ // Repoblar el selector principal y resetear completamente la UI
333
+ populateGuideSelector();
334
+ // resetUI() ya se llama dentro de populateGuideSelector, así que no hace falta llamarlo de nuevo explícitamente aquí.
335
  });
336
+
337
+ console.log("[proa.js v12] Listeners añadidos.");
338
  // ======================================================================
339
  // BLOCK END: Event Listeners Setup
340
  // ======================================================================
 
342
  // ======================================================================
343
  // BLOCK START: Initial Execution
344
  // ======================================================================
345
+ loadGuidesData(); // Cargar JSON e iniciar UI
346
  // ======================================================================
347
  // BLOCK END: Initial Execution
348
  // ======================================================================
349
 
350
  }); // Fin DOMContentLoaded
351
+ console.log("[proa.js v12] Script completamente definido.");