/* ============================================ INICIALIZACIÓN DE ELEMENTOS DE LA PÁGINA (independiente del header) ============================================ */ document.addEventListener("DOMContentLoaded", () => { visualizarSalmo(); visualizarRosario(); recordatorioDifuntos(); cargarIntencionesIndex(); }); /* ============================================ VARIABLES GLOBALES ============================================ */ let fechaHoyElem, indicadorLiturgicoElem, cabeceraHoy, menuPrincipalElem, nombreCicloElem, cicloParImparElem, descripcionSantoDelDiaElem, errorElem, 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() { // Buscamos el elemento directamente para evitar fallos de referencia global 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('data/salmos.json'); if (!res.ok) throw new Error("Error en fetch"); const listaSalmos = await res.json(); // Cálculo del día del año corregido const hoy = new Date(); const inicioAnio = new Date(hoy.getFullYear(), 0, 0); const dif = hoy - inicioAnio; const diaDelAnio = Math.floor(dif / (1000 * 60 * 60 * 24)); // Obtenemos el salmo (0 a 149) const indiceHoy = diaDelAnio % listaSalmos.length; const salmoDeHoy = listaSalmos[indiceHoy]; if (salmoDeHoy && salmoDeHoy.texto) { salmoElem.textContent = salmoDeHoy.texto; } else { salmoElem.textContent = "El Señor es mi pastor, nada me falta."; } } catch (e) { console.error("Error cargando el salmo:", e); 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('data/calendario-liturgico.json'); const datosCalendario = await respuesta.json(); const datosHoy = datosCalendario.find(dia => dia.fecha === fechaISO); 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(""); }