-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfaq-admin.html
More file actions
814 lines (699 loc) · 35 KB
/
faq-admin.html
File metadata and controls
814 lines (699 loc) · 35 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
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sistema de FAQ Jerárquico - WidKit</title>
<meta name="description" content="Sistema de gestión de preguntas frecuentes con estructura jerárquica de nodos">
<script src="https://cdn.tailwindcss.com"></script>
<style>
.node-children {
margin-left: 2rem;
border-left: 2px solid #e2e8f0;
}
.collapse-arrow {
transition: transform 0.2s;
}
.collapse-arrow.open {
transform: rotate(90deg);
}
.search-highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body class="bg-slate-50 min-h-screen">
<!-- Navbar -->
<nav class="bg-white border-b border-slate-200 shadow-sm">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between items-center h-16">
<div class="flex items-center gap-3">
<div class="w-10 h-10 bg-gradient-to-br from-amber-500 to-orange-600 rounded-lg flex items-center justify-center p-2">
<img src="../../assets/widkit_fuego_icono.png" alt="WidKit" class="w-full h-full object-contain">
</div>
<h1 class="text-xl font-bold text-slate-900">FAQ Admin</h1>
</div>
<div class="flex gap-2">
<a href="../../app/faq.html" target="_blank" class="px-4 py-2 bg-amber-600 hover:bg-amber-700 text-white font-semibold rounded-lg transition">
👁️ Ver Público
</a>
<a href="../../index.html" class="px-4 py-2 text-slate-700 hover:bg-slate-100 rounded-lg transition">← Volver</a>
</div>
</div>
</div>
</nav>
<!-- Main Container -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Panel de Gestión (Izquierda) -->
<div class="lg:col-span-1">
<div class="bg-white rounded-xl shadow-lg p-6 sticky top-8">
<h2 class="text-2xl font-bold text-slate-900 mb-4">⚙️ Gestión</h2>
<!-- Búsqueda -->
<div class="mb-6">
<label class="block text-sm font-semibold text-slate-700 mb-2">🔍 Buscar</label>
<input type="text" id="searchInput"
class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent"
placeholder="Buscar por título o descripción...">
</div>
<!-- Botones de Acción -->
<div class="space-y-3">
<button onclick="showCreateModal()"
class="w-full px-4 py-3 bg-amber-600 hover:bg-amber-700 text-white font-semibold rounded-lg transition">
➕ Crear Nodo Raíz
</button>
<button onclick="exportJSON()"
class="w-full px-4 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition">
📥 Exportar JSON
</button>
<button onclick="importJSON()"
class="w-full px-4 py-3 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-lg transition">
📤 Importar JSON
</button>
<button onclick="resetToDefaults()"
class="w-full px-4 py-3 bg-red-600 hover:bg-red-700 text-white font-semibold rounded-lg transition">
🔄 Resetear a Predeterminado
</button>
</div>
<!-- Estadísticas -->
<div class="mt-6 p-4 bg-slate-100 rounded-lg">
<h3 class="font-bold text-slate-900 mb-2">📊 Estadísticas</h3>
<div class="space-y-1 text-sm text-slate-600">
<div>Total nodos: <span class="font-bold" id="totalNodes">0</span></div>
<div>Nodos raíz: <span class="font-bold" id="rootNodes">0</span></div>
<div>Profundidad máxima: <span class="font-bold" id="maxDepth">0</span></div>
</div>
</div>
<!-- Compartir / Embed -->
<div class="mt-6 p-4 bg-slate-100 rounded-lg">
<h3 class="font-bold text-slate-900 mb-2">🔗 Compartir</h3>
<div class="flex gap-2 mb-3">
<button onclick="generateShare()" class="px-3 py-2 bg-violet-600 hover:bg-violet-700 text-white text-sm font-semibold rounded-lg transition">Generar Enlace</button>
<button onclick="copyEmbed()" class="px-3 py-2 bg-slate-800 hover:bg-black text-white text-sm font-semibold rounded-lg transition">Copiar Iframe</button>
</div>
<textarea id="shareOutput" class="w-full text-xs p-2 border border-slate-300 rounded-lg" rows="3" readonly></textarea>
</div>
</div>
</div>
<!-- Vista del Árbol (Derecha) -->
<div class="lg:col-span-2">
<div class="bg-white rounded-xl shadow-lg p-6">
<div class="flex justify-between items-center mb-6">
<h2 class="text-2xl font-bold text-slate-900">📚 Árbol de FAQ</h2>
<button onclick="collapseAll()"
class="px-3 py-1 text-sm bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg transition">
🔽 Colapsar Todo
</button>
</div>
<div id="treeContainer" class="space-y-2">
<!-- Los nodos se renderizan aquí -->
</div>
</div>
</div>
</div>
</div>
<!-- Modal de Crear/Editar Nodo -->
<div id="nodeModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
<div class="bg-white rounded-xl shadow-2xl p-6 w-full max-w-md mx-4">
<h3 class="text-2xl font-bold text-slate-900 mb-4" id="modalTitle">Crear Nodo</h3>
<input type="hidden" id="nodeId">
<input type="hidden" id="parentId">
<div class="space-y-4">
<div>
<label class="block text-sm font-semibold text-slate-700 mb-2">Título *</label>
<input type="text" id="nodeTitle"
class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent"
placeholder="Ej: Becas">
<div id="titleError" class="text-red-600 text-xs mt-1 hidden"></div>
</div>
<div>
<label class="block text-sm font-semibold text-slate-700 mb-2">Descripción</label>
<textarea id="nodeDesc" rows="4"
class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent"
placeholder="Contenido de la respuesta..."></textarea>
</div>
<div id="parentInfo" class="p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-800">
<strong>Padre:</strong> <span id="parentTitle">Raíz</span>
</div>
<div class="flex gap-3">
<button onclick="saveNode()"
class="flex-1 px-4 py-3 bg-amber-600 hover:bg-amber-700 text-white font-semibold rounded-lg transition">
💾 Guardar
</button>
<button onclick="closeModal()"
class="flex-1 px-4 py-3 bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold rounded-lg transition">
Cancelar
</button>
</div>
</div>
</div>
</div>
<!-- Modal de Confirmación -->
<div id="confirmModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
<div class="bg-white rounded-xl shadow-2xl p-6 w-full max-w-md mx-4">
<h3 class="text-2xl font-bold text-slate-900 mb-4">⚠️ Confirmar</h3>
<p class="text-slate-600 mb-6" id="confirmMessage"></p>
<div class="flex gap-3">
<button onclick="confirmAction()"
class="flex-1 px-4 py-3 bg-red-600 hover:bg-red-700 text-white font-semibold rounded-lg transition">
Confirmar
</button>
<button onclick="cancelConfirm()"
class="flex-1 px-4 py-3 bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold rounded-lg transition">
Cancelar
</button>
</div>
</div>
</div>
<!-- Input oculto para importar JSON -->
<input type="file" id="jsonFileInput" accept=".json" style="display: none;" onchange="handleFileImport(event)">
<script>
// ============================================
// MODELO DE DATOS Y STORAGE
// ============================================
class Nodo {
constructor(id, titulo, descripcion, id_nodo_padre = null, orden = 0) {
this.id_nodo = id;
this.titulo = titulo;
this.descripcion = descripcion || '';
this.id_nodo_padre = id_nodo_padre;
this.orden = orden || 0;
this.hijos = [];
}
// Añade un hijo al nodo
agregarHijo(nodo) {
this.hijos.push(nodo);
}
// Verifica si tiene hijos
tieneHijos() {
return this.hijos.length > 0;
}
}
class FAQSystem {
constructor() {
this.nodos = [];
this.nextId = 1;
this.loadFromStorage();
this.searchTerm = '';
this.pendingAction = null;
}
// Guarda en localStorage
saveToStorage() {
localStorage.setItem('faq_nodos', JSON.stringify(this.nodos));
localStorage.setItem('faq_next_id', JSON.stringify(this.nextId));
}
// Carga desde localStorage
loadFromStorage() {
const savedNodos = localStorage.getItem('faq_nodos');
const savedNextId = localStorage.getItem('faq_next_id');
if (savedNodos) {
this.nodos = JSON.parse(savedNodos);
} else {
this.initDefaultData();
}
if (savedNextId) {
this.nextId = parseInt(savedNextId);
} else {
this.nextId = 1;
// Calcular el siguiente ID desde los nodos existentes
if (this.nodos.length > 0) {
const maxId = Math.max(...this.nodos.map(n => n.id_nodo));
this.nextId = maxId + 1;
}
}
}
// Datos predeterminados
initDefaultData() {
const nodos = [
{ id_nodo: 1, titulo: 'Becas', descripcion: 'Información general sobre becas disponibles', id_nodo_padre: null, orden: 0 },
{ id_nodo: 2, titulo: 'Tipo de becas', descripcion: 'Tipos de becas según perfil del estudiante', id_nodo_padre: 1, orden: 0 },
{ id_nodo: 3, titulo: 'Gratuidad', descripcion: 'La gratuidad cubre el arancel de la carrera completa.', id_nodo_padre: 2, orden: 0 },
{ id_nodo: 4, titulo: 'Postulación', descripcion: 'Puedes postular a las becas a través del portal Mineduc.cl', id_nodo_padre: 1, orden: 1 },
{ id_nodo: 5, titulo: 'Cómo pagar la mensualidad', descripcion: 'Puedes pagar en línea o en las cajas del campus.', id_nodo_padre: null, orden: 1 }
];
this.nodos = nodos;
this.nextId = 6;
this.saveToStorage();
}
// Obtiene todos los nodos raíz
getRootNodes() {
return this.nodos.filter(n => n.id_nodo_padre === null);
}
// Obtiene un nodo por ID
getNodoById(id) {
return this.nodos.find(n => n.id_nodo === id);
}
// Obtiene hijos de un nodo
getHijos(id_padre) {
return this.nodos.filter(n => n.id_nodo_padre === id_padre);
}
// Crea un nodo
crearNodo(titulo, descripcion, id_nodo_padre) {
// Validar que el título sea único en el mismo nivel
if (this.tituloExisteEnNivel(titulo, id_nodo_padre)) {
return { success: false, error: 'Ya existe un nodo con este título en el mismo nivel' };
}
const nuevoNodo = {
id_nodo: this.nextId++,
titulo: titulo.trim(),
descripcion: descripcion.trim(),
id_nodo_padre: id_nodo_padre,
orden: 0
};
this.nodos.push(nuevoNodo);
this.saveToStorage();
return { success: true, nodo: nuevoNodo };
}
// Edita un nodo
editarNodo(id, titulo, descripcion) {
const nodo = this.getNodoById(id);
if (!nodo) return { success: false, error: 'Nodo no encontrado' };
// Validar que el título sea único en el mismo nivel (excepto el mismo nodo)
if (this.tituloExisteEnNivel(titulo, nodo.id_nodo_padre, id)) {
return { success: false, error: 'Ya existe un nodo con este título en el mismo nivel' };
}
nodo.titulo = titulo.trim();
nodo.descripcion = descripcion.trim();
this.saveToStorage();
return { success: true };
}
// Elimina un nodo
eliminarNodo(id) {
// Verificar si tiene hijos
if (this.getHijos(id).length > 0) {
return { success: false, error: 'No se puede eliminar un nodo que tiene hijos' };
}
this.nodos = this.nodos.filter(n => n.id_nodo !== id);
this.saveToStorage();
return { success: true };
}
// Verifica si un título existe en el mismo nivel
tituloExisteEnNivel(titulo, id_nodo_padre, excludeId = null) {
return this.nodos.some(n =>
n.titulo.toLowerCase() === titulo.toLowerCase() &&
n.id_nodo_padre === id_nodo_padre &&
n.id_nodo !== excludeId
);
}
// Construye el árbol jerárquico recursivamente
construirArbol(nodos = null, padreId = null) {
if (!nodos) nodos = this.nodos;
if (padreId === undefined) padreId = null;
const hijosDirectos = nodos.filter(n => n.id_nodo_padre === padreId)
.sort((a, b) => a.orden - b.orden);
const arbol = hijosDirectos.map(nodo => {
const nodoConHijos = { ...nodo };
nodoConHijos.hijos = this.construirArbol(nodos, nodo.id_nodo);
return nodoConHijos;
});
return arbol;
}
// Búsqueda por palabra clave
buscar(keyword) {
if (!keyword || keyword.trim() === '') return this.construirArbol();
this.searchTerm = keyword.toLowerCase();
const keywordLower = keyword.toLowerCase();
const resultados = this.nodos.filter(n =>
n.titulo.toLowerCase().includes(keywordLower) ||
n.descripcion.toLowerCase().includes(keywordLower)
);
// Construir árbol parcial solo con resultados y sus ancestros
const nodosIncluir = new Set();
resultados.forEach(n => {
nodosIncluir.add(n.id_nodo);
// Incluir ancestros
let parentId = n.id_nodo_padre;
while (parentId !== null) {
nodosIncluir.add(parentId);
const parent = this.getNodoById(parentId);
parentId = parent ? parent.id_nodo_padre : null;
}
});
const nodosFiltrados = this.nodos.filter(n => nodosIncluir.has(n.id_nodo));
return this.construirArbol(nodosFiltrados, null);
}
// Calcula estadísticas
getStats() {
const total = this.nodos.length;
const root = this.getRootNodes().length;
// Calcular profundidad máxima
const maxDepth = this.calcularProfundidadMaxima();
return { total, root, maxDepth };
}
calcularProfundidadMaxima() {
const profundidades = {};
const calcularProfundidad = (id) => {
if (profundidades[id] !== undefined) {
return profundidades[id];
}
const nodo = this.getNodoById(id);
if (!nodo || nodo.id_nodo_padre === null) {
profundidades[id] = 0;
return 0;
}
profundidades[id] = calcularProfundidad(nodo.id_nodo_padre) + 1;
return profundidades[id];
};
this.nodos.forEach(n => {
calcularProfundidad(n.id_nodo);
});
return Math.max(...Object.values(profundidades), 0);
}
}
// ============================================
// INSTANCIA GLOBAL
// ============================================
const faqSystem = new FAQSystem();
// ============================================
// FUNCIONES DE UI
// ============================================
function renderTree() {
const treeContainer = document.getElementById('treeContainer');
let arbol;
if (faqSystem.searchTerm && faqSystem.searchTerm.trim() !== '') {
arbol = faqSystem.buscar(faqSystem.searchTerm);
} else {
arbol = faqSystem.construirArbol();
}
treeContainer.innerHTML = '';
if (arbol.length === 0) {
treeContainer.innerHTML = '<p class="text-slate-500 text-center py-8">No se encontraron nodos</p>';
return;
}
arbol.forEach(nodo => {
treeContainer.appendChild(renderNode(nodo, 0));
});
updateStats();
}
function renderNode(nodo, nivel) {
const hasChildren = nodo.hijos && nodo.hijos.length > 0;
const div = document.createElement('div');
div.className = 'mb-2';
const indent = nivel * 2;
const isExpanded = localStorage.getItem(`faq_expanded_${nodo.id_nodo}`) !== 'false';
div.innerHTML = `
<div class="flex items-start gap-2 bg-slate-50 hover:bg-slate-100 p-3 rounded-lg transition">
<div style="margin-left: ${indent}rem;" class="flex items-start gap-2 flex-1">
${hasChildren ? `
<button onclick="toggleNode(${nodo.id_nodo})"
class="collapse-arrow ${isExpanded ? 'open' : ''} mt-1 text-slate-400 hover:text-slate-600">
▶
</button>
` : '<span class="w-4"></span>'}
<div class="flex-1">
<div class="font-bold text-slate-900 mb-1" id="node-title-${nodo.id_nodo}">${highlightSearch(nodo.titulo)}</div>
${nodo.descripcion ? `<div class="text-sm text-slate-600" id="node-desc-${nodo.id_nodo}">${highlightSearch(nodo.descripcion)}</div>` : ''}
</div>
<div class="flex gap-1">
<button onclick="showEditModal(${nodo.id_nodo})"
class="px-2 py-1 text-xs bg-blue-100 hover:bg-blue-200 text-blue-700 rounded">
✏️
</button>
<button onclick="showDeleteConfirm(${nodo.id_nodo})"
class="px-2 py-1 text-xs bg-red-100 hover:bg-red-200 text-red-700 rounded">
🗑️
</button>
<button onclick="showCreateChildModal(${nodo.id_nodo})"
class="px-2 py-1 text-xs bg-green-100 hover:bg-green-200 text-green-700 rounded">
➕
</button>
</div>
</div>
</div>
${hasChildren ? `
<div id="children-${nodo.id_nodo}" class="node-children ${isExpanded ? '' : 'hidden'}">
${nodo.hijos.map(hijo => renderNode(hijo, nivel + 1).outerHTML).join('')}
</div>
` : ''}
`;
return div;
}
function highlightSearch(text) {
if (!faqSystem.searchTerm) return text;
const regex = new RegExp(`(${faqSystem.searchTerm})`, 'gi');
return text.replace(regex, '<span class="search-highlight">$1</span>');
}
function toggleNode(id) {
const childrenDiv = document.getElementById(`children-${id}`);
const button = document.querySelector(`button[onclick="toggleNode(${id})"]`);
if (childrenDiv) {
childrenDiv.classList.toggle('hidden');
button.classList.toggle('open');
localStorage.setItem(`faq_expanded_${id}`, !childrenDiv.classList.contains('hidden'));
}
}
function collapseAll() {
faqSystem.nodos.forEach(n => {
localStorage.setItem(`faq_expanded_${n.id_nodo}`, 'false');
});
renderTree();
}
function updateStats() {
const stats = faqSystem.getStats();
document.getElementById('totalNodes').textContent = stats.total;
document.getElementById('rootNodes').textContent = stats.root;
document.getElementById('maxDepth').textContent = stats.maxDepth;
}
// ============================================
// MODALES
// ============================================
let currentNodeId = null;
let currentParentId = null;
function showCreateModal() {
currentNodeId = null;
currentParentId = null;
document.getElementById('modalTitle').textContent = 'Crear Nodo Raíz';
document.getElementById('nodeTitle').value = '';
document.getElementById('nodeDesc').value = '';
document.getElementById('nodeId').value = '';
document.getElementById('parentId').value = '';
document.getElementById('parentTitle').textContent = 'Raíz';
document.getElementById('titleError').classList.add('hidden');
document.getElementById('nodeModal').classList.remove('hidden');
document.getElementById('nodeModal').classList.add('flex');
document.getElementById('nodeTitle').focus();
}
function showCreateChildModal(parentId) {
currentNodeId = null;
currentParentId = parentId;
const parent = faqSystem.getNodoById(parentId);
document.getElementById('modalTitle').textContent = 'Crear Nodo Hijo';
document.getElementById('nodeTitle').value = '';
document.getElementById('nodeDesc').value = '';
document.getElementById('nodeId').value = '';
document.getElementById('parentId').value = parentId;
document.getElementById('parentTitle').textContent = parent.titulo;
document.getElementById('titleError').classList.add('hidden');
document.getElementById('nodeModal').classList.remove('hidden');
document.getElementById('nodeModal').classList.add('flex');
document.getElementById('nodeTitle').focus();
}
function showEditModal(id) {
currentNodeId = id;
const nodo = faqSystem.getNodoById(id);
if (!nodo) return;
currentParentId = nodo.id_nodo_padre;
const parentTitle = nodo.id_nodo_padre ?
faqSystem.getNodoById(nodo.id_nodo_padre).titulo : 'Raíz';
document.getElementById('modalTitle').textContent = 'Editar Nodo';
document.getElementById('nodeTitle').value = nodo.titulo;
document.getElementById('nodeDesc').value = nodo.descripcion || '';
document.getElementById('nodeId').value = id;
document.getElementById('parentId').value = nodo.id_nodo_padre || '';
document.getElementById('parentTitle').textContent = parentTitle;
document.getElementById('titleError').classList.add('hidden');
document.getElementById('nodeModal').classList.remove('hidden');
document.getElementById('nodeModal').classList.add('flex');
document.getElementById('nodeTitle').focus();
}
function closeModal() {
document.getElementById('nodeModal').classList.add('hidden');
document.getElementById('nodeModal').classList.remove('flex');
}
function saveNode() {
const titulo = document.getElementById('nodeTitle').value.trim();
const descripcion = document.getElementById('nodeDesc').value.trim();
const id = parseInt(document.getElementById('nodeId').value);
const parentId = currentParentId;
if (!titulo) {
document.getElementById('titleError').textContent = 'El título es obligatorio';
document.getElementById('titleError').classList.remove('hidden');
return;
}
let resultado;
if (id) {
// Editar
resultado = faqSystem.editarNodo(id, titulo, descripcion);
} else {
// Crear
resultado = faqSystem.crearNodo(titulo, descripcion, parentId);
}
if (!resultado.success) {
document.getElementById('titleError').textContent = resultado.error;
document.getElementById('titleError').classList.remove('hidden');
return;
}
closeModal();
renderTree();
}
function showDeleteConfirm(id) {
const nodo = faqSystem.getNodoById(id);
if (!nodo) return;
currentNodeId = id;
document.getElementById('confirmMessage').textContent =
`¿Estás seguro de eliminar el nodo "${nodo.titulo}"?`;
faqSystem.pendingAction = () => {
const resultado = faqSystem.eliminarNodo(id);
if (resultado.success) {
renderTree();
} else {
alert(resultado.error);
}
cancelConfirm();
};
document.getElementById('confirmModal').classList.remove('hidden');
document.getElementById('confirmModal').classList.add('flex');
}
function confirmAction() {
if (faqSystem.pendingAction) {
faqSystem.pendingAction();
}
}
function cancelConfirm() {
document.getElementById('confirmModal').classList.add('hidden');
document.getElementById('confirmModal').classList.remove('flex');
faqSystem.pendingAction = null;
}
// ============================================
// BÚSQUEDA
// ============================================
document.getElementById('searchInput').addEventListener('input', (e) => {
faqSystem.searchTerm = e.target.value;
renderTree();
});
// ============================================
// EXPORT/IMPORT
// ============================================
function exportJSON() {
// Exportar como array plano de nodos (no árbol anidado) para compatibilidad
const json = JSON.stringify(faqSystem.nodos, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'faq-export.json';
a.click();
URL.revokeObjectURL(url);
}
function importJSON() {
document.getElementById('jsonFileInput').click();
}
function handleFileImport(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
try {
const json = JSON.parse(e.target.result);
let nodosImportados = [];
// Manejar ambos formatos: array plano o árbol anidado
if (Array.isArray(json)) {
// Si es un array, verificar si son nodos planos o árbol anidado
if (json.length > 0 && json[0].hijos !== undefined) {
// Es un árbol anidado, convertir a array plano
nodosImportados = flattenTree(json);
} else {
// Es un array plano de nodos
nodosImportados = json;
}
} else {
throw new Error('El formato del JSON no es válido');
}
if (confirm('¿Importar datos? Esto sobrescribirá los datos actuales.')) {
faqSystem.nodos = nodosImportados;
faqSystem.nextId = 1;
if (faqSystem.nodos.length > 0) {
const maxId = Math.max(...faqSystem.nodos.map(n => n.id_nodo));
faqSystem.nextId = maxId + 1;
}
faqSystem.saveToStorage();
renderTree();
}
} catch (error) {
alert('Error al importar JSON: ' + error.message);
}
};
reader.readAsText(file);
event.target.value = '';
}
// Función auxiliar para convertir árbol anidado a array plano
function flattenTree(arbol, result = []) {
for (const nodo of arbol) {
// Crear copia del nodo sin la propiedad hijos
const { hijos, ...nodoPlano } = nodo;
result.push(nodoPlano);
// Si tiene hijos, procesarlos recursivamente
if (hijos && hijos.length > 0) {
flattenTree(hijos, result);
}
}
return result;
}
function resetToDefaults() {
if (confirm('¿Restablecer a los datos predeterminados? Esto eliminará todos los nodos actuales.')) {
faqSystem.initDefaultData();
renderTree();
}
}
// ============================================
// COMPARTIR / EMBED (URL PARAM)
// ============================================
// Nota: La función encodeTreeForParam está definida arriba junto con generateShare()
function generateShare() {
// Usar array plano de nodos (no árbol anidado) para compatibilidad con app/faq.html
const nodos = faqSystem.nodos;
const encoded = encodeTreeForParam(nodos);
if (!encoded) return;
// Construir URL hacia app/faq.html desde la ubicación actual
const currentUrl = new URL(window.location.href);
// Subir un nivel desde admin/ y entrar a app/
const faqUrl = new URL('../app/faq.html', currentUrl);
faqUrl.searchParams.set('faq', encoded);
document.getElementById('shareOutput').value = faqUrl.toString();
}
// Renombrar función para mayor claridad (aunque el nombre sigue siendo válido)
function encodeTreeForParam(data) {
try {
const json = JSON.stringify(data);
// Base64 URL-safe
const b64 = btoa(unescape(encodeURIComponent(json)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/,'');
return b64;
} catch (e) {
alert('Error al codificar: ' + e.message);
return '';
}
}
function copyEmbed() {
let link = document.getElementById('shareOutput').value.trim();
if (!link) {
generateShare();
link = document.getElementById('shareOutput').value.trim();
}
if (!link) return;
const iframe = `<iframe src="${link}" width="100%" height="600" frameborder="0" loading="lazy"></iframe>`;
document.getElementById('shareOutput').value = iframe;
navigator.clipboard.writeText(iframe).then(() => {
alert('Iframe copiado al portapapeles');
}).catch(() => {});
}
// ============================================
// INICIALIZACIÓN
// ============================================
document.addEventListener('DOMContentLoaded', () => {
renderTree();
});
</script>
</body>
</html>