aarnal80 commited on
Commit
8b295ca
·
verified ·
1 Parent(s): 5794a0d

Update js/proa.js

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