/* ============================================ INICIALIZACIÓN DE ELEMENTOS DE LA PÁGINA (independiente del header) ============================================ */ document.addEventListener("DOMContentLoaded", () => { visualizarRosario(); recordatorioDifuntos(); cargarIntencionesIndex(); personalizarSeccionDiario(); }); // visualizarSalmo se llama directamente porque salmo-pcpal // está en el HTML estático y este script está al final del body if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', visualizarSalmo); } else { visualizarSalmo(); } /* ============================================ VARIABLES GLOBALES ============================================ */ // Las variables globales comunes (fechaHoyElem, etc.) se declaran en header.js let salmoDelDiaElem; /* ============================================ INICIALIZAR VARIABLES ============================================ */ function inicializarVariables() { cabeceraHoy = document.getElementById('header-hoy'); menuPrincipalElem = document.getElementById('menu-principal'); errorElem = document.getElementById('__error'); salmoDelDiaElem = document.getElementById('salmo-pcpal'); fechaHoyElem = document.getElementById('fecha-hoy'); nombreCicloElem = document.getElementById('nombre_ciclo'); cicloParImparElem = document.getElementById('ciclo_par_impar'); descripcionSantoDelDiaElem = document.getElementById('descripcion-santo-del-dia'); indicadorLiturgicoElem = document.getElementById('indicador-liturgico'); } /* ============================================ SALMO DEL DÍA ============================================ */ async function visualizarSalmo() { const salmoElem = document.getElementById('salmo-pcpal'); if (!salmoElem) { console.error("No se encontró el elemento 'salmo-pcpal' en el DOM"); return; } try { const res = await fetch(`${API_BASE}/versos/hoy`); if (!res.ok) throw new Error("Error en fetch"); const verso = await res.json(); if (verso && verso.texto) { salmoElem.innerHTML = `${verso.texto}
— ${verso.fuente} ${verso.numero}`; } else { salmoElem.textContent = "El Señor es mi pastor, nada me falta."; } } catch (e) { console.warn("API no disponible, cargando salmo local:", e); try { const res2 = await fetch('data/salmos.json'); const salmos = await res2.json(); const hoy = new Date(); const diaAnyo = Math.floor((hoy - new Date(hoy.getFullYear(), 0, 0)) / 86400000); const salmo = salmos[diaAnyo % salmos.length]; salmoElem.innerHTML = `${salmo.texto}
— Salmo ${salmo.numero}`; } catch (e2) { salmoElem.textContent = "Bendice, alma mía, al Señor."; } } } /* ============================================ ROSARIO DEL DÍA ============================================ */ function visualizarRosario() { const MISTERIOS_DATA = { 0: { nombre: "Gloriosos" }, 1: { nombre: "Gozosos"}, 2: { nombre: "Dolorosos" }, 3: { nombre: "Gloriosos" }, 4: { nombre: "Luminosos" }, 5: { nombre: "Dolorosos" }, 6: { nombre: "Gozosos" } }; const hoy = new Date(); const diaSemana = hoy.getDay(); const misterioHoy = MISTERIOS_DATA[diaSemana]; const nombreMistElem = document.getElementById('nombre_misterio'); if (nombreMistElem) { nombreMistElem.textContent = `MISTERIOS ${misterioHoy.nombre.toUpperCase()}`; } } /* ============================================ FECHA HUMANA ============================================ */ function visualizarDatos() { const opcionesFecha = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; const hoy = new Date(); fechaHoyElem.textContent = hoy.toLocaleDateString('es-ES', opcionesFecha); } /* ============================================ CALENDARIO LITÚRGICO ============================================ */ /* ============================================ RECORDATORIO DE DIFUNTOS ============================================ */ async function recordatorioDifuntos() { const seccion = document.getElementById("seccion-recordatorio"); if (!seccion) return; const hoy = new Date(); const mmdd = String(hoy.getMonth() + 1).padStart(2, "0") + "-" + String(hoy.getDate()).padStart(2, "0"); // 1. Lista compartida desde difuntos.json (normalizar fallecimiento -> defuncion) let difuntosJSON = []; try { const res = await fetch('data/difuntos.json'); if (res.ok) { const data = await res.json(); difuntosJSON = data.map(d => ({ nombre: d.nombre, nacimiento: d.nacimiento, defuncion: d.fallecimiento, nota: d.nota || "" })); } } catch (e) { /* sin conexion */ } // 2. Difuntos personales desde localStorage const usuarioGuardado = typeof getUsuario === 'function' ? getUsuario() : null; const clave = usuarioGuardado ? `difuntos_personales_${usuarioGuardado.id}` : "difuntos_personales_anonimo"; const difuntosLocal = JSON.parse(localStorage.getItem(clave) || "[]"); // 3. Combinar (locales primero, sin duplicados por nombre) const nombresSeen = new Set(); const todos = [...difuntosLocal, ...difuntosJSON].filter(d => { if (!d.nombre || nombresSeen.has(d.nombre)) return false; nombresSeen.add(d.nombre); return true; }); if (todos.length === 0) return; // 4. Detectar aniversarios de hoy const recordatorios = []; todos.forEach(d => { if (d.nacimiento && !d.nacimiento.includes('XXXX')) { const partes = d.nacimiento.split("-"); if (partes.length === 3 && partes[1] + "-" + partes[2] === mmdd) { const anios = hoy.getFullYear() - parseInt(partes[0]); recordatorios.push("\uD83C\uDF82 Hoy habr\u00eda sido el cumplea\u00F1os de " + d.nombre + " — " + anios + " a\u00F1os"); } } if (d.defuncion && !d.defuncion.includes('XXXX')) { const partes = d.defuncion.split("-"); if (partes.length === 3 && partes[1] + "-" + partes[2] === mmdd) { const anios = hoy.getFullYear() - parseInt(partes[0]); recordatorios.push("\uD83D\uDD6F Hoy es el " + anios + ".\u00BA aniversario del fallecimiento de " + d.nombre + ""); } } }); // 5. Construir HTML seccion.style.display = "block"; let html = '

\uD83D\uDD6F En el recuerdo

'; if (recordatorios.length > 0) { html += recordatorios.map(r => `

