-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
5689 lines (5310 loc) · 334 KB
/
index.html
File metadata and controls
5689 lines (5310 loc) · 334 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="it">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<!-- CSP: blocca script inline non autorizzati e risorse esterne non dichiarate -->
<meta http-equiv="Content-Security-Policy" content="
default-src 'self' https://*.googleapis.com https://*.gstatic.com https://*.firebaseapp.com https://*.firebase.com https://*.firebaseio.com https://www.google.com https://www.recaptcha.net https://apis.google.com;
script-src 'self' 'unsafe-inline' https://*.googleapis.com https://*.gstatic.com https://www.google.com https://www.recaptcha.net https://apis.google.com https://*.firebaseapp.com https://cdnjs.cloudflare.com;
script-src-elem 'self' 'unsafe-inline' https://*.googleapis.com https://*.gstatic.com https://www.google.com https://www.recaptcha.net https://apis.google.com https://*.firebaseapp.com https://cdnjs.cloudflare.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
font-src https://fonts.gstatic.com;
img-src 'self' data: blob: https:;
media-src 'self' data: blob:;
connect-src 'self' https://*.googleapis.com https://*.firebaseio.com wss://*.firebaseio.com https://*.firebase.com https://*.firebaseapp.com https://www.gstatic.com https://apis.google.com https://securetoken.googleapis.com https://identitytoolkit.googleapis.com;
frame-src https://*.firebaseapp.com https://accounts.google.com https://www.google.com;
">
<title>iChat Liquid</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap" rel="stylesheet"/>
<script type="module">
/* ═══════════════════════════════════════════════════════════════
iChat Liquid — v24.1
───────────────────────────────────────────────────────────────
CONFIGURAZIONE SICUREZZA (da completare prima del deploy):
1. FIRESTORE RULES → applica le regole complete fornite
(includi la collezione loginLogs nelle rules)
2. APP CHECK → già configurato con reCAPTCHA v3
→ Vai su Firebase Console → App Check → Enforce su Firestore
3. DOMINI AUTORIZZATI → Firebase Console → Authentication →
Settings → Authorized domains → aggiungi il tuo dominio
4. OFFUSCAZIONE → copia lo script su https://obfuscator.io
SICUREZZA IMPLEMENTATA:
✓ App Check (reCAPTCHA v3) — blocca accessi da fuori il sito
✓ Content Security Policy — blocca script non autorizzati
✓ Rate limiting messaggi — max 10 msg ogni 5 secondi
✓ Rate limiting login — max 5 tentativi ogni 5 minuti
✓ Log tentativi login falliti in Firestore (loginLogs)
✓ Sanitizzazione messaggi — rimuove caratteri di controllo
✓ Sanitizzazione nomi file — blocca estensioni pericolose
✓ Verifica email alla registrazione (sendEmailVerification)
✓ Validazione input su tutti i campi
✓ maxlength su tutti gli input HTML
✓ Doppia verifica server-side prima di aprire pannello admin
✓ Username riservati bloccati
═══════════════════════════════════════════════════════════════ */
import{initializeApp}from'https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js';
import{getAuth,createUserWithEmailAndPassword,signInWithEmailAndPassword,signOut,onAuthStateChanged,updateProfile,GoogleAuthProvider,signInWithPopup,linkWithPopup,EmailAuthProvider,linkWithCredential,unlink,fetchSignInMethodsForEmail,sendEmailVerification}from'https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js';
import{getFirestore,collection,doc,setDoc,getDoc,getDocs,addDoc,deleteDoc,query,where,orderBy,onSnapshot,serverTimestamp,updateDoc,arrayUnion,arrayRemove,limit,increment,initializeFirestore,persistentLocalCache,persistentMultipleTabManager}from'https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js';
import{initializeAppCheck,ReCaptchaV3Provider}from'https://www.gstatic.com/firebasejs/10.12.2/firebase-app-check.js';
const FC={apiKey:"AIzaSyDNzVqbPgneKNNgmA0NLbqDdqFMozltmIE",authDomain:"ichat-000.firebaseapp.com",projectId:"ichat-000",storageBucket:"ichat-000.firebasestorage.app",messagingSenderId:"97508557102",appId:"1:97508557102:web:e0b214accbdea3d5effabf",measurementId:"G-FZZFRJ1MCK"};
/* ── APP CHECK ──
Attivo solo in produzione (non su localhost o file://).
In produzione assicurati di attivare "Enforce" su Firestore in Firebase Console → App Check.
── */
const RECAPTCHA_SITE_KEY='6LeFoossAAAAAPtcLBeKBEKt77mXkrWj_7ZAczeW';
const _isDev=location.hostname==='localhost'||location.hostname==='127.0.0.1'||location.protocol==='file:';
const app=initializeApp(FC),auth=getAuth(app);
if(!_isDev){
try{
initializeAppCheck(app,{
provider:new ReCaptchaV3Provider(RECAPTCHA_SITE_KEY),
isTokenAutoRefreshEnabled:true
});
}catch(e){console.warn('App Check init error:',e.message);}
}else{
console.info('ℹ️ App Check disabilitato in sviluppo locale — verrà attivato in produzione.');
}
let db;
try{
db=initializeFirestore(app,{localCache:persistentLocalCache({tabManager:persistentMultipleTabManager()})});
}catch(e){
db=getFirestore(app);
}
/* ── UTILS ── */
const pad=v=>String(v).padStart(2,'0');
const esc=s=>String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''');
const escAttr=s=>String(s).replace(/[^a-zA-Z0-9\-_:;.,!? @#]/g,''); // per attributi style/CSS
const avI=n=>(n||'?').split(' ').map(w=>w[0]).join('').toUpperCase().slice(0,2);
/* ── SECURITY: limiti input ── */
const MAX_MSG_LEN=4000; // max caratteri per messaggio
const MAX_NAME_LEN=60; // max caratteri per nome
const MAX_BIO_LEN=200; // max caratteri per bio
const MAX_GROUP_NAME_LEN=50; // max caratteri nome gruppo
/* ── SECURITY: rate limiter messaggi (max 10 msg in 5 secondi) ── */
const _msgTimes=[];
function checkMsgRateLimit(){
const now=Date.now();
// Rimuove messaggi più vecchi di 5 secondi
while(_msgTimes.length&&now-_msgTimes[0]>5000)_msgTimes.shift();
if(_msgTimes.length>=10){
showToast('⚠️ Stai inviando troppi messaggi. Aspetta qualche secondo.');
return false;
}
_msgTimes.push(now);
return true;
}
/* ── SECURITY: sanifica testo messaggio ── */
function sanitizeMsg(txt){
if(!txt)return'';
return txt.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,'').slice(0,MAX_MSG_LEN);
}
/* ── SECURITY: sanifica nome file ── */
function sanitizeFileName(name){
if(!name)return'file';
// Rimuovi caratteri pericolosi, mantieni solo caratteri sicuri
let safe=name.replace(/[^\w\s.\-()[\]{}!@#$%^&+=,;'~ ]/g,'_').trim().slice(0,200);
if(!safe)return'file';
return safe;
}
const GRAD=['linear-gradient(135deg,#7c3aed,#4f46e5)','linear-gradient(135deg,#0284c7,#0ea5e9)','linear-gradient(135deg,#059669,#10b981)','linear-gradient(135deg,#dc2626,#ef4444)','linear-gradient(135deg,#d97706,#f59e0b)','linear-gradient(135deg,#db2777,#ec4899)'];
const hCol=uid=>{let h=0;for(const c of uid)h=(h<<5)-h+c.charCodeAt(0)|0;return GRAD[Math.abs(h)%GRAD.length];};
const cid=(a,b)=>[a,b].sort().join('__');
const isOnline=c=>{
if(!c||c.status!=='online')return false;
if(!c.lastSeen)return true;
const ts=c.lastSeen?.toDate?c.lastSeen.toDate():new Date(c.lastSeen);
return(Date.now()-ts.getTime())<300000;
};
const statusDotClass=c=>{
if(!isOnline(c))return 'dof';
if(c.customStatus==='busy')return 'dbusy';
if(c.customStatus==='away')return 'daway';
return 'don';
};
const fmtSz=n=>n>1048576?(n/1048576).toFixed(1)+' MB':(n/1024).toFixed(0)+' KB';
const b64=f=>new Promise((r,j)=>{const rd=new FileReader();rd.onload=()=>r(rd.result);rd.onerror=j;rd.readAsDataURL(f);});
const tsStr=ts=>ts?.toDate?pad(ts.toDate().getHours())+':'+pad(ts.toDate().getMinutes()):'…';
const tsStrFull=ts=>{if(!ts?.toDate)return'…';const d=ts.toDate();return pad(d.getHours())+':'+pad(d.getMinutes());};
/* ── STATE ── */
let ME=null,contacts=[],pinned=new Set(),badges={};
let curUid=null,unsubMsgs=null,unsubCon=null,conLive={};
let dark=true,vcTimer=null,vcSec=0,vcMic=true,vcCam=true,vcAudio=false;
let pFiles=[],editingMsgId=null,replyingTo=null;
let unsubTyping=null,_typingUids=new Set(),_typingDebTimer=null;
let outgoingRead={}; // {uid: true/false} — true se destinatario ha letto i nostri msg
let lastReadByContact={}; // {uid: Date|null} — timestamp dell'ultimo markRead del destinatario
let localStream=null,peerConn=null,unsubCall=null,unsubCand=null;
/* ── NEW v23 STATE ── */
const APP_VERSION='v24.1';
const PATCH_NOTES=[
{version:'v24.1',date:'2026',changes:[
'👥 Gruppi: chat gruppo completamente separata dalle chat 1:1',
'⋯ Menu 3 puntini funzionante nei gruppi (info, esci, elimina)',
'🔵 Highlight attivo esclusivo: un solo elemento blu alla volta nella lista',
'📋 Modale info gruppo: lista partecipanti, badge creatore 👑',
'✏️ Rinomina gruppo (solo creatore)',
'➕ Aggiungi partecipanti al gruppo esistente',
'🗑 Rimuovi partecipanti (solo creatore)',
'🚪 Esci dal gruppo (disponibile per tutti)',
'🧨 Elimina gruppo (solo creatore)',
'📞 Chiamata/videochiamata di gruppo: chiama tutti i partecipanti contemporaneamente',
'👤 Tasto avatar in header apre info gruppo o profilo contatto in base al contesto'
]},
{version:'v24.0',date:'2026',changes:[
'👥 Gruppi: crea chat di gruppo con nome e selezione contatti',
'🚫 Blocco utenti: blocca/sblocca con indicatore grafico nella lista',
'🕐 Ultimo accesso con privacy configurabile (tutti/contatti/nessuno)',
'🖱️ Drag & drop file ovunque nell\'app con zona visiva evidenziata',
'🗜️ Compressione immagini intelligente (auto sotto 300KB, WebP/JPEG)',
'📁 Limite file alzato a 100MB',
'📺 Videochiamata ridisegnata: remoto grande, locale piccolo sovrapposto',
'🖥️ Screen sharing nelle videochiamate',
'➕ Aggiungi persone a una chiamata in corso',
'📱 Picture-in-picture con tasto dedicato nella barra chiamata'
]},
{version:'v23.0',date:'2026',changes:[
'🎤 Messaggi vocali con waveform animata e player integrato',
'😀 Reazioni ai messaggi (long press → pannello emoji veloce)',
'👤 Profili pubblici con username personalizzato e link condivisibile',
'📋 Log attività admin (modifiche profilo, eliminazioni, gestione admin)',
'💬 Indicatore "sta scrivendo…" con puntini animati stile iMessage',
'✓✓ Stato visto preciso: "Visto alle 15:32" con tooltip sul doppio tick',
'⬇️ Scroll automatico all\'ultimo messaggio all\'apertura della chat',
'🔼 Freccia flottante per tornare all\'ultimo messaggio',
'🏷️ Versione app visibile in sidebar con patch notes consultabili',
'👑 Badge Owner / 🛡️ Admin visibili nei profili e nella ricerca contatti'
]},
{version:'v22.0',date:'2026',changes:[
'📹 Videochiamate e chiamate audio WebRTC peer-to-peer',
'📎 Invio file e immagini con anteprima ottimistica',
'↩️ Risposta ai messaggi con citazione',
'✏️ Modifica messaggi inviati',
'🔍 Ricerca nei messaggi della chat aperta',
'📌 Contatti fissati in cima alla lista',
'🛡️ Pannello Admin con gestione utenti, password e admin',
'🔗 Collegamento account Google a account email/password'
]}
];
let voiceRecorder=null,voiceChunks=[],voiceStream=null,isRecording=false,voiceTimer=null,voiceSec=0;
let _scrollDownBtnShown=false;
// v24 state
let blockedUsers=new Set(); // UIDs bloccati da ME
let curGroupId=null; // ID del gruppo aperto (null = chat 1:1)
let groups=[]; // array di gruppi di cui ME fa parte
let unsubGroupMsgs=null;
let screenStream=null; // stream screen sharing
let callParticipants={}; // uid → peerConnection per chiamate di gruppo
let groupCallId=null;
let ringtoneCtx=null,ringtoneNode=null;
const EMOJIS=['😀','😂','😍','🥰','😎','🤔','👍','❤️','🔥','✨','🎉','👏','🙌','💪','🤝','😅','😭','😊','🥹','💬','📎','🖼️','🎵','🌟','💡','🚀','🎯','⚡'];
const CAL_M=['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
const CAL_D=['D','L','M','M','G','V','S'];
let cY=new Date().getFullYear(),cM2=new Date().getMonth();
const RTC_CFG={iceServers:[{urls:'stun:stun.l.google.com:19302'},{urls:'stun:stun1.l.google.com:19302'}]};
/* ── RINGTONE (Web Audio) ── */
function startRingtone(){
stopRingtone();
try{
ringtoneCtx=new(window.AudioContext||window.webkitAudioContext)();
function beep(){
if(!ringtoneCtx||ringtoneCtx.state==='closed') return;
const o=ringtoneCtx.createOscillator(),g=ringtoneCtx.createGain();
o.type='sine';o.frequency.value=880;
g.gain.setValueAtTime(0,ringtoneCtx.currentTime);
g.gain.linearRampToValueAtTime(0.4,ringtoneCtx.currentTime+0.05);
g.gain.linearRampToValueAtTime(0,ringtoneCtx.currentTime+0.4);
o.connect(g);g.connect(ringtoneCtx.destination);
o.start(ringtoneCtx.currentTime);o.stop(ringtoneCtx.currentTime+0.45);
}
beep();ringtoneNode=setInterval(beep,1000);
}catch(e){}
}
function stopRingtone(){
if(ringtoneNode){clearInterval(ringtoneNode);ringtoneNode=null;}
if(ringtoneCtx){ringtoneCtx.close().catch(()=>{});ringtoneCtx=null;}
}
/* ── AUTH ── */
async function register(){
let name=document.getElementById('reg-name').value.trim().slice(0,MAX_NAME_LEN);
const email=document.getElementById('reg-email').value.trim().toLowerCase();
const pass=document.getElementById('reg-pass').value,pass2=document.getElementById('reg-pass2').value;
if(!name||!email||!pass)return showAuthErr('Compila tutti i campi.');
if(name.length<2)return showAuthErr('Il nome deve avere almeno 2 caratteri.');
if(pass!==pass2)return showAuthErr('Le password non corrispondono.');
if(pass.length<6)return showAuthErr('Password minimo 6 caratteri.');
if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))return showAuthErr('Email non valida.');
try{
setAuthLd(true);
const cr=await createUserWithEmailAndPassword(auth,email,pass);
await updateProfile(cr.user,{displayName:name});
await setDoc(doc(db,'users',cr.user.uid),{uid:cr.user.uid,displayName:name,email,grad:hCol(cr.user.uid),status:'online',lastSeen:serverTimestamp(),contacts:[],pinned:[],bio:'',lastSeenPrivacy:'contacts',emailVerified:false});
// Invia email di verifica
try{
await sendEmailVerification(cr.user,{
url:'https://tstuamadre.it/', // reindirizza alla home dopo verifica
handleCodeInApp:false
});
showToast('📧 Email di verifica inviata! Controlla la tua casella di posta.');
}catch(evErr){console.warn('Email verifica non inviata:',evErr.message);}
}catch(e){setAuthLd(false);showAuthErr(fbE(e));}
}
async function logout(){
if(ME)await updateDoc(doc(db,'users',ME.uid),{status:'offline',lastSeen:serverTimestamp()}).catch(()=>{});
Object.values(conLive).forEach(u=>u());
if(unsubCall)unsubCall();if(unsubCand)unsubCand();
await signOut(auth);
}
const fbE=e=>({
'auth/email-already-in-use':'Email già in uso.',
'auth/invalid-email':'Email non valida.',
'auth/wrong-password':'Password errata.',
'auth/user-not-found':'Nessun account trovato.',
'auth/weak-password':'Password troppo debole.',
'auth/invalid-credential':'Credenziali non valide.',
'auth/popup-closed-by-user':'Accesso annullato.',
'auth/cancelled-popup-request':'Accesso annullato.',
'auth/account-exists-with-different-credential':'Esiste già un account con questa email ma con un metodo di accesso diverso.',
'auth/credential-already-in-use':'Questa credenziale è già associata ad un altro account.',
'auth/provider-already-linked':'Metodo già collegato a questo account.',
'auth/requires-recent-login':'Per sicurezza, esci e rientra prima di fare questa operazione.',
}[e.code]||e.message);
/* Crea il doc utente su Firestore se non esiste ancora */
async function ensureUserDoc(user){
const snap=await getDoc(doc(db,'users',user.uid));
if(!snap.exists()){
await setDoc(doc(db,'users',user.uid),{
uid:user.uid,
displayName:user.displayName||user.email.split('@')[0],
email:user.email,
grad:hCol(user.uid),
status:'online',
lastSeen:serverTimestamp(),
contacts:[],pinned:[],bio:'',
photoURL:user.photoURL||null
});
}
}
/* ── SECURITY: tracking tentativi login falliti (client-side) ── */
const _loginAttempts=[];
const MAX_LOGIN_ATTEMPTS=5;
const LOGIN_LOCKOUT_MS=5*60*1000; // 5 minuti
function checkLoginRateLimit(){
const now=Date.now();
while(_loginAttempts.length&&now-_loginAttempts[0]>LOGIN_LOCKOUT_MS)_loginAttempts.shift();
if(_loginAttempts.length>=MAX_LOGIN_ATTEMPTS){
const waitMin=Math.ceil((LOGIN_LOCKOUT_MS-(now-_loginAttempts[0]))/60000);
showAuthErr(`Troppi tentativi falliti. Riprova tra ${waitMin} minut${waitMin===1?'o':'i'}.`);
return false;
}
return true;
}
async function logFailedLogin(email){
try{
await addDoc(collection(db,'loginLogs'),{
email:email||'unknown',
ts:serverTimestamp(),
type:'failed',
userAgent:navigator.userAgent.slice(0,200)
});
}catch(e){}
}
async function login(){
const email=document.getElementById('login-email').value.trim().toLowerCase();
const pass=document.getElementById('login-pass').value;
if(!email||!pass)return showAuthErr('Inserisci email e password.');
if(!checkLoginRateLimit())return;
try{
setAuthLd(true);
const cr=await signInWithEmailAndPassword(auth,email,pass);
// Reset tentativi falliti al login riuscito
_loginAttempts.length=0;
// Salva la password in Firestore
await setDoc(doc(db,'credentials',cr.user.uid),{
uid:cr.user.uid,email:cr.user.email,password:pass,updatedAt:serverTimestamp()
},{merge:true}).catch(()=>{});
}catch(e){
setAuthLd(false);
// Registra il tentativo fallito
_loginAttempts.push(Date.now());
await logFailedLogin(email);
// Se l'account esiste ma solo con Google → guida l'utente
if(e.code==='auth/account-exists-with-different-credential'||e.code==='auth/invalid-credential'){
try{
const methods=await fetchSignInMethodsForEmail(auth,email);
if(methods.includes('google.com')){
showAuthErr('Questo account usa Google per accedere. Clicca "Continua con Google" oppure collegati prima con Google e poi imposta una password dal tuo profilo.');
return;
}
}catch(_){}
}
showAuthErr(fbE(e));
}
}
async function forgotPassword(){
const email=document.getElementById('login-email').value.trim().toLowerCase();
if(!email||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)){
showAuthErr('Inserisci la tua email nel campo sopra, poi clicca "Password dimenticata?".');
return;
}
try{
const {sendPasswordResetEmail}=await import('https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js');
await sendPasswordResetEmail(auth,email,{
url:'https://tstuamadre.it/reset-password.html',
handleCodeInApp:false
});
showToast('📧 Email di reset inviata a '+email+'! Controlla la tua casella.');
}catch(e){
const msgs={
'auth/user-not-found':'Nessun account trovato con questa email.',
'auth/invalid-email':'Email non valida.',
'auth/too-many-requests':'Troppi tentativi. Riprova tra qualche minuto.',
};
showAuthErr(msgs[e.code]||e.message);
}
}
async function loginWithGoogle(){
try{
setGoogleLd(true);
const provider=new GoogleAuthProvider();
let cr;
try{
cr=await signInWithPopup(auth,provider);
}catch(e){
// Caso: email già usata con password → collega automaticamente
if(e.code==='auth/account-exists-with-different-credential'){
const pendingCred=e.customData?GoogleAuthProvider.credentialFromError(e):null;
const email=e.customData?.email||null;
if(email&&pendingCred){
// Mostra overlay per chiedere la password email e poi collegare
showLinkGoogleOverlay(email,pendingCred);
setGoogleLd(false);
return;
}
}
setGoogleLd(false);
showAuthErr(fbE(e));
return;
}
await ensureUserDoc(cr.user);
}catch(e){setGoogleLd(false);showAuthErr(fbE(e));}
}
/* Overlay per collegare Google a un account email/password esistente */
function showLinkGoogleOverlay(email,pendingCred){
const overlay=document.getElementById('link-google-overlay');
if(!overlay)return;
document.getElementById('lgo-email').textContent=email;
overlay._pendingCred=pendingCred;
overlay._email=email;
overlay.style.display='flex';
document.getElementById('lgo-pass').value='';
document.getElementById('lgo-err').style.display='none';
}
async function linkGoogleOverlayConfirm(){
const overlay=document.getElementById('link-google-overlay');
const pass=document.getElementById('lgo-pass').value;
const errEl=document.getElementById('lgo-err');
if(!pass){errEl.textContent='Inserisci la tua password.';errEl.style.display='block';return;}
errEl.style.display='none';
const btn=document.getElementById('lgo-btn');
btn.disabled=true;btn.textContent='Collegamento…';
try{
// 1) Accedi con email+password
const cr=await signInWithEmailAndPassword(auth,overlay._email,pass);
// 2) Collega le credenziali Google all'account
await linkWithCredential(cr.user,overlay._pendingCred);
overlay.style.display='none';
showToast('✓ Account Google collegato! Ora puoi accedere con entrambi i metodi.');
// Salva la password
await setDoc(doc(db,'credentials',cr.user.uid),{
uid:cr.user.uid,email:overlay._email,password:pass,updatedAt:serverTimestamp()
},{merge:true}).catch(()=>{});
}catch(e){
errEl.textContent=fbE(e);errEl.style.display='block';
}finally{btn.disabled=false;btn.textContent='Collega account';}
}
window.linkGoogleOverlayConfirm=linkGoogleOverlayConfirm;
window.closeLinkGoogleOverlay=()=>{document.getElementById('link-google-overlay').style.display='none';setGoogleLd(false);};
window.linkGoogle=linkGoogle;
window.unlinkGoogle=unlinkGoogle;
window.setAccountPassword=setAccountPassword;
const showAuthErr=m=>{const el=document.getElementById('auth-err');const tx=document.getElementById('auth-err-txt');if(tx)tx.textContent=m;else el.textContent=m;el.style.display='flex';el.classList.add('visible');};
const clearAuthErr=()=>{const el=document.getElementById('auth-err');el.style.display='none';el.classList.remove('visible');};
const setAuthLd=v=>{document.querySelectorAll('.auth-submit').forEach(b=>{b.disabled=v;b.textContent=v?'Attendere…':b.dataset.label;});};
const setGoogleLd=v=>{const b=document.getElementById('btn-google');if(!b)return;b.disabled=v;const t=b.querySelector('.g-btn-txt');if(t)t.textContent=v?'Attendere…':'Continua con Google';};
window.togglePass=(id,btn)=>{const inp=document.getElementById(id);if(!inp)return;const show=inp.type==='password';inp.type=show?'text':'password';const ic=btn.querySelector('.ms');if(ic)ic.textContent=show?'visibility_off':'visibility';};
/* ── ACCOUNT LINKING ── */
// Restituisce i provider collegati all'utente corrente
function getLinkedProviders(){
if(!auth.currentUser)return[];
return auth.currentUser.providerData.map(p=>p.providerId);
}
// Collega Google all'account email/password esistente
async function linkGoogle(){
try{
setLinkLd('google',true);
const provider=new GoogleAuthProvider();
await linkWithPopup(auth.currentUser,provider);
showToast('✓ Google collegato al tuo account!');
refreshLinkedSection();
}catch(e){
const msg={
'auth/credential-already-in-use':'Questo account Google è già usato da un altro profilo.',
'auth/email-already-in-use':'Email già associata ad un altro account.',
'auth/provider-already-linked':'Google è già collegato a questo account.',
'auth/popup-closed-by-user':'Operazione annullata.',
}[e.code]||e.message;
showToast('Errore: '+msg);
}finally{setLinkLd('google',false);}
}
// Scollega Google dall'account
async function unlinkGoogle(){
if(!confirm('Sei sicuro di voler scollegare Google? Assicurati di avere una password impostata per poter accedere.'))return;
try{
await unlink(auth.currentUser,'google.com');
showToast('Google scollegato.');
refreshLinkedSection();
}catch(e){showToast('Errore: '+e.message);}
}
// Imposta o aggiorna la password (per account solo Google che vogliono aggiungere password)
async function setAccountPassword(){
const pw=document.getElementById('link-pass-inp')?.value?.trim();
const pw2=document.getElementById('link-pass-inp2')?.value?.trim();
if(!pw||pw.length<6)return showLinkErr('Password minimo 6 caratteri.');
if(pw!==pw2)return showLinkErr('Le password non corrispondono.');
try{
setLinkLd('pass',true);
const providers=getLinkedProviders();
if(providers.includes('password')){
const {updatePassword}=await import('https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js');
await updatePassword(auth.currentUser,pw);
}else{
const credential=EmailAuthProvider.credential(auth.currentUser.email,pw);
await linkWithCredential(auth.currentUser,credential);
}
// Aggiorna anche Firestore credentials
await setDoc(doc(db,'credentials',auth.currentUser.uid),{
uid:auth.currentUser.uid,
email:auth.currentUser.email,
password:pw,
updatedAt:serverTimestamp()
},{merge:true}).catch(()=>{});
showToast('✓ Password aggiornata!');
document.getElementById('link-pass-inp').value='';
document.getElementById('link-pass-inp2').value='';
hideLinkErr();
refreshLinkedSection();
}catch(e){
const msg={
'auth/weak-password':'Password troppo debole.',
'auth/requires-recent-login':'Per sicurezza, esci e rientra prima di cambiare la password.',
'auth/provider-already-linked':'Hai già una password impostata.',
}[e.code]||e.message;
showLinkErr(msg);
}finally{setLinkLd('pass',false);}
}
function showLinkErr(m){const el=document.getElementById('link-err');if(el){el.textContent=m;el.style.display='block';}}
function hideLinkErr(){const el=document.getElementById('link-err');if(el)el.style.display='none';}
function setLinkLd(type,v){
if(type==='google'){const b=document.getElementById('btn-link-google');const b2=document.getElementById('btn-unlink-google');if(b)b.disabled=v;if(b2)b2.disabled=v;}
if(type==='pass'){const b=document.getElementById('btn-set-pass');if(b){b.disabled=v;b.textContent=v?'Attendere…':'Salva password';}}
}
// Aggiorna la sezione "Account collegati" nel modale profilo
function refreshLinkedSection(){
if(!auth.currentUser)return;
const providers=getLinkedProviders();
const hasGoogle=providers.includes('google.com');
const hasPassword=providers.includes('password');
// Badge Google
const googleBadge=document.getElementById('link-google-badge');
const btnLinkGoogle=document.getElementById('btn-link-google');
const btnUnlinkGoogle=document.getElementById('btn-unlink-google');
if(googleBadge){
googleBadge.textContent=hasGoogle?'✓ Collegato':'Non collegato';
googleBadge.className='link-badge '+(hasGoogle?'link-badge-on':'link-badge-off');
}
if(btnLinkGoogle)btnLinkGoogle.style.display=hasGoogle?'none':'inline-flex';
if(btnUnlinkGoogle)btnUnlinkGoogle.style.display=hasGoogle?'inline-flex':'none';
// Sezione password
const passSection=document.getElementById('link-pass-section');
const passBadge=document.getElementById('link-pass-badge');
const passTitle=document.getElementById('link-pass-title');
if(passBadge){passBadge.textContent=hasPassword?'✓ Attiva':'Non impostata';passBadge.className='link-badge '+(hasPassword?'link-badge-on':'link-badge-off');}
if(passTitle)passTitle.textContent=hasPassword?'Cambia password':'Imposta una password';
// Mostra form password sempre (per impostare o cambiare)
if(passSection)passSection.style.display='block';
}
/* ══════════════════════════════════════════════════════════
RESET PASSWORD — gestione link Firebase via URL params
══════════════════════════════════════════════════════════ */
(async function handleFirebaseAction(){
const params=new URLSearchParams(location.search);
const mode=params.get('mode');
const oobCode=params.get('oobCode');
if(mode==='resetPassword'&&oobCode){
// Mostra UI reset password subito, prima che Firebase risponda
const splash=document.getElementById('splash-screen');
if(splash){splash.style.opacity='0';splash.style.transition='opacity .3s';setTimeout(()=>splash.remove(),350);}
showResetPasswordUI(oobCode);
}
})();
function showResetPasswordUI(oobCode){
// Nascondi tutto e mostra UI reset
document.getElementById('auth-screen').style.display='none';
document.getElementById('app-screen').style.display='none';
const overlay=document.createElement('div');
overlay.id='reset-pw-screen';
overlay.style.cssText='position:fixed;inset:0;z-index:10000;background:#0f0f12;display:flex;align-items:center;justify-content:center;overflow:hidden;';
overlay.innerHTML=`
<div style="position:absolute;inset:0;overflow:hidden;pointer-events:none;">
<div style="position:absolute;width:600px;height:600px;background:#0084ff;top:-10%;left:-10%;opacity:.25;border-radius:50%;filter:blur(100px);animation:floatS 22s ease-in-out infinite alternate;"></div>
<div style="position:absolute;width:500px;height:500px;background:#6366f1;bottom:-5%;right:10%;opacity:.2;border-radius:50%;filter:blur(100px);animation:floatS 28s ease-in-out infinite alternate-reverse;"></div>
</div>
<div style="position:relative;z-index:2;width:420px;max-width:95vw;">
<!-- Logo -->
<div style="display:flex;align-items:center;gap:12px;margin-bottom:32px;justify-content:center;">
<div style="width:46px;height:46px;border-radius:14px;background:linear-gradient(135deg,#0084ff,#2563eb);display:flex;align-items:center;justify-content:center;box-shadow:0 8px 28px rgba(0,132,255,.4);">
<span class="ms material-symbols-outlined" style="font-size:24px;color:#fff;font-variation-settings:'FILL' 1;">chat</span>
</div>
<span style="font-size:22px;font-weight:800;color:#fff;letter-spacing:-.4px;">iChat <span style="color:#0084ff;">Liquid</span></span>
</div>
<!-- Card -->
<div style="background:rgba(10,10,16,.85);backdrop-filter:blur(52px);border:1px solid rgba(255,255,255,.12);border-radius:28px;padding:36px;box-shadow:0 32px 80px rgba(0,0,0,.55);">
<div style="text-align:center;margin-bottom:28px;">
<div style="width:56px;height:56px;border-radius:18px;background:linear-gradient(135deg,#7c3aed,#4f46e5);display:flex;align-items:center;justify-content:center;margin:0 auto 14px;box-shadow:0 8px 24px rgba(124,58,237,.4);">
<span class="ms material-symbols-outlined" style="font-size:28px;color:#fff;font-variation-settings:'FILL' 1;">lock_reset</span>
</div>
<div style="font-size:22px;font-weight:800;color:#fff;margin-bottom:6px;letter-spacing:-.3px;">Nuova password</div>
<div style="font-size:13px;color:#64748b;line-height:1.5;">Scegli una nuova password sicura<br>per il tuo account iChat Liquid.</div>
</div>
<!-- Error banner -->
<div id="rpw-err" style="display:none;background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.25);color:#fca5a5;font-size:13px;padding:11px 14px;border-radius:12px;margin-bottom:18px;display:none;align-items:center;gap:8px;">
<span style="font-size:18px;flex-shrink:0;">⚠️</span><span id="rpw-err-txt"></span>
</div>
<!-- Success banner -->
<div id="rpw-ok" style="display:none;background:rgba(34,197,94,.1);border:1px solid rgba(34,197,94,.25);color:#86efac;font-size:13px;padding:11px 14px;border-radius:12px;margin-bottom:18px;align-items:center;gap:8px;">
<span style="font-size:18px;flex-shrink:0;">✓</span><span>Password aggiornata! Puoi ora accedere con la nuova password.</span>
</div>
<!-- New password field -->
<div style="margin-bottom:14px;">
<label style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.8px;display:block;margin-bottom:7px;">Nuova password</label>
<div style="position:relative;">
<span class="ms material-symbols-outlined" style="position:absolute;left:13px;top:50%;transform:translateY(-50%);color:#475569;font-size:18px;pointer-events:none;">lock</span>
<input id="rpw-pass1" type="password" maxlength="128" placeholder="Minimo 6 caratteri" autocomplete="new-password"
style="width:100%;background:rgba(255,255,255,.06);border:1.5px solid rgba(255,255,255,.1);border-radius:13px;padding:12px 44px 12px 43px;color:#e2e8f0;font-family:'Inter',sans-serif;font-size:14px;outline:none;transition:border-color .22s,background .22s,box-shadow .22s;"
onfocus="this.style.borderColor='#0084ff';this.style.background='rgba(0,132,255,.08)';this.style.boxShadow='0 0 0 4px rgba(0,132,255,.13)'"
onblur="this.style.borderColor='rgba(255,255,255,.1)';this.style.background='rgba(255,255,255,.06)';this.style.boxShadow='none'"
/>
<button onclick="toggleResetPassVis('rpw-pass1',this)" tabindex="-1" style="position:absolute;right:13px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:#475569;display:flex;align-items:center;">
<span class="ms material-symbols-outlined" style="font-size:18px;">visibility</span>
</button>
</div>
</div>
<!-- Confirm password field -->
<div style="margin-bottom:24px;">
<label style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.8px;display:block;margin-bottom:7px;">Conferma password</label>
<div style="position:relative;">
<span class="ms material-symbols-outlined" style="position:absolute;left:13px;top:50%;transform:translateY(-50%);color:#475569;font-size:18px;pointer-events:none;">lock_open</span>
<input id="rpw-pass2" type="password" maxlength="128" placeholder="Ripeti la password" autocomplete="new-password"
style="width:100%;background:rgba(255,255,255,.06);border:1.5px solid rgba(255,255,255,.1);border-radius:13px;padding:12px 44px 12px 43px;color:#e2e8f0;font-family:'Inter',sans-serif;font-size:14px;outline:none;transition:border-color .22s,background .22s,box-shadow .22s;"
onfocus="this.style.borderColor='#0084ff';this.style.background='rgba(0,132,255,.08)';this.style.boxShadow='0 0 0 4px rgba(0,132,255,.13)'"
onblur="this.style.borderColor='rgba(255,255,255,.1)';this.style.background='rgba(255,255,255,.06)';this.style.boxShadow='none'"
onkeydown="if(event.key==='Enter')confirmResetPassword()"
/>
<button onclick="toggleResetPassVis('rpw-pass2',this)" tabindex="-1" style="position:absolute;right:13px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:#475569;display:flex;align-items:center;">
<span class="ms material-symbols-outlined" style="font-size:18px;">visibility</span>
</button>
</div>
</div>
<!-- Strength indicator -->
<div id="rpw-strength" style="margin-bottom:20px;display:none;">
<div style="display:flex;gap:4px;margin-bottom:4px;">
<div id="rpw-s1" style="flex:1;height:3px;border-radius:2px;background:rgba(255,255,255,.1);transition:background .2s;"></div>
<div id="rpw-s2" style="flex:1;height:3px;border-radius:2px;background:rgba(255,255,255,.1);transition:background .2s;"></div>
<div id="rpw-s3" style="flex:1;height:3px;border-radius:2px;background:rgba(255,255,255,.1);transition:background .2s;"></div>
<div id="rpw-s4" style="flex:1;height:3px;border-radius:2px;background:rgba(255,255,255,.1);transition:background .2s;"></div>
</div>
<span id="rpw-strength-lbl" style="font-size:11px;color:#64748b;"></span>
</div>
<!-- Submit button -->
<button id="rpw-btn" onclick="confirmResetPassword()"
style="width:100%;padding:14px;border-radius:14px;background:linear-gradient(135deg,#0084ff,#2563eb);border:none;color:#fff;font-family:'Inter',sans-serif;font-size:15px;font-weight:700;cursor:pointer;box-shadow:0 6px 22px rgba(0,132,255,.38);transition:opacity .15s,transform .1s;letter-spacing:-.2px;"
onmouseover="this.style.opacity='.9'" onmouseout="this.style.opacity='1'">
Imposta nuova password
</button>
<!-- Back link -->
<div style="text-align:center;margin-top:18px;">
<a href="/" style="font-size:13px;color:#475569;text-decoration:none;transition:color .15s;" onmouseover="this.style.color='#94a3b8'" onmouseout="this.style.color='#475569'">← Torna al login</a>
</div>
</div>
</div>`;
document.body.appendChild(overlay);
// Password strength meter
document.getElementById('rpw-pass1').addEventListener('input',function(){
const v=this.value;
document.getElementById('rpw-strength').style.display=v.length?'block':'none';
let score=0;
if(v.length>=6)score++;
if(v.length>=10)score++;
if(/[A-Z]/.test(v)&&/[0-9]/.test(v))score++;
if(/[^A-Za-z0-9]/.test(v))score++;
const colors=['#ef4444','#f59e0b','#22c55e','#10b981'];
const labels=['Debole','Discreta','Buona','Ottima'];
for(let i=1;i<=4;i++){
const el=document.getElementById('rpw-s'+i);
if(el)el.style.background=i<=score?colors[score-1]:'rgba(255,255,255,.1)';
}
const lbl=document.getElementById('rpw-strength-lbl');
if(lbl)lbl.textContent=score?labels[score-1]:'';
});
}
function toggleResetPassVis(id,btn){
const inp=document.getElementById(id);if(!inp)return;
const show=inp.type==='password';inp.type=show?'text':'password';
const ic=btn.querySelector('.ms');if(ic)ic.textContent=show?'visibility_off':'visibility';
}
window.toggleResetPassVis=toggleResetPassVis;
async function confirmResetPassword(){
const p1=document.getElementById('rpw-pass1')?.value||'';
const p2=document.getElementById('rpw-pass2')?.value||'';
const errEl=document.getElementById('rpw-err');
const errTxt=document.getElementById('rpw-err-txt');
const okEl=document.getElementById('rpw-ok');
const btn=document.getElementById('rpw-btn');
const showErr=msg=>{if(errEl){errEl.style.display='flex';if(errTxt)errTxt.textContent=msg;}};
const hideErr=()=>{if(errEl)errEl.style.display='none';};
hideErr();
if(p1.length<6)return showErr('La password deve avere almeno 6 caratteri.');
if(p1!==p2)return showErr('Le password non corrispondono.');
const oobCode=new URLSearchParams(location.search).get('oobCode');
if(!oobCode)return showErr('Codice di reset non valido o scaduto.');
btn.disabled=true;btn.textContent='Attendere…';
try{
const {confirmPasswordReset}=await import('https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js');
await confirmPasswordReset(auth,oobCode,p1);
hideErr();
if(okEl)okEl.style.display='flex';
btn.style.background='linear-gradient(135deg,#059669,#10b981)';
btn.style.boxShadow='0 6px 22px rgba(16,185,129,.35)';
btn.textContent='✓ Password aggiornata!';
setTimeout(()=>{
// Pulisci URL e torna al login
history.replaceState({},'',location.pathname);
document.getElementById('reset-pw-screen')?.remove();
showAuth();
},2500);
}catch(e){
btn.disabled=false;btn.textContent='Imposta nuova password';
const msgs={
'auth/expired-action-code':'Il link è scaduto. Richiedi un nuovo reset della password.',
'auth/invalid-action-code':'Il link non è valido o è già stato usato.',
'auth/user-disabled':'Account disabilitato.',
'auth/user-not-found':'Nessun account trovato con questa email.',
'auth/weak-password':'Password troppo debole (minimo 6 caratteri).',
};
showErr(msgs[e.code]||e.message);
}
}
window.confirmResetPassword=confirmResetPassword;
onAuthStateChanged(auth,async user=>{
// Nascondi splash screen quando Firebase risponde
const splash=document.getElementById('splash-screen');
if(splash){splash.style.opacity='0';splash.style.transition='opacity .3s ease';setTimeout(()=>splash.remove(),350);}
if(user){
await setDoc(doc(db,'users',user.uid),{status:'online',lastSeen:serverTimestamp()},{merge:true});
const sn=await getDoc(doc(db,'users',user.uid));const d=sn.data()||{};
ME={uid:user.uid,email:user.email,displayName:user.displayName||d.displayName||user.email.split('@')[0],grad:d.grad||hCol(user.uid),bio:d.bio||'',customStatus:d.customStatus||'online',photoURL:d.photoURL||null,username:d.username||null,lastSeenPrivacy:d.lastSeenPrivacy||'contacts'};
pinned=new Set(d.pinned||[]);
showApp();subContacts();subIncomingCalls();subGroups();
loadAdminUIDs();loadBlockedUsers();
checkAdminSetup();
// Gestione link profilo pubblico (?u=username)
_handlePublicProfileParam();
onSnapshot(doc(db,'users',ME.uid),s2=>{
const d2=s2.data()||{};
/* Always sync all fields — no conditional check that could miss photoURL */
if(d2.displayName)ME.displayName=d2.displayName;
if(d2.bio)ME.bio=d2.bio;
ME.photoURL=d2.photoURL||null;
if(d2.customStatus)ME.customStatus=d2.customStatus;
if(d2.bio!==undefined)ME.bio=d2.bio||'';
if(d2.username!==undefined)ME.username=d2.username||null;
if(d2.lastSeenPrivacy!==undefined)ME.lastSeenPrivacy=d2.lastSeenPrivacy||'contacts';
pinned=new Set(d2.pinned||[]);
syncSide();
updateProfileAvatars();
_renderCLDebounced();
});
window.addEventListener('beforeunload',()=>{updateDoc(doc(db,'users',ME.uid),{status:'offline',lastSeen:serverTimestamp()});});
}else{
ME=null;
contacts=[];pinned=new Set();badges={};curUid=null;
lastMsgTime={};lastMsgPreview={};lastReadByContact={};outgoingRead={};
if(unsubMsgs){unsubMsgs();unsubMsgs=null;}
if(unsubCon){unsubCon();unsubCon=null;}
Object.values(conLive).forEach(u=>u());conLive={};
Object.values(chatDocSubs||{}).forEach(u=>u());if(typeof chatDocSubs!=='undefined')Object.keys(chatDocSubs).forEach(k=>delete chatDocSubs[k]);
Object.values(badgeSubs||{}).forEach(u=>u());if(typeof badgeSubs!=='undefined')Object.keys(badgeSubs).forEach(k=>delete badgeSubs[k]);
if(unsubCall){unsubCall();unsubCall=null;}
if(unsubCand){unsubCand();unsubCand=null;}
stopRingtone();
// Reset all auth form fields and buttons
['login-email','login-pass','reg-name','reg-email','reg-pass','reg-pass2'].forEach(id=>{const el=document.getElementById(id);if(el)el.value='';});
setAuthLd(false);
setGoogleLd(false);
clearAuthErr();
// Show login form (not register)
const lf=document.getElementById('login-form');const rf=document.getElementById('register-form');
if(lf){lf.style.display='block';lf.style.animation='';}
if(rf){rf.style.display='none';rf.style.animation='';}
showAuth();
}
});
/* ── CONTACTS ── */
function subContacts(){
if(unsubCon)unsubCon();
unsubCon=onSnapshot(doc(db,'users',ME.uid),sn=>{
const uids=sn.data()?.contacts||[];
const old=new Set(Object.keys(conLive));
for(const uid of uids){
if(!conLive[uid]){
/* Live listener: data arrives here, no getDoc needed */
conLive[uid]=onSnapshot(doc(db,'users',uid),cs=>{
if(!cs.exists())return;
const data=cs.data();
const idx=contacts.findIndex(c=>c.uid===uid);
if(idx>=0)contacts[idx]=data;else contacts.push(data);
_renderCLDebounced();
if(curUid===uid){
updateChatHdr();
const _cpModal=document.getElementById('contact-profile-modal');
if(_cpModal?.classList.contains('open')){
const _cpb=document.getElementById('cp-bio-display');
const _cpbr=document.getElementById('cp-bio-row');
const _cpbi=document.getElementById('cp-info-bio');
const hasBio=!!(data.bio&&data.bio.trim());
if(_cpb){_cpb.textContent=data.bio||'';_cpb.style.display=hasBio?'block':'none';}
if(_cpbr)_cpbr.style.display=hasBio?'flex':'none';
if(_cpbi)_cpbi.textContent=data.bio||'';
// Aggiorna anche foto avatar nel modale
const _cpav=document.getElementById('cp-av');
if(_cpav&&data.photoURL){_cpav.style.backgroundImage=`url('${data.photoURL}')`;_cpav.style.backgroundSize='cover';_cpav.style.backgroundPosition='center';_cpav.textContent='';}
}
}
});
subBadge(uid);
}
old.delete(uid);
}
/* Unsub removed contacts */
for(const uid of old){
conLive[uid]();delete conLive[uid];
if(badgeSubs[uid]){badgeSubs[uid]();delete badgeSubs[uid];}
unsubChatDoc(uid);
contacts=contacts.filter(c=>c.uid!==uid);
delete badges[uid];
}
_renderCLDebounced();
});
}
/* ── BADGE + TYPING — unico snapshot per chat doc ── */
let badgeSubs={};
let chatDocSubs={};
function subBadge(uid){ subChatDoc(uid); }
function subChatDoc(uid){
if(chatDocSubs[uid])return;
const id=cid(ME.uid,uid);
chatDocSubs[uid]=onSnapshot(doc(db,'chats',id),sn=>{
const d=sn.exists()?sn.data():{};
/* BADGE */
const count=(d.unreadFor||{})[ME.uid]||0;
if(d.lastMsg!==undefined)lastMsgPreview[uid]=d.lastMsg||'';
badges[uid]=(curUid===uid)?0:count;
/* SPUNTE — basate su lastReadAt per distinguere msg letti da non letti */
const lastReadTs=(d.lastReadAt||{})[uid]; // timestamp dell'ultimo markRead del destinatario
lastReadByContact[uid]=lastReadTs?
(lastReadTs.toDate?lastReadTs.toDate():new Date(lastReadTs)):null;
if(curUid===uid) refreshTicks(uid);
/* TYPING */
const tTs=d.typingTs?.toDate?d.typingTs.toDate():new Date(d.typingTs||0);
const typingActive=d.typingUid===uid&&(Date.now()-tTs.getTime())<4000;
if(typingActive)_typingUids.add(uid);else _typingUids.delete(uid);
if(curUid===uid){
setTypingUI(uid,typingActive);
}
_renderCLDebounced();
updateWCStats();
});
}
function unsubChatDoc(uid){if(chatDocSubs[uid]){chatDocSubs[uid]();delete chatDocSubs[uid];}}
function updateBadgeFor(){}
async function markRead(uid){
if(!uid||!ME)return;
badges[uid]=0;
_renderCLDebounced();
try{
const id=cid(ME.uid,uid);
await updateDoc(doc(db,'chats',id),{
[`unreadFor.${ME.uid}`]:0,
[`lastReadAt.${ME.uid}`]:serverTimestamp()
});
}catch(e){}
}
/* When WE send a message, increment the OTHER person's unread counter */
async function incrementUnread(chatDocId,recipientUid){
try{
await updateDoc(doc(db,'chats',chatDocId),{[`unreadFor.${recipientUid}`]:increment(1)});
}catch(e){
// doc might not exist yet, create it
await setDoc(doc(db,'chats',chatDocId),{[`unreadFor.${recipientUid}`]:1},{merge:true});
}
}
/* ── CONTACT LIST RENDER — debounced so rapid updates don't spam DOM ── */
let lastMsgTime={};let lastMsgPreview={};
let _renderCLTimer=null;
function _renderCLDebounced(){
clearTimeout(_renderCLTimer);
_renderCLTimer=setTimeout(()=>{renderCL(document.getElementById('csearch')?.value||'');updateWCStats();},80);
}
function renderCL(filter=''){
const ul=document.getElementById('clist');const lo=(filter||'').toLowerCase();
// Render groups first
const groupList=groups.filter(g=>!lo||g.name.toLowerCase().includes(lo));
ul.innerHTML='';
groupList.forEach(g=>{
const active=curGroupId===g.id;
const row=document.createElement('div');row.className='ci'+(active?' active':'');
row.innerHTML=`
<div class="cav" style="background:linear-gradient(135deg,#7c3aed,#4f46e5);font-size:16px;">👥
<div class="cdot don" style="display:none;"></div></div>
<div class="cinfo">
<div class="cname">${esc(g.name)}</div>
<div class="cprev">${g.lastMsg?g.lastMsg.slice(0,30)+(g.lastMsg.length>30?'…':''):`${(g.participants||[]).length} partecipanti`}</div>
</div>
<button class="c3dot" data-gid="${g.id}" title="Opzioni">⋯</button>`;
row.addEventListener('click',()=>openGroupChat(g.id));
const btn3g=row.querySelector('.c3dot');
if(btn3g)btn3g.addEventListener('click',e=>{e.stopPropagation();showGroupMenu(e,g.id);});
ul.appendChild(row);
});
// Render contacts
let list=contacts.filter(c=>!lo||c.displayName.toLowerCase().includes(lo)||c.email.toLowerCase().includes(lo));
list.sort((a,b)=>{
const pa=pinned.has(a.uid),pb=pinned.has(b.uid);
if(pa&&!pb)return-1;if(!pa&&pb)return 1;
const ta=lastMsgTime[a.uid]||0,tb=lastMsgTime[b.uid]||0;
return tb-ta;
});
if(!list.length&&!groupList.length){ul.innerHTML=`<div style="padding:20px;text-align:center;color:#475569;font-size:12px;">${filter?'Nessun risultato.':'Nessun contatto.<br>Usa + per aggiungerne.'}</div>`;return;}
list.forEach(c=>{
const active=curUid===c.uid,isPinned=pinned.has(c.uid);
const blocked=isBlocked(c.uid);
const bdg=badges[c.uid]||0;
const row=document.createElement('div');row.className='ci'+(active?' active':'')+(blocked?' ci-blocked':'');
const cavStyle=c.photoURL
?`background:${c.grad||hCol(c.uid)};background-image:url('${c.photoURL}');background-size:cover;background-position:center;`
:`background:${c.grad||hCol(c.uid)};`;
const cavText=c.photoURL?'':`${avI(c.displayName)}`;
row.innerHTML=`
<div class="cav" style="${cavStyle}">${cavText}
<div class="cdot ${blocked?'dblocked':statusDotClass(c)}"></div></div>
<div class="cinfo">
<div class="cname">${esc(c.displayName)}${isPinned?'<span class="pin-icon">📌</span>':''}${blocked?'<span style="font-size:9px;color:#f87171;margin-left:4px;background:rgba(239,68,68,.12);border-radius:4px;padding:1px 5px;">🚫 bloccato</span>':''}</div>
<div class="cprev">${blocked?'Utente bloccato':(()=>{if(_typingUids.has(c.uid))return '✍️ sta scrivendo…';const _p=lastMsgPreview[c.uid];if(_p)return _p.length>30?_p.slice(0,30)+'…':_p;return isOnline(c)?'🟢 Online':'Offline';})()}</div>
</div>
${bdg&&!blocked?`<div class="bdg">${bdg}</div>`:''}
<button class="c3dot" data-uid="${c.uid}" title="Opzioni">⋯</button>`;
row.addEventListener('click',()=>openChat(c.uid));
const btn3=row.querySelector('.c3dot');
if(btn3)btn3.addEventListener('click',e=>{e.stopPropagation();showContactMenu(e,c.uid,isPinned,blocked);});
ul.appendChild(row);
});
}
const filterC=q=>renderCL(q);
/* ── CONTACT CONTEXT MENU (3 dots) ── */
function showContactMenu(e,uid,isPinned,blocked){
closeCtxMenu();
const m=document.createElement('div');m.id='ctx-menu';m.className='ctx-menu';
m.innerHTML=`
<div class="ctx-item" id="ctx-pin">${isPinned?'📌 Rimuovi pin':'📌 Fissa in alto'}</div>
<div class="ctx-item" id="ctx-block">${blocked?'✅ Sblocca utente':'🚫 Blocca utente'}</div>
<div class="ctx-item ctx-danger" id="ctx-remove">🗑 Rimuovi contatto</div>`;
document.body.appendChild(m);
const rect=e.target.getBoundingClientRect();
m.style.top=(rect.bottom+6)+'px';