-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1588 lines (1375 loc) · 49.1 KB
/
script.js
File metadata and controls
1588 lines (1375 loc) · 49.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ========== SECURITY: XSS Prevention ==========
// Sanitize HTML to prevent XSS attacks when using innerHTML with user/data content
function sanitizeHTML(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// Create safe HTML elements without innerHTML injection vulnerability
function createSafeElement(tag, className, htmlContent = null) {
const element = document.createElement(tag);
if (className) element.className = className;
if (htmlContent) {
// Only use innerHTML if content is known-safe (no user input)
element.innerHTML = htmlContent;
}
return element;
}
// ============================================
// Variables globales
let hexagramasData = null;
let consultaActual = null;
const HEXAGRAMAS_API = "hexagramas.json";
const DESTACADOS_IDS = [1, 2, 11, 12, 24, 64]; // IDs de los hexagramas destacados
let consultasGuardadas = [];
let recognition;
let isListening = false;
let voiceErrorDiv;
let modalOpen = false;
let valuesModalOpen = false;
let shareModalOpen = false;
let isScriptReady = false;
let deferredPrompt;
// Función para esperar a que un elemento esté disponible (optimizada con requestAnimationFrame)
function waitForElement(selector, callback, maxAttempts = 60, interval = null) {
let attempts = 0;
const maxTime = 6000; // 6 segundos máximo
const startTime = Date.now();
const checkElement = () => {
attempts++;
const element = document.querySelector(selector);
if (element) {
console.log(`✅ Elemento encontrado: ${selector}`);
callback(element);
return true;
} else if (attempts < maxAttempts && (Date.now() - startTime) < maxTime) {
// Usar requestAnimationFrame en lugar de setTimeout para mejor rendimiento
requestAnimationFrame(checkElement);
} else {
console.error(
`❌ Elemento no encontrado después de ${maxAttempts} intentos: ${selector}`
);
return false;
}
};
// Primera búsqueda inmediata
if (document.querySelector(selector)) {
callback(document.querySelector(selector));
return;
}
checkElement();
}
// Función para esperar múltiples elementos (optimizada con requestAnimationFrame)
function waitForElements(
selectors,
callback,
maxAttempts = 60,
interval = null
) {
let attempts = 0;
const maxTime = 6000; // 6 segundos máximo
const startTime = Date.now();
const checkElements = () => {
attempts++;
const elements = {};
let allFound = true;
for (const [key, selector] of Object.entries(selectors)) {
elements[key] = document.querySelector(selector);
if (!elements[key]) {
allFound = false;
}
}
if (allFound) {
console.log("✅ Todos los elementos necesarios están disponibles");
callback(elements);
return true;
} else if (attempts < maxAttempts && (Date.now() - startTime) < maxTime) {
requestAnimationFrame(checkElements);
} else {
console.error(
`❌ Uno o más elementos no encontrados después de ${maxAttempts} intentos`
);
return false;
}
};
checkElements();
}
// Añadir estilos de error
function addErrorStyles() {
const style = document.createElement("style");
style.textContent = `
#oracleQuestion.error {
animation: shake 0.5s;
border-color: #d32f2f;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
`;
document.head.appendChild(style);
}
// Configurar navegación suave
function setupNavigation() {
document.querySelectorAll("nav a").forEach((anchor) => {
anchor.addEventListener("click", function (e) {
e.preventDefault();
const targetId = this.getAttribute("href");
document.querySelector(targetId).scrollIntoView({
behavior: "smooth",
});
});
});
}
// Función para cargar los datos de hexagramas
async function loadHexagramData() {
if (hexagramasData) return hexagramasData; // Usar caché si ya están cargados
try {
const response = await fetch(HEXAGRAMAS_API);
if (!response.ok) {
throw new Error("No se pudo cargar la biblioteca de hexagramas");
}
hexagramasData = await response.json();
return hexagramasData;
} catch (error) {
console.error("❌ Error al cargar hexagramas:", error);
// Datos de respaldo mínimo en caso de fallo
hexagramasData = {
hexagramas: [
{
id: 1,
nombre: "Error de carga",
juicio: "No se pudieron cargar los datos de los hexagramas",
imagen:
"Cielo y tierra unidos: la imagen de la Paz. Así el soberano divide y completa el curso del cielo y la tierra; fomenta y regula los dones del cielo y la tierra, y así ayuda al pueblo.",
lineas: [
"Primera línea (6): Cuando se acerca la paz, pequeño desorden. No hay culpa en ello. Perseverancia trae buena fortuna.",
"Segunda línea (7): Paz. Lo pequeño se va, lo grande viene. Ventura. Éxito.",
"Tercera línea (8): No persigas después de la paz. Permanece en tu lugar. La desdicha acecha.",
"Cuarta línea (8): Paz. No es bueno confiar en uno mismo. Mejor buscar aliados.",
"Quinta línea (9): El rey Wei da a luz a la paz. No es bueno hacer la guerra. Es bueno correr peligros grandes. Ninguna culpa.",
"Sexta línea (6): La paz se disipa. Primero canta y baila, luego llora y gime. La desdicha acecha.",
],
binario: "111111",
},
],
};
return hexagramasData;
}
}
// Función para encontrar un hexagrama por ID
async function findHexagramById(id) {
const data = await loadHexagramData();
return (
data.hexagramas.find((h) => h.id === parseInt(id)) || data.hexagramas[0]
);
}
// Función para encontrar un hexagrama por binario
async function findHexagramByBinary(binary) {
const data = await loadHexagramData();
return (
data.hexagramas.find((h) => h.binario === binary) || data.hexagramas[0]
);
}
// Función para lanzar monedas
function castCoins() {
const lines = [];
for (let i = 0; i < 6; i++) {
let sum = 0;
for (let j = 0; j < 3; j++) {
sum += Math.floor(Math.random() * 2); // 0 o 1
}
// Convertir a línea de I Ching:
// 3 = yang (9, línea entera mutante)
// 0 = yin (6, línea quebrada mutante)
// 2 = yin (8, línea quebrada)
// 1 = yang (7, línea entera)
let lineType;
if (sum === 3) {
lineType = { type: "yang", changing: true, value: 9 };
} else if (sum === 0) {
lineType = { type: "yin", changing: true, value: 6 };
} else if (sum === 2) {
lineType = { type: "yin", changing: false, value: 8 };
} else {
lineType = { type: "yang", changing: false, value: 7 };
}
lines.push(lineType);
}
return lines;
}
// Dibujar hexagrama
function drawHexagram(lines) {
const hexagramDisplay = document.getElementById("hexagramDisplay");
if (!hexagramDisplay) {
console.error("❌ Elemento hexagramDisplay no encontrado");
return;
}
hexagramDisplay.innerHTML = "";
// Dibujar de abajo hacia arriba (línea 1 es la de abajo)
for (let i = 0; i < 6; i++) {
const lineDiv = document.createElement("div");
lineDiv.className = lines[i].type === "yang" ? "line" : "line broken";
if (lines[i].changing) {
lineDiv.classList.add("changing");
}
hexagramDisplay.appendChild(lineDiv);
}
}
// Mostrar líneas mutantes
function showChangingLines(lines, hexagram) {
const changingLinesContainer = document.getElementById(
"changingLinesContainer"
);
if (!changingLinesContainer) {
console.error("❌ Elemento changingLinesContainer no encontrado");
return;
}
changingLinesContainer.innerHTML = "";
const header = createSafeElement('h4', null, 'Líneas Mutantes');
changingLinesContainer.appendChild(header);
const changingLines = lines.filter((line) => line.changing);
if (changingLines.length === 0) {
const noLines = createSafeElement('p', null, 'No hay líneas mutantes en esta consulta');
changingLinesContainer.appendChild(noLines);
return;
}
changingLines.forEach((line, index) => {
const linePosition = lines.indexOf(line) + 1;
const lineText =
hexagram.lineas && hexagram.lineas[linePosition - 1]
? hexagram.lineas[linePosition - 1]
: `Línea ${linePosition} (${line.value}): No hay descripción disponible`;
const lineDiv = document.createElement("div");
lineDiv.className = "changing-line";
const strong = document.createElement('strong');
strong.textContent = `Línea ${linePosition} (${line.value}):`;
const textNode = document.createTextNode(' ' + lineText);
lineDiv.appendChild(strong);
lineDiv.appendChild(textNode);
changingLinesContainer.appendChild(lineDiv);
});
}
// Mostrar resultados
function showResults(hexagram, lines) {
const hexagramNumber = document.getElementById("hexagramNumber");
const hexagramName = document.getElementById("hexagramName");
const hexagramJudgment = document.getElementById("hexagramJudgment");
const hexagramImage = document.getElementById("hexagramImage");
const resultContainer = document.getElementById("resultContainer");
if (
!hexagramNumber ||
!hexagramName ||
!hexagramJudgment ||
!hexagramImage ||
!resultContainer
) {
console.error("❌ Elementos de resultados no encontrados");
return;
}
hexagramNumber.textContent = `#${hexagram.id}`;
hexagramName.textContent = hexagram.nombre;
hexagramJudgment.textContent = hexagram.juicio;
hexagramImage.textContent = hexagram.imagen;
showChangingLines(lines, hexagram);
resultContainer.classList.remove("hidden");
resultContainer.classList.add("fade-in");
// Scroll a resultados
resultContainer.scrollIntoView({ behavior: "smooth" });
}
// Función para guardar consulta
function guardarConsulta(hexagrama, lines, pregunta) {
const consulta = {
id: Date.now(), // Usamos timestamp como ID único
fecha: new Date().toLocaleDateString("es-ES", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
}),
hexagramaId: hexagrama.id,
hexagramaNombre: hexagrama.nombre,
pregunta: pregunta || "Consulta sin título",
lines: lines.map((line) => ({
type: line.type,
changing: line.changing,
value: line.value,
})),
hexagramaBinario: lines
.map((line) => (line.type === "yang" ? "1" : "0"))
.join(""),
hexagrama: hexagrama,
};
consultasGuardadas.push(consulta);
guardarEnCookies();
// Guardar en la variable global para compartir
consultaActual = consulta;
return consulta;
}
// Mostrar historial de consultas
function mostrarHistorial() {
const historialContainer = document.getElementById("historialContainer");
if (!historialContainer) {
console.error("❌ Elemento historialContainer no encontrado");
return;
}
if (consultasGuardadas.length === 0) {
historialContainer.innerHTML = `
<div class="historial-header">
<h3><i class="fas fa-history"></i> Tu Historial de Consultas</h3>
<p>No has realizado ninguna consulta todavía.</p>
</div>
`;
historialContainer.classList.add("hidden");
return;
}
historialContainer.classList.remove("hidden");
historialContainer.innerHTML = `
<div class="historial-header">
<h3><i class="fas fa-history"></i> Tu Historial de Consultas</h3>
<p>Has realizado ${consultasGuardadas.length} consulta${
consultasGuardadas.length === 1 ? "" : "s"
}.</p>
</div>
<div class="historial-list">
${consultasGuardadas
.slice(-3)
.map(
(consulta) => `
<div class="historial-item" data-id="${consulta.id}">
<div class="historial-date">${consulta.fecha}</div>
<div class="historial-question">${consulta.pregunta}</div>
<div class="historial-hexagram">Hexagrama ${consulta.hexagramaId}: ${consulta.hexagramaNombre}</div>
</div>
`
)
.join("")}
</div>
<div style="padding: 0 25px 15px;">
<button id="verHistorialCompleto" class="view-all-btn" style="width: 100%;">
<i class="fas fa-book-open"></i> Ver Todas las Consultas
</button>
</div>
`;
// Añadir evento a los elementos del historial
document.querySelectorAll(".historial-item").forEach((item) => {
item.addEventListener("click", () => {
const id = item.getAttribute("data-id");
const consulta = consultasGuardadas.find((c) => c.id == id);
if (consulta) {
// Mostrar los resultados de esta consulta
findHexagramByBinary(consulta.hexagramaBinario).then((hexagram) => {
showResults(hexagram, consulta.lines);
// Desplazar a resultados
document.getElementById("resultContainer").scrollIntoView({
behavior: "smooth",
});
});
}
});
});
// Evento para ver historial completo
const verHistorialBtn = document.getElementById("verHistorialCompleto");
if (verHistorialBtn) {
verHistorialBtn.addEventListener("click", () => {
mostrarHistorialCompleto();
});
}
}
// Mostrar historial completo en una modal
function mostrarHistorialCompleto() {
// Crear modal si no existe
let modal = document.getElementById("historialModal");
if (!modal) {
modal = document.createElement("div");
modal.id = "historialModal";
modal.className = "modal";
modal.innerHTML = `
<div class="modal-content">
<span class="close-modal">×</span>
<h2>Todas tus Consultas</h2>
<div class="modal-historial-list">
<!-- Contenido dinámico -->
</div>
</div>
`;
document.body.appendChild(modal);
// Cerrar modal al hacer clic en X
modal.querySelector(".close-modal").addEventListener("click", () => {
modal.style.display = "none";
});
// Cerrar modal al hacer clic fuera
window.addEventListener("click", (event) => {
if (event.target === modal) {
modal.style.display = "none";
}
});
// Cerrar modal con ESC
window.addEventListener("keydown", (event) => {
if (event.key === "Escape" && modal.style.display === "block") {
modal.style.display = "none";
}
});
}
// Actualizar contenido
const listContainer = modal.querySelector(".modal-historial-list");
clearElement(listContainer); // Limpiar primero (seguro)
if (consultasGuardadas.length === 0) {
const emptyMsg = document.createElement("p");
setElementText(emptyMsg, "No has realizado ninguna consulta todavía.");
listContainer.appendChild(emptyMsg);
} else {
// ========== SECURITY FIX: Sanitizar datos de usuario ==========
consultasGuardadas.forEach((consulta) => {
const item = document.createElement("div");
item.className = "modal-historial-item";
item.setAttribute("data-id", consulta.id);
// Fecha (es metadata interna, segura)
const dateDiv = document.createElement("div");
dateDiv.className = "historial-date";
dateDiv.textContent = consulta.fecha;
item.appendChild(dateDiv);
// Pregunta del usuario (SANITIZADA con textContent)
const questionDiv = document.createElement("div");
questionDiv.className = "historial-question";
questionDiv.textContent = consulta.pregunta; // ← Escapa HTML automáticamente
item.appendChild(questionDiv);
// Hexagrama (metadata interna, segura)
const hexagramDiv = document.createElement("div");
hexagramDiv.className = "historial-hexagram";
hexagramDiv.textContent = `Hexagrama ${consulta.hexagramaId}: ${consulta.hexagramaNombre}`;
item.appendChild(hexagramDiv);
listContainer.appendChild(item);
});
// ============================================
// Añadir eventos a los elementos
document.querySelectorAll(".modal-historial-item").forEach((item) => {
item.addEventListener("click", () => {
const id = item.getAttribute("data-id");
const consulta = consultasGuardadas.find((c) => c.id == id);
if (consulta) {
findHexagramByBinary(consulta.hexagramaBinario).then((hexagram) => {
showResults(hexagram, consulta.lines);
// Cerrar modal
document.getElementById("historialModal").style.display = "none";
// Desplazar a resultados
document.getElementById("resultContainer").scrollIntoView({
behavior: "smooth",
});
});
}
});
});
}
// Mostrar modal
modal.style.display = "block";
}
// Guardar consultas en cookies
function guardarEnCookies() {
// Mantener solo las últimas 10 consultas
const consultasParaGuardar = consultasGuardadas.slice(-10);
const cookieValue = JSON.stringify(consultasParaGuardar);
// Caduca en 30 días
const expiry = new Date();
expiry.setDate(expiry.getDate() + 30);
document.cookie = `iching_consultas=${cookieValue}; expires=${expiry.toUTCString()}; path=/`;
}
// Cargar consultas de cookies
function cargarConsultasDeCookies() {
try {
const cookieName = "iching_consultas=";
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
if (cookie.indexOf(cookieName) === 0) {
const consultas = JSON.parse(cookie.substring(cookieName.length));
// Mantener solo las últimas 10 consultas
consultasGuardadas = consultas.slice(-10);
return;
}
}
} catch (e) {
console.log("No se pudieron cargar consultas de cookies");
}
}
// Cargar biblioteca de hexagramas destacados
async function loadHighlightedHexagrams() {
try {
const data = await loadHexagramData();
const hexagramLibrary = document.getElementById("hexagramLibrary");
if (!hexagramLibrary) {
console.error("❌ Elemento hexagramLibrary no encontrado");
return;
}
hexagramLibrary.innerHTML = ""; // Limpiar antes de cargar
// Filtrar los hexagramas destacados
const destacados = data.hexagramas.filter((h) =>
DESTACADOS_IDS.includes(h.id)
);
destacados.forEach((hexagram) => {
const card = document.createElement("div");
card.className = "hexagram-card";
card.dataset.id = hexagram.id;
// Crear representación visual del hexagrama
const hexagramVisual = document.createElement("div");
hexagramVisual.className = "card-hexagram";
// Convertir binario a líneas (de abajo hacia arriba)
const lines = hexagram.binario.split("");
for (let i = 5; i >= 0; i--) {
const lineDiv = document.createElement("div");
lineDiv.className =
lines[i] === "1" ? "card-line" : "card-line card-broken";
hexagramVisual.appendChild(lineDiv);
}
card.innerHTML = `
${hexagramVisual.outerHTML}
<div class="card-number">Hexagrama ${hexagram.id}</div>
<div class="card-name">${hexagram.nombre}</div>
<p class="card-judgment">${hexagram.juicio}</p>
<a href="hexagrama.html?id=${hexagram.id}" class="view-details-btn">Ver detalles</a>
`;
hexagramLibrary.appendChild(card);
});
} catch (error) {
console.error("❌ Error al cargar la biblioteca destacada:", error);
const hexagramLibrary = document.getElementById("hexagramLibrary");
if (hexagramLibrary) {
hexagramLibrary.innerHTML =
'<div class="error-message">Error al cargar los hexagramas destacados. Por favor, recarga la página.</div>';
}
}
}
// Configurar el modal del oráculo
function setupOracleModal() {
waitForElements(
{
consultBtn: "#consultBtn",
oracleModal: "#oracleModal",
closeModal: "#oracleModal .modal-content.simplified .close-modal",
cancelModal: "#cancelModal",
submitQuestion: "#submitQuestion",
oracleQuestion: "#oracleQuestion",
},
function (elements) {
const {
consultBtn,
oracleModal,
closeModal,
cancelModal,
submitQuestion,
oracleQuestion,
} = elements;
console.log("✅ Configurando modal del oráculo");
// Mostrar modal al hacer clic en el botón de consulta
consultBtn.addEventListener("click", (e) => {
e.preventDefault();
console.log("🖱️ Botón de consulta clickeado");
oracleModal.style.display = "flex";
setTimeout(() => {
oracleModal.classList.add("show");
}, 10);
// Enfocar el campo de texto
setTimeout(() => {
oracleQuestion.focus();
modalOpen = true;
console.log("⌨️ Campo de pregunta enfocado");
}, 300);
});
// Función para cerrar el modal
function closeModalFunc() {
if (!modalOpen) return;
console.log("❌ Cerrando modal de consulta");
oracleModal.classList.remove("show");
modalOpen = false;
setTimeout(() => {
oracleModal.style.display = "none";
// Limpiar el campo de texto
oracleQuestion.value = "";
}, 300);
}
// Cerrar modal al hacer clic en X
closeModal.addEventListener("click", closeModalFunc);
// Cerrar modal al hacer clic fuera
window.addEventListener("click", (event) => {
if (event.target === oracleModal) {
closeModalFunc();
}
});
// Cerrar modal con ESC
window.addEventListener("keydown", (event) => {
if (event.key === "Escape" && modalOpen) {
closeModalFunc();
}
});
// Cerrar modal al hacer clic en Cancelar
cancelModal.addEventListener("click", closeModalFunc);
// Procesar la consulta al hacer clic en Consultar
submitQuestion.addEventListener("click", () => {
const question = oracleQuestion.value.trim();
if (!question) {
console.log("⚠️ Pregunta vacía");
// Hacer que el textarea se estremezca para indicar error
oracleQuestion.classList.add("error");
setTimeout(() => {
oracleQuestion.classList.remove("error");
}, 1000);
return;
}
console.log("📨 Procesando consulta:", question);
// Cerrar el modal
closeModalFunc();
// Realizar la consulta después de cerrar el modal
setTimeout(() => {
performOracleConsultation(question);
}, 300);
});
}
);
}
// Configurar el modal de valores de monedas
function setupValuesModal() {
waitForElements(
{
viewAllValuesBtn: "#viewAllValuesBtn",
valuesModal: "#valuesModal",
closeModal: "#valuesModal .modal-content.values-modal .close-modal",
closeValuesModal: "#closeValuesModal",
},
function (elements) {
const { viewAllValuesBtn, valuesModal, closeModal, closeValuesModal } =
elements;
console.log("✅ Configurando modal de valores de monedas");
// Mostrar modal al hacer clic en "Ver todos los valores"
viewAllValuesBtn.addEventListener("click", (e) => {
e.preventDefault();
console.log("🖱️ Botón Ver todos los valores clickeado");
valuesModal.style.display = "flex";
setTimeout(() => {
valuesModal.classList.add("show");
}, 10);
valuesModalOpen = true;
});
// Función para cerrar el modal de valores
function closeValuesModalFunc() {
if (!valuesModalOpen) return;
console.log("❌ Cerrando modal de valores");
valuesModal.classList.remove("show");
valuesModalOpen = false;
setTimeout(() => {
valuesModal.style.display = "none";
}, 300);
}
// Cerrar modal al hacer clic en X
closeModal.addEventListener("click", closeValuesModalFunc);
// Cerrar modal al hacer clic fuera
window.addEventListener("click", (event) => {
if (event.target === valuesModal) {
closeValuesModalFunc();
}
});
// Cerrar modal con ESC
window.addEventListener("keydown", (event) => {
if (event.key === "Escape" && valuesModalOpen) {
closeValuesModalFunc();
}
});
// Cerrar modal al hacer clic en "Entendido"
closeValuesModal.addEventListener("click", closeValuesModalFunc);
}
);
}
// Configurar el modal de compartir
function setupShareModal() {
const shareModal = document.getElementById("shareModal");
if (!shareModal) {
console.error("❌ Modal de compartir no encontrado");
return;
}
// Cerrar modal al hacer clic en X
const closeModal = shareModal.querySelector(".close-share");
if (closeModal) {
closeModal.addEventListener("click", function () {
shareModal.classList.remove("show");
setTimeout(() => {
shareModal.style.display = "none";
}, 300);
});
}
// Cerrar modal al hacer clic fuera
shareModal.addEventListener("click", function (e) {
if (e.target === shareModal) {
shareModal.classList.remove("show");
setTimeout(() => {
shareModal.style.display = "none";
}, 300);
}
});
// Configurar botones de redes sociales
configurarBotonesRedesSociales();
}
// Configurar botones de redes sociales
function configurarBotonesRedesSociales() {
const whatsappBtn = document.querySelector(".whatsapp");
const twitterBtn = document.querySelector(".twitter");
const facebookBtn = document.querySelector(".facebook");
const telegramBtn = document.querySelector(".telegram");
const downloadBtn = document.getElementById("downloadShareCard");
if (whatsappBtn) {
whatsappBtn.addEventListener("click", function () {
if (!consultaActual) return;
const mensaje = encodeURIComponent(
`Mi consulta del I Ching:\n` +
`Pregunta: ${consultaActual.pregunta}\n` +
`Hexagrama #${consultaActual.hexagramaId}: ${consultaActual.hexagramaNombre}\n` +
`Juicio: ${consultaActual.hexagrama.juicio}\n\n` +
`Más en: https://iching-librodemutaciones.web.app`
);
window.open(`https://wa.me/?text=${mensaje}`, "_blank");
});
}
if (twitterBtn) {
twitterBtn.addEventListener("click", function () {
if (!consultaActual) return;
const mensaje = encodeURIComponent(
`Mi consulta del I Ching:\n` +
`Pregunta: ${consultaActual.pregunta}\n` +
`Hexagrama #${consultaActual.hexagramaId}: ${consultaActual.hexagramaNombre}\n` +
`Juicio: ${consultaActual.hexagrama.juicio}\n\n` +
`Más en: https://iching-librodemutaciones.web.app #IChing #SabiduriaAncestral`
);
window.open(`https://twitter.com/intent/tweet?text=${mensaje}`, "_blank");
});
}
if (facebookBtn) {
facebookBtn.addEventListener("click", function () {
const url = encodeURIComponent(
"https://iching-librodemutaciones.web.app"
);
window.open(
`https://www.facebook.com/sharer/sharer.php?u=${url}`,
"_blank"
);
});
}
if (telegramBtn) {
telegramBtn.addEventListener("click", function () {
if (!consultaActual) return;
const mensaje = encodeURIComponent(
`Mi consulta del I Ching:\n` +
`Pregunta: ${consultaActual.pregunta}\n` +
`Hexagrama #${consultaActual.hexagramaId}: ${consultaActual.hexagramaNombre}\n` +
`Juicio: ${consultaActual.hexagrama.juicio}\n\n` +
`Más en: https://iching-librodemutaciones.web.app`
);
window.open(`https://t.me/share/url?url=${mensaje}`, "_blank");
});
}
if (downloadBtn) {
downloadBtn.addEventListener("click", function () {
descargarTarjetaComoImagen();
});
}
}
// Descargar la tarjeta como imagen
function descargarTarjetaComoImagen() {
const shareCard = document.getElementById("shareCard");
if (!shareCard) {
console.error("❌ Elemento shareCard no encontrado");
return;
}
const originalClasses = shareCard.className;
// Añadir clase para formato de imagen
shareCard.className = `${originalClasses} screenshot`;
// Usar html2canvas para capturar la imagen
html2canvas(shareCard, {
scale: 2,
backgroundColor: null,
logging: false,
useCORS: true,
allowTaint: true,
})
.then((canvas) => {
// Restaurar clases originales
shareCard.className = originalClasses;
// Crear enlace de descarga
const link = document.createElement("a");
link.download = `consulta-iching-${Date.now()}.png`;
link.href = canvas.toDataURL("image/png");
link.click();
})
.catch((error) => {
console.error("❌ Error al generar imagen:", error);
shareCard.className = originalClasses;
// Mostrar mensaje de error
alert(
"Hubo un error al generar la imagen. Por favor, intenta nuevamente."
);
});
}
// Configurar el botón de compartir
function configurarBotonCompartir() {
// Primera forma: usando delegación de eventos (más robusta)
document.body.addEventListener("click", function (e) {
const compartirBtn = e.target.closest("#compartirResultado");
if (compartirBtn) {
e.preventDefault();
console.log("🖱️ Botón de compartir clickeado");
// Verificar si hay consulta actual
if (!consultaActual) {
console.log("⚠️ No hay consulta actual para compartir");
mostrarMensajeError(
"Debes realizar una consulta primero antes de poder compartirla."
);
return;
}
// Mostrar el modal de compartir
mostrarModalCompartir();
}
});
// Segunda forma: por si el botón ya existe
const botonCompartir = document.getElementById("compartirResultado");
if (botonCompartir) {
botonCompartir.addEventListener("click", function (e) {
e.preventDefault();
console.log("🖱️ Botón de compartir clickeado (método directo)");
// Verificar si hay consulta actual
if (!consultaActual) {
console.log("⚠️ No hay consulta actual para compartir");
mostrarMensajeError(
"Debes realizar una consulta primero antes de poder compartirla."
);
return;
}
// Mostrar el modal de compartir
mostrarModalCompartir();
});
}
}
// Función para mostrar el modal de compartir
function mostrarModalCompartir() {
const shareModal = document.getElementById("shareModal");
if (!shareModal) {
console.error("❌ Modal de compartir no encontrado");
return;
}
// Actualizar la tarjeta con los datos de la consulta
actualizarTarjetaCompartir();
// Mostrar el modal
shareModal.style.display = "flex";
setTimeout(() => {
shareModal.classList.add("show");
}, 10);
}
// Función para actualizar la tarjeta de compartir
function actualizarTarjetaCompartir() {
if (!consultaActual) {
console.log("⚠️ No hay consulta actual para actualizar la tarjeta");
return;
}