${r}

`).join(""); html += '

"D\u00E1les, Se\u00F1or, el descanso eterno y brille para ellos la luz perpetua."

'; html += '
'; } html += ''; seccion.innerHTML = html; } /* ============================================ CALENDARIO LITÚRGICO ============================================ */ async function cargarYActualizarTodo() { const hoy = new Date(); const fechaISO = hoy.toISOString().split('T')[0]; cicloParImparElem.textContent = hoy.getFullYear() % 2 === 0 ? "Año Par" : "Año Impar"; if (hoy.getFullYear() % 3 === 0) { nombreCicloElem.textContent = "Ciclo C -"; } else if (hoy.getFullYear() % 3 === 1) { nombreCicloElem.textContent = "Ciclo A -"; } else { nombreCicloElem.textContent = "Ciclo B -"; } try { const respuesta = await fetch(`${API_BASE}/calendario/hoy`); if (!respuesta.ok) throw new Error("Sin datos litúrgicos"); const datosHoy = await respuesta.json(); const mapaColores = { "verde": "#2d5a27", "morado": "#5d2d91", "blanco": "#ffffff", "rojo": "#b30000", "azul": "#0074d9", "rosa": "#e7b1cc", "violeta": "#a0b5b0" }; if (datosHoy) { const colorReal = mapaColores[datosHoy.color] || "#333"; const colorTexto = (datosHoy.color === "blanco" || datosHoy.color === "rosa") ? "#2b2b2b" : "#ffffff"; cabeceraHoy.style.backgroundColor = colorReal; menuPrincipalElem.style.backgroundColor = colorReal; cabeceraHoy.style.color = colorTexto; indicadorLiturgicoElem.textContent = datosHoy.tiempo; indicadorLiturgicoElem.style.color = colorTexto; } } catch (error) { console.error("Error cargando el calendario:", error); } } /* ============================================ INTENCIONES DEL USUARIO EN LA PORTADA ============================================ */ async function cargarIntencionesIndex() { const lista = document.getElementById("lista-intenciones-index"); if (!lista) return; const usuario = typeof getUsuario === 'function' ? getUsuario() : null; if (!usuario) return; // sin sesión: se mantienen las intenciones genéricas // Actualizar título y enlace const titulo = document.getElementById("titulo-intenciones"); if (titulo) titulo.textContent = "\uD83D\uDE4F Mis intenciones"; let intenciones = []; // Intentar cargar desde la API try { if (typeof apiCall === 'function') { const response = await apiCall("/intenciones/personales"); if (response && response.ok) { intenciones = await response.json(); } } } catch (e) { /* sin conexión al backend */ } // Fallback a localStorage if (intenciones.length === 0) { const clave = `intenciones_${usuario.id}`; const local = JSON.parse(localStorage.getItem(clave) || localStorage.getItem("intenciones") || "[]"); intenciones = local.map(i => ({ texto: i.texto })); } if (intenciones.length === 0) { lista.innerHTML = '
  • A\u00FAn no tienes intenciones. A\u00F1adir
  • '; return; } // Mostrar hasta 5 intenciones lista.innerHTML = intenciones.slice(0, 5) .map(i => `
  • ${i.texto}
  • `) .join(""); } /* ============================================ PERSONALIZACIÓN SECCIÓN DIARIO EN PORTADA ============================================ */ function personalizarSeccionDiario() { const previewElem = document.getElementById('diario-preview-index'); const textoElem = document.getElementById('texto-diario-index'); const botonElem = document.getElementById('boton-diario-index'); if (!previewElem) return; const usuario = typeof getUsuario === 'function' ? getUsuario() : null; if (!usuario) return; // sin sesión: se muestra el texto genérico // Ajustar texto intro con el nombre if (textoElem) { textoElem.textContent = `Tu espacio personal, ${usuario.nombre}.`; } // Buscar entrada de hoy en localStorage const hoy = (() => { const d = new Date(); const offset = d.getTimezoneOffset() * 60000; return new Date(d - offset).toISOString().split('T')[0]; })(); let entradas = {}; try { const data = localStorage.getItem(`diario_${usuario.id}`); if (data) entradas = JSON.parse(data); } catch (e) { /* sin entradas */ } const entradaHoy = entradas[hoy] || null; if (entradaHoy && entradaHoy.texto) { const icono = { paz: '🕊️', gratitud: '🙏', lucha: '😔', gozo: '✨', silencio: '🌿' }[entradaHoy.estado] || '🕯'; const preview = entradaHoy.texto.substring(0, 120) + (entradaHoy.texto.length > 120 ? '…' : ''); previewElem.innerHTML = `
    ${icono} ${entradaHoy.titulo || 'Mi oración de hoy'} ${preview}
    `; if (botonElem) botonElem.textContent = 'Continuar escribiendo'; } }