Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
1194 lines (1100 loc) · 63.7 KB
/
Copy pathindex.html
File metadata and controls
1194 lines (1100 loc) · 63.7 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
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pixel Store — tarjetas y recargas</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;700&family=Inter:wght@400;500;600&family=IBM+Plex+Mono:wght@500&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<style>
:root{
--bg:#14131F; --surface:#1D1C2C; --surface-2:#26243A; --border:#332F4C;
--text:#EDEAF6; --text-secondary:#9C99B4; --text-muted:#6E6B87;
--accent:#7B5CFA; --accent-soft:#251F52; --amber:#F2A93B; --amber-soft:#3A2E14;
--green:#3FC97A; --green-soft:#123A26; --radius:14px;
}
*{box-sizing:border-box;}
body{margin:0;background:var(--bg) url('assets/fondo.png') repeat;background-size:420px;color:var(--text);font-family:'Inter',sans-serif;line-height:1.5;}
body::before{content:"";position:fixed;inset:0;background:var(--bg);opacity:.88;z-index:-1;}
h1,h2,h3{font-family:'Space Grotesk',sans-serif;}
.wrap{max-width:960px;margin:0 auto;padding:28px 18px 90px;}
.topbar{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:28px;flex-wrap:wrap;}
.brand{display:flex;align-items:center;gap:10px;}
.brand-mark{width:34px;height:34px;border-radius:9px;background:var(--accent);display:flex;align-items:center;justify-content:center;font-family:'Space Grotesk',sans-serif;font-weight:700;color:#fff;}
.brand-name{font-weight:600;font-size:16px;}
.nav-tabs{display:flex;gap:4px;background:var(--surface);padding:4px;border-radius:999px;border:1px solid var(--border);overflow-x:auto;max-width:100%;}
.nav-tab{padding:8px 14px;border-radius:999px;font-size:12.5px;font-weight:500;color:var(--text-secondary);cursor:pointer;transition:.15s;background:none;border:none;font-family:inherit;white-space:nowrap;}
.nav-tab.active{background:var(--accent);color:#fff;}
.nav-tab.hidden{display:none;}
.profile-chip{width:34px;height:34px;border-radius:50%;background:var(--surface-2);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:600;color:var(--text-secondary);cursor:pointer;flex-shrink:0;}
.view{display:none;}
.view.active{display:block;animation:fade .25s ease;}
@keyframes fade{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}
.eyebrow{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--text-muted);margin:0 0 6px;}
.section-title{font-size:21px;font-weight:700;margin:0 0 22px;}
.subhead{font-size:13px;font-weight:600;color:var(--text-secondary);margin:24px 0 10px;}
.card-box{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px;}
.help-note{font-size:12px;color:var(--text-muted);margin:6px 0 0;line-height:1.5;}
.req{color:var(--amber);font-size:11px;}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:16px;}
.product{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;display:flex;flex-direction:column;position:relative;}
.card-art{height:100px;margin:14px 14px 0;border-radius:10px;display:flex;align-items:center;justify-content:space-between;padding:14px;background:linear-gradient(120deg,#3A2E90,#241A5C);position:relative;overflow:hidden;}
.card-logo{font-family:'Space Grotesk',sans-serif;font-weight:700;font-size:14px;color:#fff;}
.product-body{padding:14px;display:flex;flex-direction:column;gap:8px;flex:1;}
.product-name{font-weight:600;font-size:14px;margin:0;}
.product-desc{font-size:12px;color:var(--text-secondary);margin:0;white-space:pre-line;}
.btn-order{background:var(--accent);color:#fff;border:none;padding:10px;border-radius:9px;font-weight:600;font-size:12.5px;cursor:pointer;margin-top:auto;}
.btn-order:disabled{opacity:.5;cursor:not-allowed;}
.field-label{font-size:12px;color:var(--text-secondary);margin:0 0 6px;display:flex;gap:6px;align-items:center;}
.field{width:100%;padding:11px 12px;border-radius:9px;background:var(--surface-2);border:1px solid var(--border);color:var(--text);font-size:14px;margin-bottom:4px;font-family:'Inter',sans-serif;}
.field:focus{outline:none;border-color:var(--accent);}
.field-block{margin-bottom:16px;}
.btn-primary{width:100%;background:var(--accent);color:#fff;border:none;padding:12px;border-radius:9px;font-weight:600;font-size:14px;cursor:pointer;}
.login-wrap{max-width:340px;margin:40px auto;background:var(--surface);border:1px solid var(--border);border-radius:18px;padding:28px 24px;}
.login-switch{text-align:center;font-size:13px;color:var(--text-secondary);margin-top:16px;}
.login-switch span{color:var(--accent);cursor:pointer;}
.status-msg{font-size:12.5px;padding:10px 12px;border-radius:9px;margin-bottom:14px;display:none;}
.status-msg.show{display:block;}
.status-error{background:#3A1414;color:#F28080;}
.status-ok{background:var(--green-soft);color:var(--green);}
.empty-state{color:var(--text-muted);font-size:13px;padding:20px 0;text-align:center;}
.admin-subtabs{display:flex;gap:6px;margin-bottom:18px;flex-wrap:wrap;}
.admin-subtab{padding:7px 13px;border-radius:9px;font-size:12.5px;background:var(--surface);border:1px solid var(--border);color:var(--text-secondary);cursor:pointer;}
.admin-subtab.active{background:var(--accent-soft);border-color:var(--accent);color:var(--accent);}
.admin-view{display:none;}
.admin-view.active{display:block;}
.guia-item{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:0;margin-bottom:16px;overflow:hidden;}
.guia-img{width:100%;height:170px;object-fit:cover;display:block;background:var(--surface-2);}
.guia-texto{padding:14px;}
.guia-titulo{font-weight:600;font-size:15px;margin:0 0 6px;}
.guia-contenido{font-size:13px;color:var(--text-secondary);margin:0;white-space:pre-line;}
.banner-img{width:100%;border-radius:var(--radius);margin-bottom:22px;display:block;border:1px solid var(--border);}
.filters{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:18px;}
.filter-pill{display:flex;align-items:center;gap:6px;background:var(--surface);border:1px solid var(--border);color:var(--text-secondary);font-size:12.5px;padding:8px 12px;border-radius:999px;cursor:pointer;}
.filter-pill.active{background:var(--accent-soft);border-color:var(--accent);color:var(--accent);}
select.field-inline{background:var(--surface);border:1px solid var(--border);color:var(--text);border-radius:999px;padding:8px 12px;font-size:12.5px;font-family:inherit;}
.product-price{font-family:'IBM Plex Mono',monospace;font-size:12.5px;color:var(--accent);font-weight:600;}
</style>
</head>
<body>
<div class="wrap">
<div class="topbar">
<div class="brand" onclick="showView('tienda', document.getElementById('tab-tienda'))" style="cursor:pointer;">
<img id="logo-img" src="assets/logo.png" alt="Pixel Store" style="width:34px;height:34px;border-radius:9px;object-fit:cover;">
<div class="brand-name" id="tab-tienda">Pixel Store</div>
</div>
<div class="nav-tabs" id="nav-tabs">
<button class="nav-tab active" data-view="catalogo" onclick="showView('catalogo', this)">Catálogo</button>
<button class="nav-tab" data-view="perfil" onclick="showView('perfil', this)">Perfil</button>
<button class="nav-tab" data-view="escuela" onclick="showView('escuela', this)">Escuela</button>
<button class="nav-tab" data-view="torneos" onclick="showView('torneos', this)">Torneos</button>
<button class="nav-tab" data-view="anuncios" onclick="showView('anuncios', this)">Anuncios</button>
<button class="nav-tab hidden" id="tab-admin" data-view="admin" onclick="showView('admin', this)">Admin</button>
<button class="nav-tab" id="tab-acceso" data-view="acceso" onclick="showView('acceso', this)">Acceder</button>
</div>
<div class="profile-chip" id="chip">?</div>
</div>
<!-- CATÁLOGO -->
<div class="view active" id="view-catalogo">
<div id="carrusel-torneos" style="display:none;position:relative;border-radius:var(--radius);overflow:hidden;margin-bottom:18px;border:1px solid var(--border);cursor:pointer;" onclick="irACarruselDestino()">
<img id="carrusel-img" src="" alt="" style="width:100%;height:170px;object-fit:cover;display:block;transition:opacity .4s;">
<div id="carrusel-titulo" style="position:absolute;bottom:0;left:0;right:0;background:linear-gradient(0deg, rgba(0,0,0,.75), transparent);color:#fff;padding:24px 14px 10px;font-size:13.5px;font-weight:600;"></div>
<div id="carrusel-dots" style="position:absolute;top:10px;right:10px;display:flex;gap:5px;"></div>
</div>
<img class="banner-img" src="assets/banner.png" alt="Pixel Store">
<p class="eyebrow">Elige y encarga</p>
<h1 class="section-title">Tarjetas y recargas disponibles</h1>
<div style="background:var(--amber-soft);border:1px solid var(--amber);color:var(--amber);border-radius:10px;padding:10px 12px;font-size:12.5px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;">
<span>⚠️ Si no ves los productos, toca "Actualizar" para refrescar el catálogo.</span>
<button class="btn-order" style="padding:7px 14px;flex-shrink:0;" onclick="cargarProductos()">🔄 Actualizar</button>
</div>
<div class="filters">
<div class="filter-pill" id="filtro-precio" onclick="toggleOrdenPrecio()">↕ Precio: menor a mayor</div>
<select class="field-inline" id="filtro-moneda" onchange="cargarProductos()">
<option value="">Todas las monedas</option>
<option value="CUP">Transferencia CUP ₱</option>
<option value="USDT">USDT / USDC</option>
<option value="USD">Efectivo USD 💵</option>
</select>
</div>
<div class="grid" id="productos-grid">
<p class="empty-state">Cargando productos…</p>
</div>
</div>
<!-- DATOS DE LA TIENDA -->
<div class="view" id="view-tienda">
<p class="eyebrow">Sobre nosotros</p>
<h1 class="section-title">Pixel Store</h1>
<div id="tienda-lectura" class="card-box">
<p class="empty-state">Cargando datos de la tienda…</p>
</div>
<div id="tienda-editar" style="display:none;margin-top:18px;">
<p class="subhead">Editar datos (solo admin)</p>
<div id="status-tienda" class="status-msg"></div>
<div class="card-box">
<div class="field-block"><label class="field-label">Nombre de la tienda</label><input class="field" id="t-nombre" type="text" placeholder="Pixel Store"></div>
<div class="field-block"><label class="field-label">Sitio de entrega</label><input class="field" id="t-entrega" type="text" placeholder="Ej: Solo entrega digital"></div>
<div class="field-block"><label class="field-label">Link de Google Maps</label><input class="field" id="t-maps" type="text" placeholder="https://maps.google.com/..."></div>
<div class="field-block"><label class="field-label">Tu WhatsApp para recibir encargos</label><input class="field" id="t-whatsapp-admin" type="text" placeholder="+53 5xxx xxxx (sin espacios ni +, ej: 5355123456)"></div>
<div class="field-block"><label class="field-label">Tu correo para recibir encargos</label><input class="field" id="t-email-admin" type="email" placeholder="tucorreo@ejemplo.com"></div>
<div class="field-block"><label class="field-label">Latitud</label><input class="field" id="t-lat" type="number" step="0.000001" placeholder="Ej: 23.135305"></div>
<div class="field-block" style="margin-bottom:0;">
<label class="field-label">Longitud</label>
<input class="field" id="t-lng" type="number" step="0.000001" placeholder="Ej: -82.358965">
<p class="help-note">Para conseguir estos números: abre Google Maps, toca y mantén presionado tu punto de entrega, y arriba te muestra las coordenadas — cópialas aquí separadas (la primera es latitud, la segunda longitud).</p>
</div>
</div>
<button class="btn-primary" style="margin-top:14px;" onclick="guardarDatosTienda()">Guardar datos</button>
</div>
</div>
<!-- PERFIL -->
<div class="view" id="view-perfil">
<p class="eyebrow">Tu cuenta</p>
<h1 class="section-title">Perfil</h1>
<div id="status-perfil" class="status-msg"></div>
<div style="display:flex;gap:16px;align-items:center;margin-bottom:18px;">
<img id="avatar-grande" src="" alt="" style="width:84px;height:84px;border-radius:50%;object-fit:cover;background:var(--surface-2);border:1px solid var(--border);display:none;">
<div id="avatar-grande-fallback" style="width:84px;height:84px;border-radius:50%;background:var(--surface-2);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;font-size:26px;color:var(--text-secondary);">?</div>
<div>
<input type="file" id="p-foto-file" accept="image/*" style="display:none;" onchange="previsualizarFoto('p-foto-file','avatar-grande','avatar-grande-fallback')">
<button class="btn-order" style="padding:8px 14px;" onclick="document.getElementById('p-foto-file').click()">Cambiar foto</button>
</div>
</div>
<div class="card-box">
<div class="field-block">
<label class="field-label">Nombre real <span class="req">· obligatorio</span></label>
<input class="field" id="p-nombre" type="text" placeholder="Nombre y apellidos">
</div>
<div class="field-block">
<label class="field-label">Contacto de WhatsApp <span class="req">· obligatorio</span></label>
<input class="field" id="p-whatsapp" type="text" placeholder="+53 5xxx xxxx">
<p class="help-note">Sin este dato no puedes realizar encargos.</p>
</div>
<div class="field-block" style="margin-bottom:0;">
<label class="field-label">Carnet / DNI <span style="color:var(--text-muted);font-size:11px;">· solo para Efectivo USD o CUP</span></label>
<input class="field" id="p-carnet" type="text" placeholder="00000000000">
</div>
</div>
<p class="help-note" style="margin-top:6px;"><b>Medidas recomendadas para la foto:</b> cuadrada, 400×400 px (mínimo 200×200 px), JPG o PNG, hasta 2 MB.</p>
<button class="btn-primary" style="margin-top:10px;" onclick="guardarPerfil()">Guardar perfil</button>
<p class="login-switch" id="logout-row" style="display:none;"><span onclick="salir()">Cerrar sesión</span></p>
</div>
<!-- ESCUELA -->
<div class="view" id="view-escuela">
<p class="eyebrow">Aprende</p>
<h1 class="section-title">Guías de Web3</h1>
<div id="guias-lista">
<p class="empty-state">Cargando guías…</p>
</div>
</div>
<!-- TORNEOS -->
<div class="view" id="view-torneos">
<p class="eyebrow">Compite</p>
<h1 class="section-title">Torneos</h1>
<div id="torneos-lista">
<p class="empty-state">Cargando torneos…</p>
</div>
</div>
<!-- ANUNCIOS -->
<div class="view" id="view-anuncios">
<p class="eyebrow">Novedades</p>
<h1 class="section-title">Anuncios</h1>
<div id="anuncios-lista">
<p class="empty-state">Cargando anuncios…</p>
</div>
</div>
<!-- ADMIN (oculto salvo es_admin = true) -->
<div class="view" id="view-admin">
<p class="eyebrow">Panel privado</p>
<h1 class="section-title">Administración</h1>
<div class="admin-subtabs">
<button class="admin-subtab active" onclick="showAdmin('producto', this)">Agregar producto</button>
<button class="admin-subtab" onclick="showAdmin('guia', this)">Agregar guía</button>
<button class="admin-subtab" onclick="showAdmin('torneo', this)">Agregar torneo</button>
<button class="admin-subtab" onclick="showAdmin('anuncio', this)">Agregar anuncio</button>
<button class="admin-subtab" onclick="showAdmin('usuarios', this)">Usuarios</button>
</div>
<div class="admin-view active" id="admin-producto">
<div id="status-admin" class="status-msg"></div>
<div class="card-box">
<div class="field-block">
<label class="field-label">Foto del producto</label>
<input type="file" id="a-img-file" accept="image/*" style="display:none;" onchange="previsualizarFoto('a-img-file','a-img-preview',null)">
<button class="btn-order" style="padding:9px 14px;" onclick="document.getElementById('a-img-file').click()">📷 Elegir foto</button>
<img id="a-img-preview" src="" alt="" style="display:none;width:100%;max-height:160px;object-fit:contain;border-radius:9px;margin-top:8px;background:var(--surface-2);">
<p class="help-note"><b>Medidas recomendadas:</b> 800×800 px, cuadrada, fondo simple, JPG/PNG hasta 3 MB.</p>
</div>
<div class="field-block"><label class="field-label">Nombre del producto</label><input class="field" id="a-nombre" type="text" placeholder="Ej: Free Fire — Diamantes"></div>
<p class="field-label" style="margin-bottom:8px;">Precios por moneda <span style="color:var(--text-muted);font-size:11px;">· deja vacío lo que no aplique</span></p>
<div class="field-block"><label class="field-label">Transferencia CUP ₱</label><input class="field" id="a-precio-cup" type="number" step="0.01" placeholder="Ej: 350"></div>
<div class="field-block"><label class="field-label">USDT / USDC</label><input class="field" id="a-precio-usdt" type="number" step="0.01" placeholder="Ej: 3.50"></div>
<div class="field-block"><label class="field-label">Efectivo USD 💵</label><input class="field" id="a-precio-usd" type="number" step="0.01" placeholder="Ej: 3.50"></div>
<div class="field-block" style="margin-bottom:0;"><label class="field-label">Descripción</label><textarea class="field" id="a-desc" placeholder="Recarga directa a tu ID..." style="min-height:90px;resize:vertical;"></textarea></div>
</div>
<button class="btn-primary" style="margin-top:14px;" id="btn-producto" onclick="agregarProducto()">Publicar producto</button>
<button class="btn-order" id="btn-cancelar-producto" style="display:none;width:100%;margin-top:8px;background:var(--surface-2);border:1px solid var(--border);color:var(--text);" onclick="cancelarEdicionProducto()">Cancelar edición</button>
<button class="btn-order" id="btn-eliminar-producto" style="display:none;width:100%;margin-top:8px;background:#3A1414;border:1px solid #6B2222;color:#F28080;" onclick="eliminarProducto(productoEditando)">🗑️ Eliminar este producto</button>
<p class="subhead">Tus productos publicados</p>
<div id="lista-productos-admin"><p class="empty-state">Cargando…</p></div>
</div>
<div class="admin-view" id="admin-guia">
<div id="status-guia" class="status-msg"></div>
<div class="card-box">
<div class="field-block">
<label class="field-label">Imagen de la guía</label>
<input type="file" id="g-img-file" accept="image/*" style="display:none;" onchange="previsualizarFoto('g-img-file','g-img-preview',null)">
<button class="btn-order" style="padding:9px 14px;" onclick="document.getElementById('g-img-file').click()">📷 Elegir foto</button>
<img id="g-img-preview" src="" alt="" style="display:none;width:100%;max-height:160px;object-fit:contain;border-radius:9px;margin-top:8px;background:var(--surface-2);">
<p class="help-note"><b>Medidas recomendadas:</b> 600×400 px, JPG/PNG hasta 2 MB.</p>
</div>
<div class="field-block"><label class="field-label">Título</label><input class="field" id="g-titulo" type="text" placeholder="Ej: ¿Qué es USDT y cómo comprarlo?"></div>
<div class="field-block" style="margin-bottom:0;"><label class="field-label">Contenido</label><textarea class="field" id="g-contenido" placeholder="Explica el paso a paso aquí..." style="min-height:140px;resize:vertical;"></textarea></div>
</div>
<button class="btn-primary" style="margin-top:14px;" id="btn-guia" onclick="agregarGuia()">Publicar guía</button>
<button class="btn-order" id="btn-cancelar-guia" style="display:none;width:100%;margin-top:8px;background:var(--surface-2);border:1px solid var(--border);color:var(--text);" onclick="cancelarEdicionGuia()">Cancelar edición</button>
<button class="btn-order" id="btn-eliminar-guia" style="display:none;width:100%;margin-top:8px;background:#3A1414;border:1px solid #6B2222;color:#F28080;" onclick="eliminarGuia(guiaEditando)">🗑️ Eliminar esta guía</button>
<p class="subhead">Tus guías publicadas</p>
<div id="lista-guias-admin"><p class="empty-state">Cargando…</p></div>
</div>
<div class="admin-view" id="admin-torneo">
<div id="status-torneo" class="status-msg"></div>
<div class="card-box">
<div class="field-block">
<label class="field-label">Imagen del torneo</label>
<input type="file" id="tr-img-file" accept="image/*" style="display:none;" onchange="previsualizarFoto('tr-img-file','tr-img-preview',null)">
<button class="btn-order" style="padding:9px 14px;" onclick="document.getElementById('tr-img-file').click()">📷 Elegir foto</button>
<img id="tr-img-preview" src="" alt="" style="display:none;width:100%;max-height:160px;object-fit:contain;border-radius:9px;margin-top:8px;background:var(--surface-2);">
<p class="help-note"><b>Medidas recomendadas:</b> 1200×500 px (horizontal), JPG/PNG hasta 3 MB — se usa también en el carrusel de inicio.</p>
</div>
<div class="field-block"><label class="field-label">Título</label><input class="field" id="tr-titulo" type="text" placeholder="Ej: Torneo Free Fire — Agosto"></div>
<div class="field-block" style="margin-bottom:0;"><label class="field-label">Instrucciones para participar</label><textarea class="field" id="tr-contenido" placeholder="Explica cómo inscribirse, premios, fecha..." style="min-height:140px;resize:vertical;"></textarea></div>
</div>
<button class="btn-primary" style="margin-top:14px;" id="btn-torneo" onclick="agregarTorneo()">Publicar torneo</button>
<button class="btn-order" id="btn-cancelar-torneo" style="display:none;width:100%;margin-top:8px;background:var(--surface-2);border:1px solid var(--border);color:var(--text);" onclick="cancelarEdicionTorneo()">Cancelar edición</button>
<button class="btn-order" id="btn-eliminar-torneo" style="display:none;width:100%;margin-top:8px;background:#3A1414;border:1px solid #6B2222;color:#F28080;" onclick="eliminarTorneo(torneoEditando)">🗑️ Eliminar este torneo</button>
<p class="subhead">Tus torneos publicados</p>
<div id="lista-torneos-admin"><p class="empty-state">Cargando…</p></div>
</div>
<div class="admin-view" id="admin-anuncio">
<div id="status-anuncio" class="status-msg"></div>
<div class="card-box">
<div class="field-block">
<label class="field-label">Imagen del anuncio</label>
<input type="file" id="an-img-file" accept="image/*" style="display:none;" onchange="previsualizarFoto('an-img-file','an-img-preview',null)">
<button class="btn-order" style="padding:9px 14px;" onclick="document.getElementById('an-img-file').click()">📷 Elegir foto</button>
<img id="an-img-preview" src="" alt="" style="display:none;width:100%;max-height:160px;object-fit:contain;border-radius:9px;margin-top:8px;background:var(--surface-2);">
<p class="help-note"><b>Medidas recomendadas:</b> 1200×500 px (horizontal), JPG/PNG hasta 3 MB — se usa también en el carrusel de inicio.</p>
</div>
<div class="field-block"><label class="field-label">Título</label><input class="field" id="an-titulo" type="text" placeholder="Ej: Descuento especial de fin de mes"></div>
<div class="field-block"><label class="field-label">Descripción</label><textarea class="field" id="an-contenido" placeholder="Detalles del anuncio..." style="min-height:100px;resize:vertical;"></textarea></div>
<div class="field-block"><label class="field-label">Fecha de inicio</label><input class="field" id="an-fecha-inicio" type="date"></div>
<div class="field-block" style="margin-bottom:0;">
<label class="field-label">Fecha de finalización</label>
<input class="field" id="an-fecha-fin" type="date">
<p class="help-note">Al pasar esta fecha, el anuncio deja de mostrarse en el carrusel de inicio y queda marcado como "Acabado" en este menú.</p>
</div>
</div>
<button class="btn-primary" style="margin-top:14px;" id="btn-anuncio" onclick="agregarAnuncio()">Publicar anuncio</button>
<button class="btn-order" id="btn-cancelar-anuncio" style="display:none;width:100%;margin-top:8px;background:var(--surface-2);border:1px solid var(--border);color:var(--text);" onclick="cancelarEdicionAnuncio()">Cancelar edición</button>
<button class="btn-order" id="btn-eliminar-anuncio" style="display:none;width:100%;margin-top:8px;background:#3A1414;border:1px solid #6B2222;color:#F28080;" onclick="eliminarAnuncio(anuncioEditando)">🗑️ Eliminar este anuncio</button>
<p class="subhead">Tus anuncios publicados</p>
<div id="lista-anuncios-admin"><p class="empty-state">Cargando…</p></div>
</div>
<div class="admin-view" id="admin-usuarios">
<p class="help-note" style="margin-bottom:12px;">Lista de solo lectura — aquí no se puede editar ni eliminar a nadie.</p>
<div id="lista-usuarios-admin"><p class="empty-state">Cargando…</p></div>
</div>
</div>
<!-- ACCESO -->
<div class="view" id="view-acceso">
<div class="login-wrap">
<h2 id="login-title" style="font-size:19px;margin:0 0 4px;">Bienvenido de vuelta</h2>
<p style="font-size:13px;color:var(--text-secondary);margin:0 0 18px;">Entra para ver el catálogo y tus encargos</p>
<div id="status-login" class="status-msg"></div>
<label class="field-label">Correo</label>
<input class="field" id="l-email" type="email" placeholder="tunombre@correo.com">
<label class="field-label">Contraseña</label>
<input class="field" id="l-pass" type="password" placeholder="••••••••">
<button class="btn-primary" style="margin-top:8px;" onclick="entrar()" id="btn-entrar">Entrar</button>
<p class="login-switch" id="login-switch">¿No tienes cuenta? <span onclick="modoRegistro()">Crear una</span></p>
</div>
</div>
</div>
<script>
// ⚠️ Reemplaza estos dos valores con los tuyos (Settings → API en Supabase)
const SUPABASE_URL = 'https://wntdofksncorxybgpeqa.supabase.co';
const SUPABASE_KEY = 'sb_publishable_cBU0WIk2tfVRWjA8cSvsAg__YVOHOhy';
const sb = supabase.createClient(SUPABASE_URL, SUPABASE_KEY);
let modoActual = 'login'; // 'login' o 'registro'
let sesion = null;
let miPerfil = null;
function showView(id, btn){
document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));
document.getElementById('view-'+id).classList.add('active');
document.querySelectorAll('.nav-tab').forEach(t=>t.classList.remove('active'));
if(btn) btn.classList.add('active');
}
function showAdmin(id, btn){
document.querySelectorAll('.admin-view').forEach(v=>v.classList.remove('active'));
document.getElementById('admin-'+id).classList.add('active');
document.querySelectorAll('.admin-subtab').forEach(t=>t.classList.remove('active'));
btn.classList.add('active');
if(id === 'usuarios') cargarUsuariosAdmin();
}
async function cargarUsuariosAdmin(){
const cont = document.getElementById('lista-usuarios-admin');
cont.innerHTML = '<p class="empty-state">Cargando…</p>';
const { data, error } = await sb.from('perfiles').select('*').order('creado_en', { ascending:false });
if(error){ cont.innerHTML = `<p class="empty-state">No se pudo cargar: ${error.message}</p>`; return; }
if(!data || data.length === 0){ cont.innerHTML = '<p class="empty-state">Aún no hay usuarios registrados.</p>'; return; }
cont.innerHTML = '';
data.forEach(u=>{
const row = document.createElement('div');
row.className = 'order-item';
const inicial = (u.nombre_real||'?').slice(0,2).toUpperCase();
row.innerHTML = `
${u.foto_url ? `<img src="${u.foto_url}" style="width:36px;height:36px;border-radius:50%;object-fit:cover;flex-shrink:0;">` : `<div class="order-icon">${inicial}</div>`}
<div>
<p class="order-name">${u.nombre_real || '(sin nombre)'} ${u.es_admin ? ' · 👑 admin' : ''}</p>
<p class="order-meta">WhatsApp: ${u.whatsapp || '—'}${u.carnet ? ' · Carnet: '+u.carnet : ''}</p>
</div>
`;
cont.appendChild(row);
});
}
function linkify(texto){
if(!texto) return '';
const escapado = texto.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
return escapado.replace(/(https?:\/\/[^\s]+)/g, url => `<a href="${url}" target="_blank" style="color:var(--accent);text-decoration:underline;">${url}</a>`);
}
function previsualizarFoto(inputId, imgId, fallbackId){
const file = document.getElementById(inputId).files[0];
if(!file) return;
const url = URL.createObjectURL(file);
const img = document.getElementById(imgId);
img.src = url;
img.style.display = 'block';
if(fallbackId) document.getElementById(fallbackId).style.display = 'none';
}
async function subirArchivo(inputId){
const file = document.getElementById(inputId).files[0];
if(!file) return null;
try{
const nombreArchivo = `${Date.now()}-${file.name.replace(/[^a-zA-Z0-9.]/g,'_')}`;
const { error } = await sb.storage.from('imagenes').upload(nombreArchivo, file);
if(error){ throw error; }
const { data } = sb.storage.from('imagenes').getPublicUrl(nombreArchivo);
return data.publicUrl;
} catch(e){
alert('No se pudo subir la imagen: ' + (e.message || e));
throw e;
}
}
function mostrarMsg(id, texto, tipo){
const el = document.getElementById(id);
el.textContent = texto;
el.className = 'status-msg show ' + (tipo === 'error' ? 'status-error' : 'status-ok');
}
function modoRegistro(){
modoActual = 'registro';
document.getElementById('login-title').textContent = 'Crear cuenta';
document.getElementById('btn-entrar').textContent = 'Registrarme';
document.getElementById('login-switch').innerHTML = '¿Ya tienes cuenta? <span onclick="modoLogin()">Entrar</span>';
}
function modoLogin(){
modoActual = 'login';
document.getElementById('login-title').textContent = 'Bienvenido de vuelta';
document.getElementById('btn-entrar').textContent = 'Entrar';
document.getElementById('login-switch').innerHTML = '¿No tienes cuenta? <span onclick="modoRegistro()">Crear una</span>';
}
async function entrar(){
const email = document.getElementById('l-email').value.trim();
const pass = document.getElementById('l-pass').value;
if(!email || !pass){ mostrarMsg('status-login','Completa correo y contraseña','error'); return; }
if(modoActual === 'registro'){
const { data, error } = await sb.auth.signUp({ email, password: pass });
if(error){ mostrarMsg('status-login', error.message, 'error'); return; }
mostrarMsg('status-login','Cuenta creada. Ahora completa tu perfil.','ok');
} else {
const { data, error } = await sb.auth.signInWithPassword({ email, password: pass });
if(error){ mostrarMsg('status-login', error.message, 'error'); return; }
}
await cargarSesion();
showView('catalogo', document.querySelector('.nav-tab[data-view="catalogo"]'));
}
async function salir(){
await sb.auth.signOut();
sesion = null; miPerfil = null;
actualizarUIsegunSesion();
showView('acceso', document.getElementById('tab-acceso'));
}
async function cargarSesion(){
const { data:{ session } } = await sb.auth.getSession();
sesion = session;
if(sesion){
const { data: perfil } = await sb.from('perfiles').select('*').eq('id', sesion.user.id).maybeSingle();
miPerfil = perfil;
if(miPerfil){
document.getElementById('p-nombre').value = miPerfil.nombre_real || '';
document.getElementById('p-whatsapp').value = miPerfil.whatsapp || '';
document.getElementById('p-carnet').value = miPerfil.carnet || '';
document.getElementById('chip').textContent = (miPerfil.nombre_real||'?').slice(0,2).toUpperCase();
const avatarImg = document.getElementById('avatar-grande');
const avatarFallback = document.getElementById('avatar-grande-fallback');
if(miPerfil.foto_url){
avatarImg.src = miPerfil.foto_url; avatarImg.style.display='block'; avatarFallback.style.display='none';
document.getElementById('chip').style.backgroundImage = `url('${miPerfil.foto_url}')`;
document.getElementById('chip').style.backgroundSize = 'cover';
document.getElementById('chip').textContent = '';
} else {
avatarImg.style.display='none'; avatarFallback.style.display='flex';
avatarFallback.textContent = (miPerfil.nombre_real||'?').slice(0,2).toUpperCase();
}
}
}
actualizarUIsegunSesion();
}
function actualizarUIsegunSesion(){
const tabAdmin = document.getElementById('tab-admin');
const tabAcceso = document.getElementById('tab-acceso');
const logoutRow = document.getElementById('logout-row');
if(sesion){
tabAcceso.classList.add('hidden');
logoutRow.style.display = 'block';
if(miPerfil && miPerfil.es_admin){
tabAdmin.classList.remove('hidden');
} else {
tabAdmin.classList.add('hidden');
}
} else {
tabAcceso.classList.remove('hidden');
logoutRow.style.display = 'none';
tabAdmin.classList.add('hidden');
}
actualizarVistaTienda();
}
async function guardarPerfil(){
if(!sesion){ mostrarMsg('status-perfil','Primero inicia sesión','error'); return; }
const nombre_real = document.getElementById('p-nombre').value.trim();
const whatsapp = document.getElementById('p-whatsapp').value.trim();
const carnet = document.getElementById('p-carnet').value.trim();
if(!nombre_real || !whatsapp){ mostrarMsg('status-perfil','Nombre y WhatsApp son obligatorios','error'); return; }
let foto_url = miPerfil ? miPerfil.foto_url : null;
const nuevaFoto = await subirArchivo('p-foto-file');
if(nuevaFoto) foto_url = nuevaFoto;
const { error } = await sb.from('perfiles').upsert({
id: sesion.user.id, nombre_real, whatsapp, carnet: carnet || null, foto_url: foto_url || null
});
if(error){ mostrarMsg('status-perfil', error.message, 'error'); return; }
mostrarMsg('status-perfil','Perfil guardado ✔','ok');
document.getElementById('p-foto-file').value = '';
await cargarSesion();
}
let productoEditando = null;
let imagenActualProducto = null;
const etiquetaMoneda = { CUP:'CUP ₱', USDT:'USDT/USDC', USD:'USD 💵' };
async function cargarProductos(){
const cont = document.getElementById('productos-grid');
if(!sesion){
cont.innerHTML = `
<div style="grid-column:1/-1;background:var(--amber-soft);border:1px solid var(--amber);color:var(--amber);border-radius:10px;padding:10px 12px;font-size:12.5px;display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;">
<span>⚠️ Debes iniciar sesión o registrarte para ver el catálogo.</span>
<button class="btn-order" style="padding:7px 14px;flex-shrink:0;" onclick="showView('acceso', document.getElementById('tab-acceso'))">Acceder</button>
</div>`;
return;
}
const { data: crudos, error } = await sb.from('productos').select('*');
if(error || !crudos || crudos.length === 0){
cont.innerHTML = '<p class="empty-state">Aún no hay productos publicados.</p>';
if(miPerfil && miPerfil.es_admin) cargarListaProductosAdmin([]);
return;
}
const monedaFiltro = document.getElementById('filtro-moneda').value;
let data = crudos.filter(p => !monedaFiltro || (p.precios||[]).some(x=>x.moneda===monedaFiltro));
function precioClave(p){
const precios = p.precios || [];
if(monedaFiltro){ const f = precios.find(x=>x.moneda===monedaFiltro); return f ? f.precio : Infinity; }
if(precios.length === 0) return Infinity;
return Math.min(...precios.map(x=>x.precio));
}
if(ordenPrecioAsc) data.sort((a,b)=>precioClave(a)-precioClave(b));
else data.sort((a,b)=> new Date(b.creado_en) - new Date(a.creado_en));
if(data.length === 0){
cont.innerHTML = '<p class="empty-state">No hay productos en esa moneda.</p>';
} else {
cont.innerHTML = '';
data.forEach(p=>{
const div = document.createElement('div');
div.className = 'product';
const precios = p.precios || [];
const preciosHtml = precios.map(x=>`<p class="product-price">${x.precio} ${etiquetaMoneda[x.moneda]||x.moneda}</p>`).join('');
div.innerHTML = `
<div class="card-art" style="${p.imagen_url ? `background-image:url('${p.imagen_url}');background-size:cover;background-position:center;` : ''}">
<span class="card-logo">${p.imagen_url ? '' : p.nombre}</span>
</div>
<div class="product-body">
<p class="product-name">${p.nombre}</p>
<p class="product-desc">${linkify(p.descripcion || '')}</p>
${preciosHtml}
<button class="btn-order" onclick="crearEncargo('${p.id}','${(p.nombre||'').replace(/'/g,"\\'")}')">Encargar</button>
</div>`;
cont.appendChild(div);
});
}
if(miPerfil && miPerfil.es_admin) cargarListaProductosAdmin(crudos);
}
function cargarListaProductosAdmin(data){
const cont = document.getElementById('lista-productos-admin');
if(!data || data.length === 0){ cont.innerHTML = '<p class="empty-state">Aún no has publicado productos.</p>'; return; }
cont.innerHTML = '';
data.forEach(p=>{
const precios = p.precios || [];
const resumenPrecios = precios.length ? precios.map(x=>`${x.precio} ${x.moneda}`).join(' · ') : 'Sin precio';
const row = document.createElement('div');
row.className = 'order-item';
row.innerHTML = `
<div class="order-icon">🛒</div>
<div><p class="order-name">${p.nombre}</p><p class="order-meta">${resumenPrecios}</p></div>
<button class="btn-cart" title="Editar" onclick='editarProducto(${JSON.stringify(p)})'>✏️</button>
<button class="btn-cart" title="Eliminar" onclick="eliminarProducto('${p.id}')">🗑️</button>
`;
cont.appendChild(row);
});
}
async function eliminarProducto(id){
if(!confirm('¿Seguro que quieres eliminar este producto? No se puede deshacer.')) return;
const { error } = await sb.from('productos').delete().eq('id', id);
if(error){ alert('No se pudo eliminar: ' + error.message); return; }
if(productoEditando === id) cancelarEdicionProducto();
cargarProductos();
}
function editarProducto(p){
productoEditando = p.id;
imagenActualProducto = p.imagen_url || null;
document.getElementById('a-img-file').value = '';
const prev = document.getElementById('a-img-preview');
if(p.imagen_url){ prev.src = p.imagen_url; prev.style.display='block'; } else { prev.style.display='none'; }
document.getElementById('a-nombre').value = p.nombre || '';
const precios = p.precios || [];
const buscar = (m)=> { const f = precios.find(x=>x.moneda===m); return f ? f.precio : ''; };
document.getElementById('a-precio-cup').value = buscar('CUP');
document.getElementById('a-precio-usdt').value = buscar('USDT');
document.getElementById('a-precio-usd').value = buscar('USD');
document.getElementById('a-desc').value = p.descripcion || '';
document.getElementById('btn-producto').textContent = 'Guardar cambios';
document.getElementById('btn-cancelar-producto').style.display = 'block';
document.getElementById('btn-eliminar-producto').style.display = 'block';
window.scrollTo({top:0, behavior:'smooth'});
}
function cancelarEdicionProducto(){
productoEditando = null;
imagenActualProducto = null;
document.getElementById('a-img-file').value = '';
document.getElementById('a-img-preview').style.display = 'none';
document.getElementById('a-nombre').value = '';
document.getElementById('a-precio-cup').value = '';
document.getElementById('a-precio-usdt').value = '';
document.getElementById('a-precio-usd').value = '';
document.getElementById('a-desc').value = '';
document.getElementById('btn-producto').textContent = 'Publicar producto';
document.getElementById('btn-cancelar-producto').style.display = 'none';
document.getElementById('btn-eliminar-producto').style.display = 'none';
}
let ordenPrecioAsc = false;
function toggleOrdenPrecio(){
ordenPrecioAsc = !ordenPrecioAsc;
document.getElementById('filtro-precio').classList.toggle('active', ordenPrecioAsc);
cargarProductos();
}
let datosTiendaCache = null;
async function crearEncargo(producto_id, nombreProducto){
if(!sesion){ alert('Primero inicia sesión'); showView('acceso', document.getElementById('tab-acceso')); return; }
if(!miPerfil || !miPerfil.whatsapp){ alert('Completa tu perfil (WhatsApp obligatorio) antes de encargar'); showView('perfil', document.querySelector('.nav-tab[data-view="perfil"]')); return; }
const { error } = await sb.from('encargos').insert({ usuario_id: sesion.user.id, producto_id, estado:'en_proceso' });
if(error){ alert('No se pudo crear el encargo: ' + error.message); return; }
// Notificación por WhatsApp al admin
if(datosTiendaCache && datosTiendaCache.whatsapp_admin){
const numero = datosTiendaCache.whatsapp_admin.replace(/[^0-9]/g,'');
const texto = encodeURIComponent(`Nuevo encargo en Pixel Store:\n${nombreProducto}\nCliente: ${miPerfil.nombre_real}\nWhatsApp: ${miPerfil.whatsapp}`);
window.open(`https://wa.me/${numero}?text=${texto}`, '_blank');
}
alert('¡Encargo enviado! Se abrió WhatsApp para confirmarlo con la tienda.');
}
async function agregarProducto(){
const nombre = document.getElementById('a-nombre').value.trim();
const descripcion = document.getElementById('a-desc').value.trim();
const pCup = document.getElementById('a-precio-cup').value.trim();
const pUsdt = document.getElementById('a-precio-usdt').value.trim();
const pUsd = document.getElementById('a-precio-usd').value.trim();
if(!nombre){ mostrarMsg('status-admin','Ponle un nombre al producto','error'); return; }
const precios = [];
if(pCup) precios.push({ moneda:'CUP', precio: parseFloat(pCup) });
if(pUsdt) precios.push({ moneda:'USDT', precio: parseFloat(pUsdt) });
if(pUsd) precios.push({ moneda:'USD', precio: parseFloat(pUsd) });
let imagen_url = productoEditando ? imagenActualProducto : null;
try{
const nuevaImg = await subirArchivo('a-img-file');
if(nuevaImg) imagen_url = nuevaImg;
} catch(e){
mostrarMsg('status-admin','No se pudo subir la foto: ' + (e.message || e), 'error');
return;
}
const payload = { nombre, descripcion, imagen_url: imagen_url || null, precios };
let error;
if(productoEditando){
({ error } = await sb.from('productos').update(payload).eq('id', productoEditando));
} else {
({ error } = await sb.from('productos').insert(payload));
}
if(error){ mostrarMsg('status-admin', error.message, 'error'); return; }
mostrarMsg('status-admin', productoEditando ? 'Producto actualizado ✔' : 'Producto publicado ✔', 'ok');
cancelarEdicionProducto();
cargarProductos();
}
let guiaEditando = null;
let imagenActualGuia = null;
async function cargarGuias(){
const cont = document.getElementById('guias-lista');
if(!sesion){
cont.innerHTML = `
<div style="background:var(--amber-soft);border:1px solid var(--amber);color:var(--amber);border-radius:10px;padding:10px 12px;font-size:12.5px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;">
<span>⚠️ Debes iniciar sesión o registrarte para ver el contenido de la Escuela.</span>
<button class="btn-order" style="padding:7px 14px;flex-shrink:0;" onclick="showView('acceso', document.getElementById('tab-acceso'))">Acceder</button>
</div>`;
return;
}
const { data, error } = await sb.from('guias').select('*').order('creado_en', { ascending:false });
if(error || !data || data.length === 0){
cont.innerHTML = '<p class="empty-state">Aún no hay guías publicadas.</p>';
} else {
cont.innerHTML = '';
data.forEach(g=>{
const div = document.createElement('div');
div.className = 'guia-item';
div.innerHTML = `
${g.imagen_url ? `<img class="guia-img" src="${g.imagen_url}" alt="">` : ''}
<div class="guia-texto">
<p class="guia-titulo">${g.titulo}</p>
<p class="guia-contenido">${linkify(g.contenido || '')}</p>
</div>`;
cont.appendChild(div);
});
}
if(miPerfil && miPerfil.es_admin) cargarListaGuiasAdmin(data || []);
}
function cargarListaGuiasAdmin(data){
const cont = document.getElementById('lista-guias-admin');
if(!data || data.length === 0){ cont.innerHTML = '<p class="empty-state">Aún no has publicado guías.</p>'; return; }
cont.innerHTML = '';
data.forEach(g=>{
const row = document.createElement('div');
row.className = 'order-item';
row.innerHTML = `
<div class="order-icon">📘</div>
<div><p class="order-name">${g.titulo}</p></div>
<button class="btn-cart" title="Editar" onclick='editarGuia(${JSON.stringify(g)})'>✏️</button>
<button class="btn-cart" title="Eliminar" onclick="eliminarGuia('${g.id}')">🗑️</button>
`;
cont.appendChild(row);
});
}
async function eliminarGuia(id){
if(!confirm('¿Seguro que quieres eliminar esta guía? No se puede deshacer.')) return;
const { error } = await sb.from('guias').delete().eq('id', id);
if(error){ alert('No se pudo eliminar: ' + error.message); return; }
if(guiaEditando === id) cancelarEdicionGuia();
cargarGuias();
}
function editarGuia(g){
guiaEditando = g.id;
imagenActualGuia = g.imagen_url || null;
document.getElementById('g-img-file').value = '';
const prev = document.getElementById('g-img-preview');
if(g.imagen_url){ prev.src = g.imagen_url; prev.style.display='block'; } else { prev.style.display='none'; }
document.getElementById('g-titulo').value = g.titulo || '';
document.getElementById('g-contenido').value = g.contenido || '';
document.getElementById('btn-guia').textContent = 'Guardar cambios';
document.getElementById('btn-cancelar-guia').style.display = 'block';
document.getElementById('btn-eliminar-guia').style.display = 'block';
window.scrollTo({top:0, behavior:'smooth'});
}
function cancelarEdicionGuia(){
guiaEditando = null;
imagenActualGuia = null;
document.getElementById('g-img-file').value = '';
document.getElementById('g-img-preview').style.display = 'none';
document.getElementById('g-titulo').value = '';
document.getElementById('g-contenido').value = '';
document.getElementById('btn-guia').textContent = 'Publicar guía';
document.getElementById('btn-cancelar-guia').style.display = 'none';
document.getElementById('btn-eliminar-guia').style.display = 'none';
}
async function agregarGuia(){
const titulo = document.getElementById('g-titulo').value.trim();
const contenido = document.getElementById('g-contenido').value.trim();
if(!titulo){ mostrarMsg('status-guia','Ponle un título a la guía','error'); return; }
let imagen_url = guiaEditando ? imagenActualGuia : null;
try{
const nuevaImg = await subirArchivo('g-img-file');
if(nuevaImg) imagen_url = nuevaImg;
} catch(e){
mostrarMsg('status-guia','No se pudo subir la foto: ' + (e.message || e), 'error');
return;
}
const payload = { titulo, contenido, imagen_url: imagen_url || null };
let error;
if(guiaEditando){
({ error } = await sb.from('guias').update(payload).eq('id', guiaEditando));
} else {
({ error } = await sb.from('guias').insert(payload));
}
if(error){ mostrarMsg('status-guia', error.message, 'error'); return; }
mostrarMsg('status-guia', guiaEditando ? 'Guía actualizada ✔' : 'Guía publicada ✔', 'ok');
cancelarEdicionGuia();
cargarGuias();
}
let torneoEditando = null;
let imagenActualTorneo = null;
async function cargarTorneos(){
const cont = document.getElementById('torneos-lista');
if(!sesion){
cont.innerHTML = `
<div style="background:var(--amber-soft);border:1px solid var(--amber);color:var(--amber);border-radius:10px;padding:10px 12px;font-size:12.5px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;">
<span>⚠️ Debes iniciar sesión o registrarte para ver los torneos.</span>
<button class="btn-order" style="padding:7px 14px;flex-shrink:0;" onclick="showView('acceso', document.getElementById('tab-acceso'))">Acceder</button>
</div>`;
torneosParaCarrusel = [];
refrescarCarrusel();
return;
}
const { data, error } = await sb.from('torneos').select('*').order('creado_en', { ascending:false });
if(error || !data || data.length === 0){
cont.innerHTML = '<p class="empty-state">Aún no hay torneos publicados.</p>';
torneosParaCarrusel = [];
refrescarCarrusel();
} else {
cont.innerHTML = '';
data.forEach(t=>{
const div = document.createElement('div');
div.className = 'guia-item';
div.innerHTML = `
${t.imagen_url ? `<img class="guia-img" src="${t.imagen_url}" alt="">` : ''}
<div class="guia-texto">
<p class="guia-titulo">${t.titulo}</p>
<p class="guia-contenido">${linkify(t.contenido || '')}</p>
</div>`;
cont.appendChild(div);
});
torneosParaCarrusel = data.filter(t=>t.imagen_url).map(t=>({ ...t, _tipo:'torneo' }));
refrescarCarrusel();
}
if(miPerfil && miPerfil.es_admin) cargarListaTorneosAdmin(data || []);
}
function cargarListaTorneosAdmin(data){
const cont = document.getElementById('lista-torneos-admin');
if(!data || data.length === 0){ cont.innerHTML = '<p class="empty-state">Aún no has publicado torneos.</p>'; return; }
cont.innerHTML = '';
data.forEach(t=>{
const row = document.createElement('div');
row.className = 'order-item';
row.innerHTML = `
<div class="order-icon">🏆</div>
<div><p class="order-name">${t.titulo}</p></div>
<button class="btn-cart" title="Editar" onclick='editarTorneo(${JSON.stringify(t)})'>✏️</button>
<button class="btn-cart" title="Eliminar" onclick="eliminarTorneo('${t.id}')">🗑️</button>
`;
cont.appendChild(row);
});
}
async function eliminarTorneo(id){
if(!confirm('¿Seguro que quieres eliminar este torneo? No se puede deshacer.')) return;
const { error } = await sb.from('torneos').delete().eq('id', id);
if(error){ alert('No se pudo eliminar: ' + error.message); return; }
if(torneoEditando === id) cancelarEdicionTorneo();
cargarTorneos();
}
function editarTorneo(t){
torneoEditando = t.id;
imagenActualTorneo = t.imagen_url || null;
document.getElementById('tr-img-file').value = '';
const prev = document.getElementById('tr-img-preview');
if(t.imagen_url){ prev.src = t.imagen_url; prev.style.display='block'; } else { prev.style.display='none'; }
document.getElementById('tr-titulo').value = t.titulo || '';
document.getElementById('tr-contenido').value = t.contenido || '';
document.getElementById('btn-torneo').textContent = 'Guardar cambios';
document.getElementById('btn-cancelar-torneo').style.display = 'block';
document.getElementById('btn-eliminar-torneo').style.display = 'block';
window.scrollTo({top:0, behavior:'smooth'});
}
function cancelarEdicionTorneo(){
torneoEditando = null;
imagenActualTorneo = null;
document.getElementById('tr-img-file').value = '';
document.getElementById('tr-img-preview').style.display = 'none';
document.getElementById('tr-titulo').value = '';
document.getElementById('tr-contenido').value = '';
document.getElementById('btn-torneo').textContent = 'Publicar torneo';
document.getElementById('btn-cancelar-torneo').style.display = 'none';
document.getElementById('btn-eliminar-torneo').style.display = 'none';
}
async function agregarTorneo(){
const titulo = document.getElementById('tr-titulo').value.trim();
const contenido = document.getElementById('tr-contenido').value.trim();
if(!titulo){ mostrarMsg('status-torneo','Ponle un título al torneo','error'); return; }
let imagen_url = torneoEditando ? imagenActualTorneo : null;
try{
const nuevaImg = await subirArchivo('tr-img-file');
if(nuevaImg) imagen_url = nuevaImg;
} catch(e){
mostrarMsg('status-torneo','No se pudo subir la foto: ' + (e.message || e), 'error');
return;
}
const payload = { titulo, contenido, imagen_url: imagen_url || null };
let error;
if(torneoEditando){
({ error } = await sb.from('torneos').update(payload).eq('id', torneoEditando));
} else {
({ error } = await sb.from('torneos').insert(payload));
}
if(error){ mostrarMsg('status-torneo', error.message, 'error'); return; }
mostrarMsg('status-torneo', torneoEditando ? 'Torneo actualizado ✔' : 'Torneo publicado ✔', 'ok');
cancelarEdicionTorneo();
cargarTorneos();
}
// ANUNCIOS
let anuncioEditando = null;
let imagenActualAnuncio = null;
function estadoAnuncio(a){
const hoy = new Date().toISOString().slice(0,10);
if(a.fecha_fin && hoy > a.fecha_fin) return 'Acabado';
if(a.fecha_inicio && hoy < a.fecha_inicio) return 'Próximo';
return 'Activo';
}
async function cargarAnuncios(){
const cont = document.getElementById('anuncios-lista');
if(!sesion){
cont.innerHTML = `
<div style="background:var(--amber-soft);border:1px solid var(--amber);color:var(--amber);border-radius:10px;padding:10px 12px;font-size:12.5px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;">
<span>⚠️ Debes iniciar sesión o registrarte para ver los anuncios.</span>
<button class="btn-order" style="padding:7px 14px;flex-shrink:0;" onclick="showView('acceso', document.getElementById('tab-acceso'))">Acceder</button>
</div>`;
anunciosParaCarrusel = [];
refrescarCarrusel();
return;
}
const { data, error } = await sb.from('anuncios').select('*').order('creado_en', { ascending:false });
if(error || !data || data.length === 0){
cont.innerHTML = '<p class="empty-state">Aún no hay anuncios publicados.</p>';
anunciosParaCarrusel = [];
refrescarCarrusel();
} else {
cont.innerHTML = '';
const colorEstado = { Activo:'status-listo', Próximo:'status-espera', Acabado:'' };
data.forEach(a=>{
const estado = estadoAnuncio(a);
const div = document.createElement('div');
div.className = 'guia-item';
div.innerHTML = `
${a.imagen_url ? `<img class="guia-img" src="${a.imagen_url}" alt="" style="${estado==='Acabado'?'filter:grayscale(1);opacity:.6;':''}">` : ''}
<div class="guia-texto">
<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px;">
<p class="guia-titulo" style="margin:0;">${a.titulo}</p>
<span class="order-status ${estado==='Acabado' ? '' : colorEstado[estado]}" style="${estado==='Acabado' ? 'background:var(--surface-2);color:var(--text-muted);' : ''}">${estado}</span>
</div>
<p class="guia-contenido">${linkify(a.contenido || '')}</p>
</div>`;
cont.appendChild(div);
});
anunciosParaCarrusel = data.filter(a=>a.imagen_url && estadoAnuncio(a)==='Activo').map(a=>({ ...a, _tipo:'anuncio' }));
refrescarCarrusel();
}
if(miPerfil && miPerfil.es_admin) cargarListaAnunciosAdmin(data || []);
}
function cargarListaAnunciosAdmin(data){
const cont = document.getElementById('lista-anuncios-admin');
if(!data || data.length === 0){ cont.innerHTML = '<p class="empty-state">Aún no has publicado anuncios.</p>'; return; }
cont.innerHTML = '';
data.forEach(a=>{
const estado = estadoAnuncio(a);
const row = document.createElement('div');