Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2951 lines (2744 loc) · 180 KB
/
Copy pathscript.js
File metadata and controls
2951 lines (2744 loc) · 180 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
/*
Application script: small improvements for reliability and performance.
- Guards DOM operations so pages that don't include certain elements won't throw.
- Provides same function names used in HTML for compatibility.
- Uses DOMContentLoaded and event delegation where appropriate.
*/
(function () {
'use strict';
// Lightweight localStorage tamper-detection wrapper
// Wraps Storage.prototype.setItem/getItem so stored values include a simple checksum.
// Not cryptographically secure — helpful to detect accidental or manual tampering.
(function hardenLocalStorage(){
try{
const originalSet = Storage.prototype.setItem;
const originalGet = Storage.prototype.getItem;
const originalRemove = Storage.prototype.removeItem;
// simple checksum: 32-bit sum of char codes, hex
function computeChecksum(str){
if (!str) return '0';
let sum = 0;
for (let i=0;i<str.length;i++) sum = (sum + str.charCodeAt(i)) >>> 0;
return sum.toString(16);
}
Storage.prototype.setItem = function(key, value){
try{
// ensure value is a string
const s = (typeof value === 'string') ? value : String(value);
const payload = JSON.stringify({ __bt_wrapped: 1, v: s, c: computeChecksum(s) });
return originalSet.call(this, key, payload);
}catch(e){ return originalSet.call(this, key, value); }
};
Storage.prototype.getItem = function(key){
try{
const raw = originalGet.call(this, key);
if (!raw) return raw;
// try parse — if it's our wrapped object, verify checksum and return inner value string
try{
const obj = JSON.parse(raw);
if (obj && obj.__bt_wrapped){
const v = obj.v || '';
const c = obj.c || '';
if (computeChecksum(v) === c){
return v;
} else {
// tamper detected
window.localStorageTampered = true;
try{ if (window.showToast) window.showToast('LocalStorage tamper detected for ' + key, 'danger'); }catch(e){}
return null;
}
}
}catch(e){ /* not JSON / not wrapped */ }
return raw;
}catch(e){ return originalGet.call(this, key); }
};
Storage.prototype.removeItem = function(key){ try{ return originalRemove.call(this,key); }catch(e){ return originalRemove.call(this,key); } };
// expose helpers
window.localStorageHardened = true;
}catch(e){ console.warn('Failed to harden localStorage', e); }
})();
// safe query helpers
function $(id) { return document.getElementById(id); }
function text(id, value) { const el = $(id); if (!el) return; el.innerText = value; }
// Resize image (File or dataURL) to limit dimensions and reduce size. Returns dataURL (JPEG or original mime if small)
async function resizeImageDataURL(input, maxDim = 256, quality = 0.75){
return new Promise((resolve)=>{
try{
const toImage = (src)=>{
const img = new Image();
img.onload = ()=>{
try{
const w = img.naturalWidth, h = img.naturalHeight;
if (!w || !h) return resolve(null);
let nw = w, nh = h;
if (Math.max(w,h) > maxDim){
if (w >= h){ nw = maxDim; nh = Math.round(h * (maxDim / w)); }
else { nh = maxDim; nw = Math.round(w * (maxDim / h)); }
}
const c = document.createElement('canvas'); c.width = nw; c.height = nh;
const ctx = c.getContext('2d');
// draw with smoothing
ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high';
ctx.clearRect(0,0,nw,nh);
ctx.drawImage(img, 0, 0, nw, nh);
// always produce JPEG to keep size small; quality param helps
const dataUrl = c.toDataURL('image/jpeg', quality);
resolve(dataUrl);
}catch(err){ console.warn('resizeImage error', err); resolve(null); }
};
img.onerror = ()=> resolve(null);
img.src = src;
};
if (!input) return resolve(null);
// If input is a File
if (typeof File !== 'undefined' && input instanceof File){
const fr = new FileReader();
fr.onload = ()=> toImage(fr.result);
fr.onerror = ()=> resolve(null);
fr.readAsDataURL(input);
return;
}
// If input is already a dataURL
if (typeof input === 'string' && input.indexOf('data:') === 0){
toImage(input); return;
}
// Unknown type
resolve(null);
}catch(e){ console.warn('resizeImageDataURL failed', e); resolve(null); }
});
}
// Loading animation (if present)
document.addEventListener('DOMContentLoaded', () => {
const loader = $('loader');
const content = $('content');
if (loader) {
setTimeout(() => {
loader.classList.add('fade-out');
if (content) content.style.display = 'block';
setTimeout(() => loader.remove(), 1200);
}, 600);
}
// register service worker non-blocking
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js').catch(() => {});
}
// initialize theme toggle (adds a small button in .topbar)
try { if (typeof initTheme === 'function') initTheme(); } catch (e) { /* ignore */ }
// Add iOS safe-area helper class to body when running on iOS devices
try {
const ua = navigator.userAgent || navigator.vendor || window.opera || '';
const iOS = /iP(ad|hone|od)/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
if (iOS) document.body.classList.add('ios');
} catch (e) { /* ignore */ }
// API helper: attach access token, auto-refresh using refresh token when available
async function apiFetch(path, opts){
const ep = (localStorage.getItem('bt_api_endpoint') || window.BT_API_ENDPOINT || '').replace(/\/$/, '');
if (!ep) throw new Error('No API endpoint configured');
const headers = Object.assign({}, (opts && opts.headers) || {});
const access = localStorage.getItem('bt_api_token') || window.BT_API_TOKEN || null;
if (access) headers['Authorization'] = 'Bearer ' + access;
const final = Object.assign({}, opts || {}, { headers });
let res;
try{ res = await fetch(ep + path, final); }
catch(err){ throw err; }
// if unauthorized, attempt refresh flow once by calling /auth/refresh (httpOnly cookie)
if (res && res.status === 401){
try{
const r = await fetch(ep + '/auth/refresh', { method: 'POST', credentials: 'include' });
if (r && r.ok){
const j = await r.json();
if (j && j.accessToken) localStorage.setItem('bt_api_token', j.accessToken);
headers['Authorization'] = 'Bearer ' + (j && j.accessToken ? j.accessToken : access);
const retry = Object.assign({}, final, { headers });
return await fetch(ep + path, retry);
}
}catch(e){ /* refresh failed */ }
}
return res;
}
function isStrongPassword(p){
if (!p || p.length < 8) return false;
if (!/[a-z]/.test(p)) return false;
if (!/[A-Z]/.test(p)) return false;
if (!/[0-9]/.test(p)) return false;
return true;
}
// Login helper used by login.html — will use API auth if an endpoint is configured
window.login = async function(){
try{
const uEl = document.getElementById('li_username');
const pEl = document.getElementById('li_password');
const username = (uEl && uEl.value || '').trim();
const pass = (pEl && pEl.value || '').trim();
if (!username) { window.showToast && window.showToast('Enter username','info'); uEl && uEl.focus(); return; }
const loader = document.getElementById('loginLoader'); const msg = document.getElementById('loginLoaderMsg');
if (loader) loader.style.display = 'flex'; if (msg) msg.innerText = 'Logging in to Fast & Reliable Bank…';
const ep = (localStorage.getItem('bt_api_endpoint') || window.BT_API_ENDPOINT || null);
if (ep){
try{
const res = await fetch((ep||'').replace(/\/$/, '') + '/auth/login', {
method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ username: username, password: pass }), credentials: 'include'
});
if (res && res.ok){
const j = await res.json();
if (j && j.accessToken) localStorage.setItem('bt_api_token', j.accessToken);
// ensure profile stored locally for UI
const profiles = JSON.parse(localStorage.getItem('bt_profiles')||'{}');
profiles[username] = profiles[username] || { displayName: j.displayName || username, wallet: Number((profiles[username] && profiles[username].wallet) || 0) };
if (j.avatarUrl) profiles[username].avatar = j.avatarUrl;
localStorage.setItem('bt_profiles', JSON.stringify(profiles));
localStorage.setItem('loggedInUser', username);
if (msg) msg.innerText = 'Welcome to Fast & Reliable Bank — loading your dashboard…';
window.showToast && window.showToast('Signed in — redirecting to dashboard', 'success');
await new Promise(r => setTimeout(r, 700));
if (loader) loader.style.display = 'none';
try{ window.location.href = 'dashboard.html'; }catch(e){}
return;
} else {
// attempt to parse server JSON to detect MFA challenge
let j2 = null;
try{ j2 = await res.json(); }catch(e){ j2 = null; }
if (j2 && j2.mfaRequired && j2.tempToken){
const code = await window.openInputModal({ title: 'Two-factor authentication', label: 'Enter your 2FA code' });
if (!code) { window.showToast && window.showToast('2FA code required','warning'); if (loader) loader.style.display = 'none'; return; }
const v = await fetch((ep||'').replace(/\/$/, '') + '/auth/verify-2fa', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ tempToken: j2.tempToken, token: code }), credentials: 'include' });
if (v && v.ok){
const cred = await v.json();
if (cred && cred.accessToken) localStorage.setItem('bt_api_token', cred.accessToken);
const profiles = JSON.parse(localStorage.getItem('bt_profiles')||'{}');
profiles[username] = profiles[username] || { displayName: cred.displayName || username, wallet: 0 };
if (cred.avatarUrl) profiles[username].avatar = cred.avatarUrl;
localStorage.setItem('bt_profiles', JSON.stringify(profiles));
localStorage.setItem('loggedInUser', username);
window.showToast && window.showToast('Signed in (2FA) — redirecting to dashboard', 'success');
await new Promise(r => setTimeout(r, 700));
if (loader) loader.style.display = 'none';
try{ window.location.href = 'dashboard.html'; }catch(e){}
return;
} else {
window.showToast && window.showToast('2FA verify failed','danger');
if (loader) loader.style.display = 'none';
return;
}
}
// fallback to text/log
const text = await res.text().catch(()=> '');
console.warn('Server login failed', res && res.status, text);
}
}catch(err){ console.warn('Server login error', err && err.message ? err.message : err); }
}
// Local fallback (demo mode)
await new Promise(r => setTimeout(r, 300 + Math.floor(Math.random()*500)));
const profiles = JSON.parse(localStorage.getItem('bt_profiles')||'{}');
profiles[username] = profiles[username] || { displayName: username, wallet: Number((profiles[username] && profiles[username].wallet) || 0) };
localStorage.setItem('bt_profiles', JSON.stringify(profiles));
localStorage.setItem('loggedInUser', username);
if (msg) msg.innerText = 'Welcome to Fast & Reliable Bank — loading your dashboard…';
window.showToast && window.showToast('Signed in — redirecting to dashboard', 'success');
await new Promise(r => setTimeout(r, 700));
if (loader) loader.style.display = 'none';
try{ window.location.href = 'dashboard.html'; }catch(e){}
}catch(e){ console.error('login failed', e); window.showToast && window.showToast('Login failed','danger'); const loader = document.getElementById('loginLoader'); if (loader) loader.style.display='none'; }
};
});
// Signup helper used by signup.html
document.addEventListener('DOMContentLoaded', () => {
window.signup = async function(){
try{
const uEl = document.getElementById('su_username');
const pEl = document.getElementById('su_password');
const dEl = document.getElementById('su_displayName');
const avatarEl = document.getElementById('su_avatar');
const username = (uEl && uEl.value || '').trim();
const pass = (pEl && pEl.value || '').trim();
const displayName = (dEl && dEl.value || '').trim() || username;
if (!username) { window.showToast && window.showToast('Enter username','info'); uEl && uEl.focus(); return; }
if (!isStrongPassword(pass)) { window.showToast && window.showToast('Password must be at least 8 chars and include upper, lower and digits','warning'); pEl && pEl.focus(); return; }
const loader = document.getElementById('signupLoader'); const msg = document.getElementById('signupLoaderMsg');
if (loader) loader.style.display = 'flex'; if (msg) msg.innerText = 'Creating your Fast & Reliable Bank account…';
// read avatar file if provided (convert to data URL)
let avatarData = null;
try{
if (avatarEl && avatarEl.files && avatarEl.files[0]){
const file = avatarEl.files[0];
// resize & compress to keep storage small
avatarData = await resizeImageDataURL(file, 256, 0.75);
}
}catch(e){ console.warn('Failed to read/resize avatar file', e); avatarData = null; }
const ep = (localStorage.getItem('bt_api_endpoint') || window.BT_API_ENDPOINT || null);
let serverOk = false;
const profiles = JSON.parse(localStorage.getItem('bt_profiles')||'{}');
if (ep){
try{
const res = await fetch((ep||'').replace(/\/$/, '') + '/auth/register', {
method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ username: username, password: pass, displayName: displayName, avatar: avatarData, issueSession: true }), credentials: 'include'
});
const txt = await res.text().catch(()=> '');
let j = null;
try{ j = txt ? JSON.parse(txt) : null; }catch(e){}
if (res && res.ok){
serverOk = true;
window.showToast && window.showToast('Account created (server)', 'success');
// auto-login: call /auth/login to obtain tokens
try{
const r = await fetch((ep||'').replace(/\/$/, '') + '/auth/login', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ username: username, password: pass }), credentials: 'include' });
if (r && r.ok){ const cred = await r.json(); if (cred && cred.accessToken) localStorage.setItem('bt_api_token', cred.accessToken); if (cred && cred.avatarUrl) profiles[username] = profiles[username] || { displayName: displayName, wallet: 0, avatar: cred.avatarUrl }; }
}catch(e){ /* ignore */ }
if (j && j.avatarUrl) profiles[username] = profiles[username] || { displayName: displayName, wallet: 0, avatar: j.avatarUrl };
} else {
// server rejected creation — provide feedback if available
const body = j || { message: txt };
console.warn('Signup server rejected', body);
if (body && body.error) window.showToast && window.showToast('Server: ' + body.error, 'danger');
}
}catch(err){ console.warn('Signup: server create-account failed, falling back to local', err && err.message ? err.message : err); }
}
if (!serverOk){
if (!profiles[username]){
profiles[username] = { displayName: displayName, wallet: 0, createdAt: (new Date()).toISOString() };
if (avatarData) profiles[username].avatar = avatarData;
localStorage.setItem('bt_profiles', JSON.stringify(profiles));
window.showToast && window.showToast('Account created', 'success');
} else {
// update displayName/avatar if provided
profiles[username].displayName = profiles[username].displayName || displayName;
if (avatarData) profiles[username].avatar = avatarData;
localStorage.setItem('bt_profiles', JSON.stringify(profiles));
window.showToast && window.showToast('Account exists, signing in', 'info');
}
}
localStorage.setItem('loggedInUser', username);
if (msg) msg.innerText = 'Welcome to Fast & Reliable Bank — loading your dashboard…';
await new Promise(r => setTimeout(r, 600));
if (loader) loader.style.display = 'none';
try{ window.location.href = 'dashboard.html'; }catch(e){ }
}catch(e){ console.error('signup failed', e); window.showToast && window.showToast('Signup failed','danger'); const loader = document.getElementById('signupLoader'); if (loader) loader.style.display='none'; }
};
});
/* Toast manager - accessible, queued and dismissible toasts with optional action.
Public API: showToast(message, type='info', { duration=3500, action: { label, onClick } })
*/
(function setupToast(){
function ensureContainer(){
let c = document.getElementById('globalToastContainer');
if (!c){
c = document.createElement('div');
c.id = 'globalToastContainer';
c.className = 'toast-container';
c.setAttribute('aria-live','polite');
c.setAttribute('aria-atomic','true');
document.body.appendChild(c);
}
return c;
}
function makeToastEl(message, type, opts){
const wrapper = document.createElement('div');
wrapper.className = 'toast ' + (type || 'info');
wrapper.tabIndex = 0;
wrapper.setAttribute('role','status');
const body = document.createElement('div'); body.className = 'toast-body'; body.innerText = message;
wrapper.appendChild(body);
if (opts && opts.action){
const act = document.createElement('button');
act.className = 'toast-action';
act.type = 'button';
act.innerText = opts.action.label || 'Action';
act.addEventListener('click', (e)=>{ try{ opts.action.onClick && opts.action.onClick(e); }catch(err){} });
wrapper.appendChild(act);
}
const close = document.createElement('button'); close.className = 'toast-close'; close.type='button'; close.setAttribute('aria-label','Dismiss'); close.innerText = '✕';
close.addEventListener('click', ()=>{ wrapper.classList.remove('visible'); setTimeout(()=> wrapper.remove(),220); });
wrapper.appendChild(close);
// keyboard: Esc to dismiss, Enter triggers first action if present
wrapper.addEventListener('keydown', (ev)=>{
if (ev.key === 'Escape') { ev.preventDefault(); close.click(); }
if (ev.key === 'Enter') { const btn = wrapper.querySelector('.toast-action'); if (btn){ btn.click(); } }
});
return wrapper;
}
window.showToast = function(message, type='info', opts){
try{
const container = ensureContainer();
const el = makeToastEl(message, type, opts || {});
container.appendChild(el);
// small entrance
requestAnimationFrame(()=> el.classList.add('visible'));
const duration = (opts && opts.duration) ? opts.duration : 3500;
if (duration > 0) setTimeout(()=>{ if (el.parentNode){ el.classList.remove('visible'); setTimeout(()=> el.remove(), 240); } }, duration);
// ensure focus for keyboard dismiss
el.focus();
// also write into an announce node if present for screen readers
const announceNode = document.getElementById('formLive') || document.getElementById('ariaAnnounce');
if (announceNode) announceNode.textContent = message;
}catch(e){ console.error('showToast failed', e); }
};
// small helper for legacy pages
window.announce = function(msg){ const n = document.getElementById('formLive') || document.getElementById('ariaAnnounce'); if (n) n.textContent = msg; };
})();
/* Small modal helpers: openInputModal & openConfirmModal
- openInputModal(opts) -> Promise<string|null>
opts: { title, label, placeholder, type='text', defaultValue }
- openConfirmModal({ title, body }) -> Promise<boolean>
*/
(function modalHelpers(){
function _ensureModalContainer(){
let m = document.getElementById('globalModalContainer');
if (!m){ m = document.createElement('div'); m.id = 'globalModalContainer'; document.body.appendChild(m); }
return m;
}
window.openInputModal = function(opts){
opts = opts || {};
return new Promise((resolve)=>{
_ensureModalContainer();
// create overlay
const overlay = document.createElement('div'); overlay.className = 'confirm-modal'; overlay.style.display='flex'; overlay.style.zIndex=12000;
const card = document.createElement('div'); card.className='confirm-card';
card.innerHTML = `
<header class="confirm-header"><strong>${escapeHtml(opts.title||'Input')}</strong><div><button class="modal-close">✖</button></div></header>
<div class="confirm-body">
<div style="display:flex;flex-direction:column;gap:8px">
${opts.label ? `<label>${escapeHtml(opts.label)}</label>` : ''}
<input class="modal-input" type="${opts.type||'text'}" placeholder="${escapeHtml(opts.placeholder||'')}" value="${escapeHtml(opts.defaultValue||'')}" />
<div class="small-link" style="color:var(--danger);display:none"></div>
</div>
</div>
<div class="confirm-actions"><button class="btn-ghost modal-cancel">Cancel</button><button class="primary modal-ok">OK</button></div>
`;
overlay.appendChild(card);
document.body.appendChild(overlay);
const input = card.querySelector('.modal-input'); const ok = card.querySelector('.modal-ok'); const cancel = card.querySelector('.modal-cancel'); const close = card.querySelector('.modal-close'); const err = card.querySelector('.small-link');
input.focus(); input.select();
function cleanup(){ overlay.remove(); }
ok.addEventListener('click', ()=>{ const v = input.value; cleanup(); resolve(v); });
cancel.addEventListener('click', ()=>{ cleanup(); resolve(null); });
close.addEventListener('click', ()=>{ cleanup(); resolve(null); });
overlay.addEventListener('keydown', (e)=>{ if (e.key === 'Escape'){ e.preventDefault(); cleanup(); resolve(null); } if (e.key === 'Enter'){ e.preventDefault(); ok.click(); } });
});
};
window.openConfirmModal = function(opts){
opts = opts || {};
return new Promise((resolve)=>{
_ensureModalContainer();
const overlay = document.createElement('div'); overlay.className = 'confirm-modal'; overlay.style.display='flex'; overlay.style.zIndex=12000;
const card = document.createElement('div'); card.className='confirm-card';
card.innerHTML = `
<header class="confirm-header"><strong>${escapeHtml(opts.title||'Confirm')}</strong><div><button class="modal-close">✖</button></div></header>
<div class="confirm-body"><div>${escapeHtml(opts.body||'Are you sure?')}</div></div>
<div class="confirm-actions"><button class="btn-ghost modal-no">No</button><button class="primary modal-yes">Yes</button></div>
`;
overlay.appendChild(card); document.body.appendChild(overlay);
const yes = card.querySelector('.modal-yes'); const no = card.querySelector('.modal-no'); const close = card.querySelector('.modal-close');
function cleanup(){ overlay.remove(); }
yes.addEventListener('click', ()=>{ cleanup(); resolve(true); });
no.addEventListener('click', ()=>{ cleanup(); resolve(false); });
close.addEventListener('click', ()=>{ cleanup(); resolve(false); });
overlay.addEventListener('keydown', (e)=>{ if (e.key === 'Escape'){ e.preventDefault(); cleanup(); resolve(false); } if (e.key === 'Enter'){ e.preventDefault(); yes.click(); } });
});
};
})();
/* Esusu UI helpers: join modal and demo scheduler */
(function esusuUiHelpers(){
function _createJoinModalIfNeeded(){
if (document.getElementById('esusuJoinModal')) return;
const modal = document.createElement('div'); modal.id = 'esusuJoinModal'; modal.className = 'confirm-modal'; modal.style.display = 'none';
modal.innerHTML = `
<div class="confirm-card">
<header class="confirm-header"><strong id="esusuJoinTitle">Join Group</strong><div><button id="esusuJoinClose">✖</button></div></header>
<div class="confirm-body">
<div style="display:flex;flex-direction:column;gap:8px">
<div id="esusuJoinDesc" style="color:var(--muted)"></div>
<label>Join as user id</label>
<input id="esusuJoinUser" placeholder="e.g., alice" />
<div id="esusuJoinError" style="color:var(--danger);display:none"></div>
</div>
</div>
<div class="confirm-actions"><button id="esusuJoinCancel" class="btn-ghost">Cancel</button><button id="esusuJoinConfirm" class="primary">Join</button></div>
</div>
`;
document.body.appendChild(modal);
modal.querySelector('#esusuJoinClose')?.addEventListener('click', ()=> modal.style.display = 'none');
modal.querySelector('#esusuJoinCancel')?.addEventListener('click', ()=> modal.style.display = 'none');
}
// open join modal for groupId
function openEsusuJoinModal(groupId){
_createJoinModalIfNeeded();
const modal = document.getElementById('esusuJoinModal');
const title = modal.querySelector('#esusuJoinTitle');
const desc = modal.querySelector('#esusuJoinDesc');
const userInput = modal.querySelector('#esusuJoinUser');
const err = modal.querySelector('#esusuJoinError');
const confirmBtn = modal.querySelector('#esusuJoinConfirm');
const g = window.esusu && window.esusu.getGroup ? window.esusu.getGroup(groupId) : null;
title.innerText = g ? `Join ${g.name}` : 'Join Group';
desc.innerText = g ? `Contribution: ₦${g.contributionAmount} • Starts: ${g.startDate} • Members: ${g.members.length}` : '';
userInput.value = localStorage.getItem('loggedInUser') || '';
err.style.display = 'none';
modal.style.display = 'flex';
confirmBtn.onclick = function(){
const userId = (userInput.value || '').trim();
if (!userId){ err.innerText = 'Enter user id to join'; err.style.display='block'; return; }
try{
window.esusu.joinGroup(groupId, userId);
modal.style.display = 'none';
// use the centralized toast API
window.showToast && window.showToast('Joined group', 'success');
// update any list UIs if present
try{ if (window.renderGroups) window.renderGroups(); } catch(e){}
try{ if (window.populateDashboard) window.populateDashboard(); } catch(e){}
}catch(e){ err.innerText = e && e.message ? e.message : String(e); err.style.display='block'; }
};
}
// Demo scheduler: processes due payouts for today periodically while page is open
let _esusuScheduler = { timer: null, interval: 60000, running: false };
function startEsusuScheduler(intervalMs){
if (!window.esusu || !window.esusu.processDuePayouts) return false;
_esusuScheduler.interval = Number(intervalMs) || _esusuScheduler.interval;
if (_esusuScheduler.timer) clearInterval(_esusuScheduler.timer);
_esusuScheduler.timer = setInterval(()=>{
try{ const res = window.esusu.processDuePayouts(); if (res && res.length) { /* optionally show notification */ } }catch(e){ console.error('Esusu scheduler error', e); }
}, _esusuScheduler.interval);
_esusuScheduler.running = true;
localStorage.setItem('esusu_auto_process','1');
return true;
}
function stopEsusuScheduler(){ if (_esusuScheduler.timer) clearInterval(_esusuScheduler.timer); _esusuScheduler.timer = null; _esusuScheduler.running = false; localStorage.setItem('esusu_auto_process','0'); }
// auto-start if enabled previously
document.addEventListener('DOMContentLoaded', ()=>{
// wire avatar preview on signup form (if present)
try{
const avatarEl = document.getElementById('su_avatar');
const preview = document.getElementById('signupAvatarPreview');
if (avatarEl && preview){
const errorNode = document.getElementById('signupAvatarError');
const btnSignup = document.getElementById('btnSignup');
const ALLOWED = ['image/png','image/jpeg','image/webp'];
const WARN_SIZE = 150 * 1024; // 150KB - show warning
const HARD_LIMIT = 800 * 1024; // 800KB - reject
avatarEl.addEventListener('change', (e)=>{
try{
const f = avatarEl.files && avatarEl.files[0];
if (!f) { preview.src = ''; if (errorNode) errorNode.textContent = ''; if (btnSignup) btnSignup.disabled = false; return; }
// validate type
if (ALLOWED.indexOf(f.type) === -1){
if (errorNode) errorNode.textContent = 'Unsupported image format. Use PNG, JPEG or WebP.';
preview.src = '';
avatarEl.value = '';
if (btnSignup) btnSignup.disabled = true;
return;
}
// size checks
if (f.size > HARD_LIMIT){
if (errorNode) errorNode.textContent = 'File too large. Please use an image under 800KB.';
preview.src = '';
avatarEl.value = '';
if (btnSignup) btnSignup.disabled = true;
return;
}
if (f.size > WARN_SIZE){
if (errorNode) errorNode.textContent = 'Large image — it will be resized to reduce storage.';
} else {
if (errorNode) errorNode.textContent = '';
}
const fr = new FileReader();
fr.onload = ()=>{ try{ preview.src = fr.result; if (btnSignup) btnSignup.disabled = false; }catch(e){} };
fr.onerror = ()=> { preview.src = ''; if (errorNode) errorNode.textContent = 'Failed to preview image'; };
fr.readAsDataURL(f);
}catch(err){ console.warn('avatar preview failed', err); if (errorNode) errorNode.textContent = 'Failed to read image file'; }
});
}
}catch(e){}
try{
const enabled = localStorage.getItem('esusu_auto_process');
if (enabled === '1') startEsusuScheduler(_esusuScheduler.interval);
}catch(e){}
});
// expose helpers
window.openEsusuJoinModal = openEsusuJoinModal;
window.esusuScheduler = { start: startEsusuScheduler, stop: stopEsusuScheduler, status: ()=> _esusuScheduler };
})();
const trustedAgents = new Set(['john','mary','emeka','sarah']);
// Networks, plans and billers (simple local lists for Nigeria)
const NETWORKS = [
{ id: 'mtn', name: 'MTN', emoji: '🟡' },
{ id: 'glo', name: 'GLO', emoji: '🟢' },
{ id: 'airtel', name: 'AIRTEL', emoji: '🔵' },
{ id: '9mobile', name: '9MOBILE', emoji: '🟣' }
];
const COMMON_DATA_PLANS = [
{ id: '500mb', label: '500MB - Daily', amount: 100 },
{ id: '1gb', label: '1GB - Weekly', amount: 300 },
{ id: '2gb', label: '2GB - Weekly', amount: 500 },
{ id: '5gb', label: '5GB - Monthly', amount: 2000 },
{ id: '10gb', label: '10GB - Monthly', amount: 3500 }
];
// Operator specific plans (simplified examples)
const DATA_PLANS_BY_NETWORK = {
mtn: [
{ id: 'mtn_500mb', label: '500MB - Daily (MTN)', amount: 120 },
{ id: 'mtn_1gb', label: '1GB - Weekly (MTN)', amount: 350 },
{ id: 'mtn_5gb', label: '5GB - Monthly (MTN)', amount: 2100 }
],
glo: [
{ id: 'glo_500mb', label: '500MB - Daily (GLO)', amount: 90 },
{ id: 'glo_1gb', label: '1GB - Weekly (GLO)', amount: 280 },
{ id: 'glo_3gb', label: '3GB - Monthly (GLO)', amount: 1500 }
],
airtel: [
{ id: 'airtel_500mb', label: '500MB - Daily (Airtel)', amount: 110 },
{ id: 'airtel_2gb', label: '2GB - Weekly (Airtel)', amount: 520 },
{ id: 'airtel_10gb', label: '10GB - Monthly (Airtel)', amount: 3400 }
],
'9mobile': [
{ id: '9_500mb', label: '500MB - Daily (9mobile)', amount: 100 },
{ id: '9_1gb', label: '1GB - Weekly (9mobile)', amount: 300 },
{ id: '9_5gb', label: '5GB - Monthly (9mobile)', amount: 2200 }
]
};
const BILLERS = [
{ id: 'eko-electric', name: 'Eko Electricity', type: 'electricity', desc: 'Prepaid & Postpaid' },
{ id: 'ikeja-electric', name: 'Ikeja Electric', type: 'electricity', desc: 'Prepaid & Postpaid' },
{ id: 'phcn', name: 'PHCN (Generic)', type: 'electricity', desc: 'National' },
{ id: 'dstv', name: 'DSTV', type: 'cable', desc: 'Satellite TV' },
{ id: 'gotv', name: 'GOtv', type: 'cable', desc: 'Digital Terrestrial' },
{ id: 'startimes', name: 'Startimes', type: 'cable', desc: 'Satellite TV' },
{ id: 'nwsca', name: 'Water (Generic)', type: 'water', desc: 'Water bills' },
{ id: 'spectranet', name: 'Spectranet', type: 'internet', desc: 'Broadband' },
{ id: 'school', name: 'School Fees', type: 'tuition', desc: 'Institution payments' }
];
// common phone prefixes per operator (Nigeria) for basic validation
const OP_PREFIXES = {
mtn: ['0803','0806','0703','0706','0813','0816','0810','0814','0903','0906','07025','07026'],
glo: ['0805','0807','0815','0811','0705','0905'],
airtel: ['0802','0808','0708','0812','0701','0902','0907','0912'],
'9mobile': ['0809','0817','0818','0909','0908','0917','0918']
};
function _normalizePhone(phone){
if(!phone) return '';
let p = phone.replace(/[^0-9+]/g,'');
// convert +234... to 0....
if (p.startsWith('+234')) p = '0' + p.slice(4);
if (p.startsWith('234') && p.length>10) p = '0' + p.slice(3);
return p;
}
function validatePhoneForNetwork(networkId, phone){
const p = _normalizePhone(phone);
if (!p) return { valid:false, msg: 'Enter phone number' };
if (p.length !== 11) return { valid:false, msg: 'Phone should be 11 digits (e.g., 0803xxxxxxx)' };
const prefixes = OP_PREFIXES[networkId] || [];
const pref4 = p.slice(0,4);
const matches = prefixes.includes(pref4);
return { valid: matches, msg: matches ? '' : `Phone prefix ${pref4} may not belong to ${networkId.toUpperCase()}` };
}
// Populate network tiles into a container
function populateNetworks(containerId){
const container = document.getElementById(containerId);
if (!container) return;
container.innerHTML = '';
NETWORKS.forEach(n => {
const el = document.createElement('div');
el.className = 'network-tile';
el.setAttribute('data-network', n.id);
// use provided SVG if available under images/networks/{id}.svg
el.innerHTML = `<div class="network-icon"><img src="images/networks/${n.id}.svg" alt="${n.name}" onerror="this.style.display='block';this.parentNode.innerText='${n.emoji}'"></div><div class="network-label">${n.name}</div>`;
el.addEventListener('click', ()=>{
// clear other selections
const others = container.querySelectorAll('.network-tile');
others.forEach(o => o.classList.remove('selected'));
el.classList.add('selected');
window._selectedNetwork = n;
// if there's a data plans container on the page, refresh plans for this network
try { if (document.getElementById('data_plans')) populateDataPlans('data_plans', n.id); } catch(e){}
// live-validate phone inputs if present
try { if (document.getElementById('air_phone')) updatePhoneWarning('air_phone','air_phone_warn', n.id); } catch(e){}
try { if (document.getElementById('data_phone')) updatePhoneWarning('data_phone','data_phone_warn', n.id); } catch(e){}
});
container.appendChild(el);
});
// auto-select first
const first = container.querySelector('.network-tile'); if (first) { first.classList.add('selected'); window._selectedNetwork = NETWORKS[0]; try { if (document.getElementById('data_plans')) populateDataPlans('data_plans', NETWORKS[0].id); } catch(e){} }
}
// update inline phone warning element by id
function updatePhoneWarning(inputId, warnId, networkId){
try{
const inp = document.getElementById(inputId);
const warn = document.getElementById(warnId);
if(!inp || !warn) return;
const net = networkId || (window._selectedNetwork && window._selectedNetwork.id) || null;
if (!net) { warn.style.display = 'none'; return; }
const res = validatePhoneForNetwork(net, inp.value || '');
if (!res.valid){ warn.innerText = res.msg; warn.style.display = 'block'; }
else { warn.style.display = 'none'; }
}catch(e){/*ignore*/}
}
// Populate data plans into a container
function populateDataPlans(containerId, networkId){
const container = document.getElementById(containerId);
if (!container) return;
container.innerHTML = '';
// prefer explicit networkId, else use currently selected network, else fallback to common plans
const net = networkId || (window._selectedNetwork && window._selectedNetwork.id) || null;
const plans = (net && DATA_PLANS_BY_NETWORK[net]) ? DATA_PLANS_BY_NETWORK[net] : COMMON_DATA_PLANS;
plans.forEach(p => {
const el = document.createElement('div');
el.className = 'plan-tile';
el.setAttribute('data-plan', p.id);
el.innerHTML = `<div class="plan-amount">₦${Number(p.amount).toLocaleString()}</div><div class="plan-sub">${p.label}</div>`;
el.addEventListener('click', ()=>{
// clear other selections
const others = container.querySelectorAll('.plan-tile');
others.forEach(o => o.classList.remove('selected'));
el.classList.add('selected');
window._selectedPlan = p;
// autofill amount input if present
const amt = document.getElementById('data_amount'); if (amt) amt.value = p.amount;
});
container.appendChild(el);
});
// auto-select first plan for convenience
const firstPlan = container.querySelector('.plan-tile');
if (firstPlan) {
firstPlan.classList.add('selected');
window._selectedPlan = plans[0];
const amt = document.getElementById('data_amount'); if (amt) amt.value = plans[0].amount;
}
}
// Populate billers into grid
function populateBillers(containerId){
const container = document.getElementById(containerId);
if (!container) return;
container.innerHTML = '';
BILLERS.forEach(b => {
const el = document.createElement('div');
el.className = 'biller-tile';
el.setAttribute('data-biller', b.id);
// use biller svg if present
el.innerHTML = `<div class="biller-row"><div class="biller-logo"><img class="biller-img" src="images/billers/${b.id}.svg" alt="${b.name}" onerror="this.style.display='none'"></div><div style="flex:1"><div class="biller-name">${b.name}</div><div class="biller-sub">${b.desc}</div></div></div>`;
el.addEventListener('click', ()=>{
const others = container.querySelectorAll('.biller-tile');
others.forEach(o => o.classList.remove('selected'));
el.classList.add('selected');
window._selectedBiller = b;
});
container.appendChild(el);
});
// optionally auto-select first biller
const first = container.querySelector('.biller-tile'); if (first) { first.classList.add('selected'); window._selectedBiller = BILLERS[0]; }
}
window.populateNetworks = populateNetworks;
window.populateDataPlans = populateDataPlans;
window.populateBillers = populateBillers;
// verify agent - safe no-throw
function verifyAgent() {
const el = $('agent');
const result = $('result');
if (!el || !result) return;
const name = (el.value || '').toLowerCase();
if (trustedAgents.has(name)) {
result.textContent = '✅ Trusted Agent';
result.className = 'success';
} else {
result.textContent = '⚠️ Suspicious Agent';
result.className = 'danger';
}
}
function showNotification(msg, timeout = 3000) {
const note = document.createElement('div');
note.className = 'notification';
note.innerText = msg;
document.body.appendChild(note);
setTimeout(() => note.remove(), timeout);
}
// expose notification for other pages
window.showNotification = showNotification;
function saveReport() {
const name = $('r_name')?.value || '';
const location = $('r_location')?.value || '';
const message = $('r_message')?.value || '';
try {
const reports = JSON.parse(localStorage.getItem('reports') || '[]');
const reporter = localStorage.getItem('loggedInUser') || 'guest';
reports.push({ name, location, message, reporter, time: Date.now() });
localStorage.setItem('reports', JSON.stringify(reports));
showToast('Report submitted successfully!', 'success');
(function clear() { if ($('r_name')) $('r_name').value = ''; if ($('r_location')) $('r_location').value = ''; if ($('r_message')) $('r_message').value = ''; })();
} catch (e) {
console.error('saveReport failed', e);
showToast('Unable to save report.', 'danger');
}
}
/*
Support tickets handler
Stores into localStorage under 'supportTickets' and shows a notification.
*/
function createSupportTicket() {
const name = $('s_name')?.value || localStorage.getItem('loggedInUser') || 'Guest';
const email = $('s_email')?.value || '';
const subject = $('s_subject')?.value || '';
const category = $('s_category')?.value || 'General';
const priority = $('s_priority')?.value || 'Normal';
const message = $('s_message')?.value || '';
if (!subject || !message) { showToast('Please provide a subject and message for support', 'info'); return; }
try {
const tickets = JSON.parse(localStorage.getItem('supportTickets') || '[]');
const reporter = localStorage.getItem('loggedInUser') || name || 'guest';
tickets.push({ name, email, subject, category, priority, message, reporter, time: Date.now(), status: 'open' });
localStorage.setItem('supportTickets', JSON.stringify(tickets));
showToast('Support request submitted — our team will contact you shortly.', 'success');
// clear some fields for convenience
if ($('s_subject')) $('s_subject').value = '';
if ($('s_message')) $('s_message').value = '';
setTimeout(() => { window.location.href = 'dashboard.html'; }, 900);
} catch (e) {
console.error('createSupportTicket failed', e);
showToast('Unable to submit support request.', 'danger');
}
}
/* Simple support chat (client-side rule-based bot + persistent history)
Stores messages in localStorage under 'supportChat' as an array of { user, role, text, time }
*/
function _getChatStore() {
return JSON.parse(localStorage.getItem('supportChat') || '[]');
}
function _saveChatStore(arr) {
localStorage.setItem('supportChat', JSON.stringify(arr));
}
function renderSupportChat(containerId = 'chatMessages') {
const container = document.getElementById(containerId);
if (!container) return;
const messages = _getChatStore();
if (!messages.length) return container.innerHTML = '<div style="color:rgba(255,255,255,0.6)">No messages yet. Say hi 👋</div>';
container.innerHTML = messages.map(m => {
const ts = new Date(m.time).toLocaleTimeString();
if (m.role === 'user') {
return `<div class="msg user"><div class="bubble">${escapeHtml(m.text)}<div class="ts">${ts}</div></div></div>`;
}
return `<div class="msg bot"><div class="bubble">${escapeHtml(m.text)}<div class="ts">${ts}</div></div></div>`;
}).join('');
container.scrollTop = container.scrollHeight;
}
function escapeHtml(str){
if (!str) return '';
return String(str).replace(/[&<>\"]/g, function(c){return ({'&':'&','<':'<','>':'>','"':'"'})[c];});
}
function openSupportChat() {
const widget = document.getElementById('chatWidget');
if (!widget) return;
widget.setAttribute('aria-hidden', 'false');
renderSupportChat();
document.getElementById('chatInputField')?.focus();
}
function closeSupportChat() {
const widget = document.getElementById('chatWidget');
if (!widget) return;
widget.setAttribute('aria-hidden', 'true');
}
function sendSupportChat() {
const input = document.getElementById('chatInputField');
if (!input) return;
const text = (input.value || '').trim();
if (!text) return;
const user = localStorage.getItem('loggedInUser') || 'guest';
const messages = _getChatStore();
messages.push({ user, role: 'user', text, time: Date.now() });
_saveChatStore(messages);
input.value = '';
renderSupportChat();
// simulate bot typing and a reply
setTimeout(() => {
const reply = _generateBotReply(text);
messages.push({ user: 'support-bot', role: 'bot', text: reply, time: Date.now() });
_saveChatStore(messages);
renderSupportChat();
}, 700 + Math.floor(Math.random() * 900));
}
function _generateBotReply(userText) {
const t = (userText || '').toLowerCase();
const rules = [
{k: ['balance','show balance','available balance'], r: 'To check your balance, open the app dashboard — your balance is shown on the top. If it looks incorrect, please provide the transaction details.'},
{k: ['transfer','sent','send money'], r: 'Transfers are processed instantly. If the recipient did not receive funds, check the transaction history page and share the transaction reference for us to investigate.'},
{k: ['pin','password','passcode'], r: 'For security reasons we do not store your PIN. If you suspect your PIN is compromised, change it immediately in the profile settings.'},
{k: ['airtime','data','buy airtime','buy data'], r: 'Airtime and data purchases are visible in Recent Activity. If a purchase failed but money was deducted, please provide the phone number and amount.'},
{k: ['loan','loan request'], r: 'Loan requests are reviewed by our team. Check the Loans section for status. If you need urgent help, select High priority when creating a ticket.'},
{k: ['scam','fraud','suspicious'], r: 'If you suspect fraud, stop any outgoing payments, take screenshots, and submit a Support ticket with details. We will escalate immediately.'},
{k: ['hello','hi','hey'], r: 'Hi there! I am Fast & Reliable Bank helper. How can I assist you today? You can ask about balance, transfers, airtime, loans or report suspicious activity.'}
];
for (const rule of rules) {
for (const kw of rule.k) {
if (t.includes(kw)) return rule.r;
}
}
// fallback
return 'Thanks — your message has been received. Our human support team will reply in under 24 hours. For urgent issues, create a ticket in the form above.';
}
// expose chat functions
window.openSupportChat = openSupportChat;
window.closeSupportChat = closeSupportChat;
window.sendSupportChat = sendSupportChat;
window.renderSupportChat = renderSupportChat;
/* PIN, biometrics and preferences helpers */
function _toHex(buffer) {
return Array.from(new Uint8Array(buffer)).map(b => b.toString(16).padStart(2,'0')).join('');
}
function _fromBase64(s) {
try { return Uint8Array.from(atob(s), c => c.charCodeAt(0)); } catch (e) { return null; }
}
function _toBase64(u8) { return btoa(String.fromCharCode(...u8)); }
async function hashPinWithSalt(pin, saltU8) {
const enc = new TextEncoder();
const pinU8 = enc.encode(pin);
// concat salt + pin
const merged = new Uint8Array(saltU8.length + pinU8.length);
merged.set(saltU8, 0);
merged.set(pinU8, saltU8.length);
const digest = await crypto.subtle.digest('SHA-256', merged);
return _toHex(digest);
}
async function setPin(pin) {
// generate 12-byte salt
const salt = crypto.getRandomValues(new Uint8Array(12));
const hash = await hashPinWithSalt(pin, salt);
const obj = { hash, salt: _toBase64(salt), created: Date.now() };
localStorage.setItem('bt_pin', JSON.stringify(obj));
return true;
}
async function verifyPinInput(pin) {
try {
const raw = localStorage.getItem('bt_pin');
if (!raw) return false;
const obj = JSON.parse(raw);
const saltU8 = _fromBase64(obj.salt);
if (!saltU8) return false;
const h = await hashPinWithSalt(pin, saltU8);
return h === obj.hash;
} catch (e) { console.error('verifyPinInput', e); return false; }
}
async function changePin(oldPin, newPin) {
const ok = await verifyPinInput(oldPin);
if (!ok) return false;
await setPin(newPin);
return true;
}
async function forgotPin() {
// simple demo: if profile email exists, generate a short code and prompt user
try {
const user = localStorage.getItem('loggedInUser') || 'guest';
const profiles = JSON.parse(localStorage.getItem('bt_profiles') || '{}');
const p = profiles[user] || {};
if (!p.email) { showToast('No recovery email set in your profile. Please contact support.', 'danger'); return; }
const code = Math.floor(100000 + Math.random()*900000).toString();
const expires = Date.now() + 5*60*1000; // 5 min
localStorage.setItem('bt_pin_reset', JSON.stringify({ code, expires, user }));
// demo: show code to user (in real app, send by email)
showToast(`Recovery code (demo): ${code}. It expires in 5 minutes.`, 'info', { duration: 8000 });
const entered = await window.openInputModal({ title: 'Enter recovery code', placeholder: '123456', label: 'Recovery code' });
if (!entered) return;
const stored = JSON.parse(localStorage.getItem('bt_pin_reset')||'{}');
if (stored.user !== user || stored.code !== entered || Date.now() > stored.expires) { showToast('Invalid or expired code','danger'); return; }
const newPin = await window.openInputModal({ title: 'Enter new PIN', placeholder: 'New PIN', label: 'New PIN', type: 'password' });
if (!newPin) return;
await setPin(newPin);