recursos-catolicos/frontend/js/codigo.js

377 lines
13 KiB
JavaScript

/* ============================================
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}<br><cite style="font-size:0.8em;opacity:0.7;">— ${verso.fuente} ${verso.numero}</cite>`;
} 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}<br><cite style="font-size:0.8em;opacity:0.7;">— Salmo ${salmo.numero}</cite>`;
} 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 mesActual = hoy.getMonth() + 1; // 1-12
const mmdd = String(mesActual).padStart(2, "0") + "-" + String(hoy.getDate()).padStart(2, "0");
const nombreMes = hoy.toLocaleDateString('es-ES', { month: 'long' });
// 1. Difuntos personales desde la API (usuario logueado) o localStorage
const usuarioGuardado = typeof getUsuario === 'function' ? getUsuario() : null;
let todosDifuntos = [];
if (usuarioGuardado) {
try {
const res = await fetch(`${API_BASE}/difuntos/personales`, {
headers: { 'Authorization': 'Bearer ' + (localStorage.getItem('token') || '') }
});
if (res.ok) {
todosDifuntos = await res.json();
// La API devuelve 'defuncion', igual que localStorage
}
} catch (e) { /* sin conexión */ }
}
// Fallback localStorage si no hay API o no hay usuario
if (todosDifuntos.length === 0) {
const clave = usuarioGuardado
? `difuntos_personales_${usuarioGuardado.id}`
: "difuntos_personales_anonimo";
todosDifuntos = JSON.parse(localStorage.getItem(clave) || "[]");
}
if (todosDifuntos.length === 0) return;
// 2. Filtrar los que tienen aniversario o cumpleaños en el mes actual
const delMes = todosDifuntos.filter(d => {
const nacMes = d.nacimiento && !d.nacimiento.includes('XXXX')
? parseInt(d.nacimiento.split('-')[1]) : null;
const defMes = d.defuncion && !d.defuncion.includes('XXXX')
? parseInt(d.defuncion.split('-')[1]) : null;
return nacMes === mesActual || defMes === mesActual;
});
if (delMes.length === 0) return;
// 3. Detectar aniversarios de hoy (dentro de los del mes)
const recordatorios = [];
delMes.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("🎂 Hoy habría sido el cumpleaños de <strong>" + d.nombre + "</strong> &mdash; " + anios + " años");
}
}
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("🕯 Hoy es el " + anios + ".º aniversario del fallecimiento de <strong>" + d.nombre + "</strong>");
}
}
});
// 4. Construir HTML
seccion.style.display = "block";
let html = `<h3>🕯 En el recuerdo — ${nombreMes.charAt(0).toUpperCase() + nombreMes.slice(1)}</h3>`;
if (recordatorios.length > 0) {
html += recordatorios.map(r => `<p>${r}</p>`).join("");
html += '<p class="recordatorio-oracion"><em>"Dales, Señor, el descanso eterno y brille para ellos la luz perpetua."</em></p>';
html += '<hr style="border-color:rgba(255,255,255,0.15);margin:0.8rem 0;">';
}
html += '<ul class="lista-difuntos-index">';
delMes.forEach(d => {
let fechaStr = "";
if (d.nacimiento && !d.nacimiento.includes('XXXX')) {
const dia = parseInt(d.nacimiento.split('-')[2]);
fechaStr += ` <span class="anio-difunto">(🎂 ${dia})</span>`;
}
if (d.defuncion && !d.defuncion.includes('XXXX')) {
const dia = parseInt(d.defuncion.split('-')[2]);
const anio = parseInt(d.defuncion.split('-')[0]);
fechaStr += ` <span class="anio-difunto">(✝ ${dia}${anio > 1000 ? ' · ' + anio : ''})</span>`;
}
html += '<li>🕊 ' + d.nombre + fechaStr + '</li>';
});
html += '</ul>';
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 = '<li class="texto-suave">A\u00FAn no tienes intenciones. <a href="intenciones.html">A\u00F1adir</a></li>';
return;
}
// Mostrar hasta 5 intenciones
lista.innerHTML = intenciones.slice(0, 5)
.map(i => `<li>${i.texto}</li>`)
.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 = `
<div class="diario-preview-index">
<strong>${icono} ${entradaHoy.titulo || 'Mi oración de hoy'}</strong>
${preview}
</div>
`;
if (botonElem) botonElem.textContent = 'Continuar escribiendo';
}
}