-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
712 lines (617 loc) · 30.9 KB
/
Copy pathscript.js
File metadata and controls
712 lines (617 loc) · 30.9 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
// 1. INICIALIZACIÓN SUPABASE (FIX SINTAXIS)
const _supabaseUrl = 'https://dgldvmceeqjlygojpqzx.supabase.co';
const _supabaseKey = 'sb_publishable_hZyM1KCgrJac8HVtrsROQg_yB_6V0BC';
const supabaseClient = window.supabase.createClient(_supabaseUrl, _supabaseKey);
// 2. BASE DE DATOS MAESTRA (24 PRODUCTOS CON SPECS)
const products = [
// --- HARDWARE ---
{ id: 'h1', nombre: 'NVIDIA GeForce RTX 5070 Ti', precio: 4850000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773617071/81-U0K9a7mL._AC_SX466__aii7od.jpg', cat: 'hardware', specs: { vram: '16GB GDDR7', arquitectura: 'Blackwell', watts: '285W' } },
{ id: 'h2', nombre: 'NVIDIA GeForce GT 730', precio: 350000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773617065/71zKqU8xrML._AC_UY218__mhwbeu.jpg', cat: 'hardware', specs: { vram: '2GB DDR3', arquitectura: 'Kepler', watts: '38W' } },
{ id: 'h3', nombre: 'Fanxiang 64GB RAM DDR5', precio: 1250000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773617061/71qMNPhYlCL._AC_SY300_SX300_QL70_FMwebp__w6thgu.webp', cat: 'hardware', specs: { capacidad: '64GB (2x32)', velocidad: '6000 MT/s', formato: 'DDR5' } },
{ id: 'h4', nombre: 'Radeon RX 9060 Graphics', precio: 3150000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773616926/71L08TQedJL._AC_SY300_SX300_QL70_FMwebp__chkqqx.webp', cat: 'hardware', specs: { vram: '12GB GDDR6', arquitectura: 'RDNA 4', watts: '225W' } },
{ id: 'h5', nombre: 'AMD Ryzen 7 Processor', precio: 1850000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773616920/71aHvYUgX1L._AC_UY218__s5mrg6.jpg', cat: 'hardware', specs: { nucleos: '8 Cores', arquitectura: 'Zen 4', watts: '105W' } },
{ id: 'h6', nombre: 'G.Skill Trident Z RGB RAM', precio: 750000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773616918/61l4EStxhnL._AC_UY218__pgruby.jpg', cat: 'hardware', specs: { capacidad: '32GB (2x16)', velocidad: '6400 MT/s', formato: 'DDR5' } },
{ id: 'h7', nombre: 'Intel Core i7 Processor', precio: 1650000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773616915/51gf0NAUHkL._AC_UY218__aifutv.jpg', cat: 'hardware', specs: { nucleos: '20 Cores', arquitectura: 'Raptor Lake', watts: '125W' } },
{ id: 'h8', nombre: 'Gigastone Desktop RAM', precio: 420000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773616911/510V6PbPGrL._AC_UY218__mw6cbz.jpg', cat: 'hardware', specs: { capacidad: '16GB', velocidad: '3200 MHz', formato: 'DDR4' } },
// --- MÓVILES ---
{ id: 'm1', nombre: 'Samsung Galaxy S24 Ultra', precio: 5400000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624699/descarga_uookmj.jpg', cat: 'moviles', specs: { pantalla: '6.8" AMOLED 120Hz', chip: 'Snapdragon 8 Gen 3', camara: '200MP + 50MP + 12MP' } },
{ id: 'm2', nombre: 'iPhone 15 Pro Max', precio: 5200000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624696/descarga_7_xemgdc.jpg', cat: 'moviles', specs: { pantalla: '6.7" Super Retina XDR', chip: 'A17 Pro Bionic', camara: '48MP + 12MP + 12MP' } },
{ id: 'm3', nombre: 'Motorola Edge 50 Pro', precio: 2900000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624695/descarga_6_sygzsl.jpg', cat: 'moviles', specs: { pantalla: '6.7" pOLED 144Hz', chip: 'Snapdragon 7 Gen 3', camara: '50MP + 13MP + 10MP' } },
{ id: 'm4', nombre: 'Asus ROG Phone 8', precio: 4500000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624691/descarga_4_jiyvqw.jpg', cat: 'moviles', specs: { pantalla: '6.78" LTPO 165Hz', chip: 'Snapdragon 8 Gen 3', camara: '50MP + 32MP + 13MP' } },
{ id: 'm5', nombre: 'Xiaomi 14 Ultra', precio: 4800000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624687/descarga_2_q6ovv0.jpg', cat: 'moviles', specs: { pantalla: '6.73" LTPO AMOLED', chip: 'Snapdragon 8 Gen 3', camara: '50MP Quad Leica' } },
// --- PC Y PERIFÉRICOS ---
{ id: 'p1', nombre: 'PC Gamer Ultimate Setup', precio: 8500000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624652/descarga_1_f8b7c1.jpg', cat: 'perifericos', specs: { cpu: 'Intel i9-14900KF', gpu: 'NVIDIA RTX 4090', ram: '128GB DDR5' } },
{ id: 'p2', nombre: 'Asus ROG Strix Desktop', precio: 7900000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624652/descarga_14_wozrvq.jpg', cat: 'perifericos', specs: { cpu: 'AMD Ryzen 9 7950X', gpu: 'NVIDIA RTX 4080', ram: '64GB DDR5' } },
{ id: 'p3', nombre: 'PC Gamer MSI Aegis', precio: 9200000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624653/descarga_2_w8qegt.jpg', cat: 'perifericos', specs: { cpu: 'Intel i7-14700K', gpu: 'NVIDIA RTX 4070 Ti', ram: '32GB DDR5' } },
{ id: 'p4', nombre: 'Micrófono Shure MV7', precio: 1050000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624653/descarga_3_naqmhu.jpg', cat: 'perifericos', specs: {} },
{ id: 'p5', nombre: 'Audífonos HyperX Cloud II', precio: 650000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624659/descarga_5_kdy3bx.jpg', cat: 'perifericos', specs: {} },
{ id: 'p6', nombre: 'Mouse Logitech G502 Hero', precio: 450000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624661/descarga_6_dvizcg.jpg', cat: 'perifericos', specs: {} },
{ id: 'p7', nombre: 'Teclado Razer BlackWidow V4', precio: 3200000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624661/descarga_7_yl2ey6.jpg', cat: 'perifericos', specs: {} },
{ id: 'p8', nombre: 'Monitor Samsung Odyssey G7', precio: 1800000, img: 'https://res.cloudinary.com/dkctv9kqz/image/upload/v1773624662/descarga_g0hlmb.jpg', cat: 'perifericos', specs: {} }
];
// 3. ESTADO GLOBAL
let cart = JSON.parse(localStorage.getItem('sf_cart_master_final')) || [];
let comparisonList = JSON.parse(localStorage.getItem('sf_comparison_list')) || [];
// 4. LÓGICA DE REGISTRO
async function ejecutarRegistro() {
const email = document.getElementById('reg-email').value;
const password = document.getElementById('reg-password').value;
if (!email || !password) return showToast("Campos vacíos.");
const { error } = await supabaseClient.auth.signUp({
email, password, options: { emailRedirectTo: null }
});
if (error) {
showToast("Denegado: " + error.message);
} else {
document.getElementById('modal-verification').style.display = 'flex';
}
}
// 5. FUNCIÓN DE LOGIN
async function ejecutarLogin() {
const email = document.getElementById('log-email').value;
const password = document.getElementById('log-password').value;
// --- ADMIN BYPASS LOGIC (PRIORIDAD ABSOLUTA) ---
if (email === 'admin@gmail.com' && password === 'admin') {
const adminSession = { email: 'admin@gmail.com', role: 'admin', isAuthenticated: true };
localStorage.setItem('specflow_session', JSON.stringify(adminSession));
showToast("ACCESO MAESTRO DETECTADO");
unlockApp();
return; // Fin de ejecución para admin
}
// Validación de Bloqueo (Solo usuarios estándar)
const { data: userProfile } = await supabaseClient.from('perfiles').select('estado').eq('email', email).single();
if (userProfile && userProfile.estado === 'bloqueado') {
showToast("CUENTA BLOQUEADA: ACCESO REVOCADO");
return;
}
const { data, error } = await supabaseClient.auth.signInWithPassword({ email, password });
if (error) {
showToast("Fallo de Acceso: " + error.message);
return;
}
if (data.user) {
// Excepción Admin: Bypass de verificación de correo
if (email !== 'admin@gmail.com' && !data.user.email_confirmed_at) {
await supabaseClient.auth.signOut();
showToast("VERIFICA TU CORREO PARA ENTRAR");
document.getElementById('modal-verification').style.display = 'flex';
return;
}
const userSession = { email: data.user.email, role: 'user', isAuthenticated: true };
localStorage.setItem('specflow_session', JSON.stringify(userSession));
unlockApp();
}
}
// 6. CONTROLADORES UI / SPA
function lockApp() {
document.getElementById('modal-auth').style.display = 'flex';
document.getElementById('app-content').style.display = 'none';
}
function unlockApp() {
document.getElementById('modal-auth').style.display = 'none';
document.getElementById('app-content').style.display = 'block';
// Verificar sesión admin local
const session = JSON.parse(localStorage.getItem('specflow_session'));
const isAdmin = session && session.role === 'admin';
const adminBtn = document.getElementById('btn-admin-panel');
if (adminBtn) adminBtn.style.display = isAdmin ? 'inline-block' : 'none';
navigateTo('hero');
renderAllCatalogs();
updateCartVisuals();
}
function toggleAuth(type) {
const isReg = type === 'register';
const title = document.getElementById('auth-main-title');
const subtitle = document.getElementById('auth-toggle-subtitle');
document.getElementById('register-panel').style.display = isReg ? 'block' : 'none';
document.getElementById('login-panel').style.display = isReg ? 'none' : 'block';
if (isReg) {
title.innerText = "REGISTRARSE";
subtitle.innerText = "YA TENGO CUENTA";
subtitle.onclick = () => toggleAuth('login');
} else {
title.innerText = "INICIAR SESIÓN";
subtitle.innerText = "REGISTRARSE";
subtitle.onclick = () => toggleAuth('register');
}
}
function navigateTo(id) {
// Escondemos todas las secciones principales
document.querySelectorAll('main section').forEach(s => {
s.classList.remove('active');
s.style.display = 'none'; // Aseguramos limpieza total
});
const target = document.getElementById(`${id}-section`);
const hero = document.getElementById('hero-section');
const isHero = id === 'hero';
if (target) {
target.classList.add('active');
target.style.display = isHero ? 'flex' : 'block';
}
// El Hero solo se muestra en el Home
if (hero) {
hero.style.display = isHero ? 'flex' : 'none';
if (isHero) hero.classList.add('active');
}
// Manejo de padding para impacto 100vh o contenido denso
const appContent = document.getElementById('app-content');
if (isHero) {
appContent.style.paddingTop = '0';
} else {
appContent.style.paddingTop = '100px';
}
if (id === 'comparator') renderComparisonSection();
window.scrollTo({ top: 0, behavior: 'smooth' });
}
function renderAllCatalogs() {
['hardware', 'moviles', 'perifericos'].forEach(cat => {
const grid = document.getElementById(`${cat}-grid`);
if (!grid) return;
const items = products.filter(p => p.cat === cat);
grid.innerHTML = items.map(p => {
let specHtml = '';
// LÓGICA DE VISUALIZACIÓN POR CATEGORÍA
if (cat === 'moviles') {
specHtml = `
<div class="mobile-specs">
<div class="spec-item"><span class="spec-label">PANTALLA:</span> ${p.specs.pantalla}</div>
<div class="spec-item"><span class="spec-label">CHIP:</span> ${p.specs.chip}</div>
<div class="spec-item"><span class="spec-label">CÁMARA:</span> ${p.specs.camara}</div>
</div>
`;
} else if (cat === 'hardware') {
specHtml = `
<div class="mobile-specs">
<div class="spec-item"><span class="spec-label">VRAM / CAPACIDAD:</span> ${p.specs.vram || p.specs.capacidad}</div>
<div class="spec-item"><span class="spec-label">ARQUITECTURA / VELOCIDAD:</span> ${p.specs.arquitectura || p.specs.velocidad}</div>
<div class="spec-item"><span class="spec-label">WATTS / FORMATO:</span> ${p.specs.watts || p.specs.formato}</div>
</div>
`;
} else if (cat === 'perifericos' && (p.id === 'p1' || p.id === 'p2' || p.id === 'p3')) {
specHtml = `
<div class="mobile-specs">
<div class="spec-item"><span class="spec-label">PROCESADOR:</span> ${p.specs.cpu}</div>
<div class="spec-item"><span class="spec-label">GRÁFICA:</span> ${p.specs.gpu}</div>
<div class="spec-item"><span class="spec-label">RAM:</span> ${p.specs.ram}</div>
</div>
`;
}
return `
<div class="product-card">
<div class="img-container">
<img src="${p.img}" alt="${p.nombre}">
</div>
<h3>${p.nombre}</h3>
${specHtml}
<div class="price">$${p.precio.toLocaleString()}</div>
<div class="card-actions" style="display: flex; gap: 0.5rem; margin-top: 1rem;">
<button class="btn-cyber" style="padding: 0.8rem; font-size: 0.75rem; flex: 1;" onclick="addToCompare('${p.id}')">COMPARAR</button>
<button class="btn-cyber" style="padding: 0.8rem; font-size: 0.75rem; flex: 1; background: var(--neon-aqua); color: #000;" onclick="addToCart('${p.id}')">COMPRAR</button>
</div>
</div>
`;
}).join('');
});
renderComparisonSection();
}
function renderComparisonSection() {
const section = document.getElementById('comparator-section');
if (!section) return;
for (let i = 0; i < 2; i++) {
const slot = document.getElementById(`slot-${i}`);
if (!slot) continue;
const p = comparisonList[i];
if (p) {
slot.innerHTML = `
<div class="slot-info">
<button class="remove-btn" title="Quitar producto" onclick="removeFromCompare(${i})">
<i class="fas fa-trash-alt"></i>
</button>
<img src="${p.img}" alt="${p.nombre}">
<h4>${p.nombre}</h4>
</div>
`;
slot.classList.add('has-product');
} else {
slot.innerHTML = `
<div class="slot-placeholder">
<div class="scan-line"></div>
<i class="fas fa-plus pulse-icon"></i>
</div>
`;
slot.classList.remove('has-product');
}
}
}
function addToCompare(pid) {
if (comparisonList.length >= 2) {
return showToast("Solo puedes comparar 2 productos. Elimina uno para continuar.");
}
if (comparisonList.some(item => item.id === pid)) {
return showToast("Este producto ya está en el centro de análisis.");
}
const p = products.find(x => x.id === pid);
comparisonList.push(p);
localStorage.setItem('sf_comparison_list', JSON.stringify(comparisonList));
renderComparisonSection();
navigateTo('comparator');
showToast(`Elemento añadido al análisis: ${p.nombre}`);
}
function removeFromCompare(index) {
comparisonList.splice(index, 1);
localStorage.setItem('sf_comparison_list', JSON.stringify(comparisonList));
renderComparisonSection();
}
function startAnalysis() {
if (comparisonList.length < 2) return showToast("Por favor selecciona 2 productos.");
const p1 = comparisonList[0];
const p2 = comparisonList[1];
const container = document.getElementById('analysis-table-container');
// Puntuaciones ficticias basadas en el precio/tipo
const score1 = Math.floor(82 + (p1.precio / 1000000) * 2.5);
const score2 = Math.floor(82 + (p2.precio / 1000000) * 2.5);
// Mapeo inteligente de specs técnicas
const getSpec = (p, keys) => {
for (let k of keys) {
if (p.specs[k]) return p.specs[k];
}
return "N/A / Ver detalles";
};
container.innerHTML = `
<table class="analysis-table">
<thead>
<tr>
<th>ATRIBUTO TÉCNICO</th>
<td><img src="${p1.img}"><br><strong style="color: var(--neon-aqua);">${p1.nombre}</strong></td>
<td><img src="${p2.img}"><br><strong style="color: var(--neon-aqua);">${p2.nombre}</strong></td>
</tr>
</thead>
<tbody>
<tr>
<th>PROCESAMIENTO / CORE</th>
<td>${getSpec(p1, ['cpu', 'chip', 'nucleos'])}</td>
<td>${getSpec(p2, ['cpu', 'chip', 'nucleos'])}</td>
</tr>
<tr>
<th>MEMORIA / VOLUMEN</th>
<td>${getSpec(p1, ['ram', 'memoria', 'capacidad'])}</td>
<td>${getSpec(p2, ['ram', 'memoria', 'capacidad'])}</td>
</tr>
<tr>
<th>INTERFAZ / VISUAL</th>
<td>${getSpec(p1, ['gpu', 'pantalla', 'panel', 'camara'])}</td>
<td>${getSpec(p2, ['gpu', 'pantalla', 'panel', 'camara'])}</td>
</tr>
<tr>
<th>ENERGÍA / CONSUMO</th>
<td>${getSpec(p1, ['consumo', 'bateria', 'tdp', 'carga'])}</td>
<td>${getSpec(p2, ['consumo', 'bateria', 'tdp', 'carga'])}</td>
</tr>
<tr>
<th>INVERSIÓN (COP)</th>
<td style="font-weight: 900; font-size: 1.1rem;">${formatCurrency(p1.precio)}</td>
<td style="font-weight: 900; font-size: 1.1rem;">${formatCurrency(p2.precio)}</td>
</tr>
<tr>
<th>SCORE DE RENDIMIENTO</th>
<td><div class="score-tag">${score1 > 100 ? 100 : score1}%</div></td>
<td><div class="score-tag">${score2 > 100 ? 100 : score2}%</div></td>
</tr>
</tbody>
</table>
`;
document.getElementById('analysis-modal').style.display = 'flex';
}
// 8. DETALLES MODAL
function showDetails(pid) {
const p = products.find(x => x.id === pid);
const content = document.getElementById('details-content');
content.innerHTML = `
<div style="display: flex; gap: 3rem; flex-wrap: wrap;">
<div style="flex: 1; min-width: 300px;">
<img src="${p.img}" style="width: 100%; border-radius: 10px; background: #000; padding: 2rem;">
</div>
<div style="flex: 1.5; min-width: 300px;">
<h2 style="color: var(--neon-aqua); margin-bottom: 1rem;">${p.nombre}</h2>
<div class="price" style="font-size: 2rem;">${formatCurrency(p.precio)}</div>
<h3 style="margin: 2rem 0 1rem; font-size: 0.8rem; letter-spacing: 2px; color: #444;">DATA SHEET</h3>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
${Object.entries(p.specs).map(([k, v]) => `
<div style="border-bottom: 1px solid #1a1a1a; padding: 0.5rem 0;">
<span style="display: block; font-size: 0.6rem; color: #555; text-transform: uppercase;">${k}</span>
<span style="font-size: 0.9rem; font-weight: bold;">${v}</span>
</div>
`).join('')}
</div>
</div>
</div>
`;
document.getElementById('details-modal').style.display = 'flex';
}
function closeModal(id) { document.getElementById(id).style.display = 'none'; }
// 9. CARRITO Y EXTRAS
function addToCart(pid) {
const p = products.find(x => x.id === pid);
cart.push(p);
localStorage.setItem('sf_cart_master_final', JSON.stringify(cart));
updateCartVisuals();
showToast(`Producto añadido al análisis: ${p.nombre}`);
}
function updateCartVisuals() {
const counter = document.getElementById('cart-count');
if (counter) counter.innerText = cart.length;
}
function openCart() {
if (cart.length === 0) return showToast("Bolsa vacía.");
renderCartSummary();
document.getElementById('cart-modal').style.display = 'flex';
}
function renderCartSummary() {
const content = document.getElementById('cart-summary-content');
const totalLabel = document.getElementById('cart-total-value');
let total = 0;
content.innerHTML = cart.map((item, index) => {
total += item.precio;
return `
<div class="cart-item">
<img src="${item.img}" alt="${item.nombre}">
<div class="cart-item-info">
<h4>${item.nombre}</h4>
<p>${item.cat.toUpperCase()} | 1 Unidad</p>
</div>
<div class="cart-item-price" style="display: flex; align-items: center; gap: 1rem;">
<span>${formatCurrency(item.precio)}</span>
<button onclick="removeFromCart(${index})" style="background: none; border: none; color: #ff3e3e; cursor: pointer; font-size: 1rem;" title="Eliminar"><i class="fa-solid fa-trash"></i></button>
</div>
</div>
`;
}).join('');
totalLabel.innerText = formatCurrency(total);
}
function removeFromCart(index) {
cart.splice(index, 1);
localStorage.setItem('sf_cart_master_final', JSON.stringify(cart));
updateCartVisuals();
renderCartSummary();
if (cart.length === 0) closeModal('cart-modal');
}
function proceedToCheckout() {
closeModal('cart-modal');
document.getElementById('checkout-modal').style.display = 'flex';
}
function finishOrder(method) {
showToast(`Enlazando con pasarela ${method}...`);
setTimeout(() => {
showToast("¡ADQUISICIÓN CONFIRMADA!");
cart = [];
localStorage.removeItem('sf_cart_master_final');
updateCartVisuals();
closeModal('checkout-modal');
}, 1500);
}
// 10. SYSTEMA TOAST
function showToast(message) {
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
toast.className = 'toast';
toast.innerHTML = `
<i class="fa-solid fa-circle-check"></i>
<div class="toast-message">${message}</div>
`;
container.appendChild(toast);
setTimeout(() => {
toast.classList.add('removing');
setTimeout(() => toast.remove(), 500);
}, 3000);
}
async function cerrarSesionMaster() {
localStorage.removeItem('specflow_session');
await supabaseClient.auth.signOut();
location.reload();
}
function logoutUser() { cerrarSesionMaster(); }
// 12. LÓGICA DE ADMINISTRADOR (NÚCLEO)
function openAdminModal() {
renderAdminPanel();
cargarIdentidades(); // Cargar identidades reales
const modal = document.getElementById('admin-modal');
if (modal) modal.style.display = 'flex';
}
function switchAdminTab(tabName) {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.admin-tab-panel').forEach(p => p.classList.remove('active'));
event.currentTarget.classList.add('active');
document.getElementById(`admin-tab-${tabName}`).classList.add('active');
if (tabName === 'identities') cargarIdentidades();
}
async function cargarIdentidades() {
const container = document.getElementById('admin-users-content');
if (!container) return;
// Estado inicial de carga técnica
container.innerHTML = `<div style="text-align:center; padding: 2rem; color: var(--neon-aqua); letter-spacing: 2px;">SINCRONIZANDO NÚCLEO...</div>`;
const { data, error } = await supabaseClient.from('perfiles').select('*').order('created_at', { ascending: false });
if (error) {
console.error(error);
container.innerHTML = `<div style="text-align:center; color: #ff3e3e;">ERROR DE SINCRONIZACIÓN TÉCNICA</div>`;
return;
}
const counter = document.getElementById('admin-user-count');
if (counter) counter.innerText = `USUARIOS VINCULADOS: ${data.length}`;
if (data.length === 0) {
container.innerHTML = `<div style="text-align:center; padding: 2rem; color: #555;">NO SE DETECTAN IDENTIDADES EN EL NÚCLEO</div>`;
return;
}
let html = `
<table class="admin-table">
<thead>
<tr>
<th>Identidad / Email</th>
<th>Vinculación</th>
<th>Estado</th>
<th>Acción Segura</th>
</tr>
</thead>
<tbody>
`;
data.forEach(user => {
const isBlocked = user.estado === 'bloqueado';
const statusClass = isBlocked ? 'blocked' : 'active';
const statusText = isBlocked ? 'REVOCADO' : 'ACTIVO';
const actionText = isBlocked ? 'HABILITAR' : 'BLOQUEAR'; // Cambiado a 'BLOQUEAR'
const actionClass = isBlocked ? 'activate' : 'revoke';
const lastConn = user.ultima_conexion ? new Date(user.ultima_conexion).toLocaleString() : new Date().toLocaleString();
html += `
<tr>
<td>
<div style="font-weight: bold; color: #eee; font-family: monospace;">${user.email}</div>
<div style="font-size: 0.6rem; color: #444;">ID: ${user.id}</div>
</td>
<td><span style="color: #888;">${lastConn}</span></td>
<td><span class="status-badge ${statusClass}">${statusText}</span></td>
<td>
<button class="btn-admin-action ${actionClass}" onclick="toggleUserBlock('${user.id}', '${user.estado}')">
${actionText}
</button>
</td>
</tr>
`;
});
html += `</tbody></table>`;
container.innerHTML = html;
}
// Alias para compatibilidad si se llama desde otros sitios
async function fetchAdminUsers() { await cargarIdentidades(); }
async function toggleUserBlock(userId, currentStatus) {
const newStatus = currentStatus === 'activo' ? 'bloqueado' : 'activo';
const { error } = await supabaseClient.from('perfiles').update({ estado: newStatus }).eq('id', userId);
if (!error) {
showToast(newStatus === 'activo' ? "IDENTIDAD HABILITADA" : "IDENTIDAD BLOQUEADA");
cargarIdentidades();
}
}
function renderAdminPanel() {
const container = document.getElementById('admin-panel-content');
if (!container) return;
let html = `
<table class="admin-table">
<thead>
<tr>
<th>Ref</th>
<th>Producto</th>
<th>Cat</th>
<th>Precio (COP)</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
`;
products.forEach((p, index) => {
html += `
<tr id="admin-row-${p.id}">
<td style="color: #444; font-family: monospace;">${p.id}</td>
<td>
<div style="display: flex; align-items: center; gap: 1rem;">
<img src="${p.img}" class="admin-img-mini">
<span>${p.nombre}</span>
</div>
</td>
<td><span style="font-size: 0.6rem; color: #666; text-transform: uppercase;">${p.cat}</span></td>
<td>
<div class="price-editor">
<input type="number" class="price-input" id="price-input-${p.id}" value="${p.precio}" onchange="updateProductPrice('${p.id}', this.value)">
</div>
</td>
<td>
<div style="display: flex; gap: 0.5rem;">
<button class="btn-admin-action delete" onclick="deleteMasterProduct('${p.id}', ${index})">Eliminar</button>
</div>
</td>
</tr>
`;
});
html += `</tbody></table>`;
container.innerHTML = html;
}
function updateProductPrice(id, newPrice) {
const product = products.find(p => p.id === id);
if (product) {
product.precio = parseInt(newPrice);
showToast(`Precio actualizado: ${product.nombre}`);
renderAllCatalogs();
}
}
function deleteMasterProduct(id, index) {
if (confirm(`¿Eliminar definitivamente ${products[index].nombre}?`)) {
products.splice(index, 1);
showToast("Unidad eliminada del catálogo maestro");
renderAdminPanel();
renderAllCatalogs();
}
}
function formatCurrency(v) { return new Intl.NumberFormat('es-CO', { style: 'currency', currency: 'COP', maximumFractionDigits: 0 }).format(v); }
// 11. VISIBILIDAD DE CONTRASEÑA
function togglePasswordVisibility(inputId, icon) {
const input = document.getElementById(inputId);
if (!input) return;
if (input.type === 'password') {
input.type = 'text';
icon.classList.remove('fa-eye');
icon.classList.add('fa-eye-slash');
} else {
input.type = 'password';
icon.classList.remove('fa-eye-slash');
icon.classList.add('fa-eye');
}
}
// --- PERSISTENCIA Y SEGURIDAD MASTER ---
async function verificarSesion() {
const session = JSON.parse(localStorage.getItem('specflow_session'));
// 1. Caso Admin (Bypass)
if (session && session.role === 'admin') {
unlockApp();
return;
}
// 2. Caso Usuario Estándar o Auth Central
const { data: { session: sbSession } } = await supabaseClient.auth.getSession();
if (sbSession) {
// Enforce confirmación de correo al recuperar sesión
if (sbSession.user.email !== 'admin@gmail.com' && !sbSession.user.email_confirmed_at) {
localStorage.removeItem('specflow_session');
await supabaseClient.auth.signOut();
lockApp();
return;
}
const userSession = { email: sbSession.user.email, role: 'user', isAuthenticated: true };
localStorage.setItem('specflow_session', JSON.stringify(userSession));
unlockApp();
} else if (session && session.isAuthenticated) {
// Respaldo de sesión local si supabase aún no responde
unlockApp();
} else {
lockApp();
}
}
// 10. INICIALIZACIÓN FINAL
document.addEventListener('DOMContentLoaded', () => {
verificarSesion(); // Carga de persistencia inteligente
const bR = document.getElementById('btn-ejecutar-registro');
if (bR) bR.onclick = ejecutarRegistro;
const bL = document.getElementById('btn-login');
if (bL) bL.onclick = ejecutarLogin;
supabaseClient.auth.onAuthStateChange((event, session) => {
// Sincronización pero respetando el bypass del admin
const local = JSON.parse(localStorage.getItem('specflow_session'));
if (local && local.role === 'admin') return;
if (event === 'SIGNED_OUT') {
localStorage.removeItem('specflow_session');
lockApp();
} else if (session) {
// Chequeo de seguridad al vuelo
if (session.user.email_confirmed_at) {
const userSession = { email: session.user.email, role: 'user', isAuthenticated: true };
localStorage.setItem('specflow_session', JSON.stringify(userSession));
unlockApp();
}
}
});
});