-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2082 lines (1831 loc) · 66.9 KB
/
Copy pathscript.js
File metadata and controls
2082 lines (1831 loc) · 66.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
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
(function() {
'use strict';
// Smooth scroll for same-page anchors
document.addEventListener('click', function(e) {
const target = e.target;
if (target instanceof HTMLElement && target.tagName === 'A') {
const href = target.getAttribute('href') || '';
if (href.startsWith('#') && href.length > 1) {
e.preventDefault();
const el = document.querySelector(href);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}
}, false);
// Header scroll effect
const header = document.querySelector('.site-header');
function updateHeader() {
if (!header) return;
if (window.scrollY > 20) {
header.classList.add('scrolled');
} else {
header.classList.remove('scrolled');
}
}
window.addEventListener('scroll', updateHeader);
updateHeader();
// Authentication (Supabase)
const authConfig = {
supabaseUrl: document.body?.dataset?.supabaseUrl || '',
supabaseAnonKey: document.body?.dataset?.supabaseAnonKey || '',
redirectTo: document.body?.dataset?.supabaseRedirect || window.location.origin
};
const loginButton = document.getElementById('loginButton');
const authModal = document.getElementById('auth-modal');
const closeAuthModal = document.getElementById('closeAuthModal');
const authTabs = Array.from(document.querySelectorAll('.auth-tab'));
const authMessage = document.getElementById('authMessage');
const emailAuthForm = document.getElementById('emailAuthForm');
const emailSubmit = document.getElementById('emailSubmit');
const authEmailInput = document.getElementById('authEmail');
const authPasswordInput = document.getElementById('authPassword');
const authPasswordConfirmInput = document.getElementById('authPasswordConfirm');
const googleSignIn = document.getElementById('googleSignIn');
const userMenu = document.getElementById('userMenu');
const userMenuButton = document.getElementById('userMenuButton');
const userMenuPanel = document.getElementById('userMenuPanel');
const logoutButton = document.getElementById('logoutButton');
const userEmailDisplay = document.getElementById('userEmailDisplay');
const userEmailFull = document.getElementById('userEmailFull');
const userAvatar = document.getElementById('userAvatar');
const userAvatarSmall = document.getElementById('userAvatarSmall');
let authMode = 'signin';
let supabaseClient = null;
let currentUser = null;
let userMenuHTML = null; // Store user menu HTML for recreation
// Helper functions to get user menu elements (they may be removed/recreated)
function getUserMenu() { return document.getElementById('userMenu'); }
function getUserMenuButton() { return document.getElementById('userMenuButton'); }
function getUserMenuPanel() { return document.getElementById('userMenuPanel'); }
function getLogoutButton() { return document.getElementById('logoutButton'); }
function getUserEmailDisplay() { return document.getElementById('userEmailDisplay'); }
function getUserEmailFull() { return document.getElementById('userEmailFull'); }
function getUserAvatar() { return document.getElementById('userAvatar'); }
function getUserAvatarSmall() { return document.getElementById('userAvatarSmall'); }
function createSupabaseClient() {
if (!window.supabase || !authConfig.supabaseUrl || !authConfig.supabaseAnonKey) {
return null;
}
try {
return window.supabase.createClient(authConfig.supabaseUrl, authConfig.supabaseAnonKey, {
auth: { persistSession: true, autoRefreshToken: true }
});
} catch (err) {
console.error('Failed to init Supabase:', err);
return null;
}
}
function openAuthModal() {
if (!authModal) return;
authModal.style.display = 'flex';
setTimeout(function() { authModal.classList.add('active'); }, 10);
authEmailInput && authEmailInput.focus();
if (!supabaseClient && authMessage) {
authMessage.textContent = 'Add Supabase URL and anon key to the <body> data attributes to enable login.';
} else if (authMessage) {
authMessage.textContent = '';
}
}
function hideAuthModal() {
if (!authModal) return;
authModal.classList.remove('active');
setTimeout(function() { authModal.style.display = 'none'; }, 180);
}
function setAuthMode(mode) {
authMode = mode;
authTabs.forEach(function(tab) {
tab.classList.toggle('active', tab.dataset.mode === mode);
});
if (emailSubmit) {
emailSubmit.textContent = mode === 'signup' ? 'Create account' : 'Log in';
}
if (authPasswordInput) {
if (mode === 'signup') {
authPasswordInput.placeholder = 'Password (min 6 chars)';
authPasswordInput.autocomplete = 'new-password';
} else {
authPasswordInput.autocomplete = 'current-password';
}
}
// Show/hide password confirmation field
if (authPasswordConfirmInput) {
authPasswordConfirmInput.style.display = mode === 'signup' ? 'block' : 'none';
authPasswordConfirmInput.required = mode === 'signup';
if (mode === 'signup') {
authPasswordConfirmInput.placeholder = 'Confirm password';
} else {
// Clear the field when switching to signin mode
authPasswordConfirmInput.value = '';
}
}
if (authMessage) authMessage.textContent = '';
}
function userInitials(user) {
const email = user?.email || '';
if (!email) return 'U';
return email.charAt(0).toUpperCase();
}
function recreateUserMenu() {
const authControls = document.querySelector('.auth-controls');
if (!authControls || userMenuHTML === null) return;
// Create a temporary container to parse HTML
const temp = document.createElement('div');
temp.innerHTML = userMenuHTML;
const newUserMenu = temp.firstElementChild;
// Insert before the Buy Now button (or at end of auth-controls)
authControls.insertBefore(newUserMenu, authControls.querySelector('.buy-now') || null);
// Reattach event listeners
setupUserMenuListeners();
}
function setupUserMenuListeners() {
const menuButton = getUserMenuButton();
const menuPanel = getUserMenuPanel();
const logoutBtn = getLogoutButton();
if (menuButton && menuPanel) {
menuButton.addEventListener('click', function(e) {
e.stopPropagation();
const wasHidden = menuPanel.hidden;
menuPanel.hidden = !menuPanel.hidden;
// Load license info when opening the menu
if (wasHidden && currentUser) {
loadLicenseInfo();
}
});
document.addEventListener('click', function(e) {
if (menuPanel.hidden) return;
if (!menuPanel.contains(e.target) && !menuButton.contains(e.target)) {
menuPanel.hidden = true;
}
});
}
if (logoutBtn) {
logoutBtn.addEventListener('click', async function() {
if (!supabaseClient) {
updateUserUI(null);
return;
}
try {
await supabaseClient.auth.signOut();
} catch (err) {
console.error('Sign out failed:', err);
} finally {
updateUserUI(null);
}
});
}
// Setup refresh license button
const refreshLicenseBtn = document.getElementById('refreshLicenseBtn');
if (refreshLicenseBtn) {
refreshLicenseBtn.addEventListener('click', function(e) {
e.stopPropagation();
loadLicenseInfo();
});
}
}
async function loadLicenseInfo() {
const email = getSignedInEmail();
if (!email) return;
const licenseStatusDisplay = document.getElementById('licenseStatusDisplay');
if (!licenseStatusDisplay) return;
licenseStatusDisplay.innerHTML = '<div class="license-loading">Loading license information...</div>';
try {
const res = await postJson('/api/license/info', { email });
// Debug logging
console.log('License info response:', res);
if (res._debug) {
console.log('Debug info:', res._debug);
}
if (!res.ok) {
licenseStatusDisplay.innerHTML = `<div class="license-error">Unable to load license information.</div>`;
return;
}
let html = '';
// License key section
if (res.licenseKey) {
html += `<div class="license-key-section">
<div class="license-key-label">License Key:</div>
<div class="license-key-value">
<code class="license-key-code">${res.licenseKey}</code>
<button class="btn-copy-key" data-key="${res.licenseKey}" title="Copy license key">📋</button>
</div>
</div>`;
} else {
html += `<div class="license-key-section">
<div class="license-status-badge status-${res.status}">Status: ${res.status || 'inactive'}</div>
<div class="license-no-key">No active license found.</div>
</div>`;
}
// License status
if (res.licenseKey) {
const statusClass = res.status === 'active' ? 'status-active' : (res.status === 'trial' ? 'status-trial' : 'status-inactive');
html += `<div class="license-status-section">
<div class="license-status-badge ${statusClass}">Status: ${res.status || 'inactive'}</div>
${res.expiresAt ? `<div class="license-expiry">Expires: ${prettyExpiry(res.expiresAt)}</div>` : (res.status === 'trial' ? '' : '<div class="license-expiry">Lifetime license</div>')}
</div>`;
}
// Device activations section
if (res.licenseKey && res.activations && res.activations.length > 0) {
html += `<div class="device-activations-section">
<div class="device-activations-header">Device Activations (${res.activations.length})</div>
<div class="device-activations-list">`;
res.activations.forEach(function(activation) {
const activatedDate = activation.activated_at ? prettyExpiry(new Date(activation.activated_at).getTime()) : 'Unknown';
html += `<div class="device-activation-item">
<div class="device-info">
<div class="device-id">${escapeHtml(activation.device_id || 'Unknown Device')}</div>
<div class="device-activated-date">Activated: ${activatedDate}</div>
</div>
<button class="btn-deactivate-device" data-license-key="${escapeHtml(res.licenseKey)}" data-device-id="${escapeHtml(activation.device_id)}" title="Deactivate device">Deactivate</button>
</div>`;
});
html += `</div></div>`;
} else if (res.licenseKey) {
// Check if activations is actually an array or if it's null/undefined
const activationsInfo = res.activations === null ? 'null' :
res.activations === undefined ? 'undefined' :
Array.isArray(res.activations) ? `array with ${res.activations.length} items` :
typeof res.activations;
html += `<div class="device-activations-section">
<div class="device-activations-header">Device Activations</div>
<div class="device-activations-empty">No active device activations.
${res._debug ? `<br><small style="color: #9ca3af; font-size: 10px;">Debug: activations=${activationsInfo}, licenseKey=${res.licenseKey}</small>` : ''}
<br><small style="color: #9ca3af; font-size: 10px;">Note: Device activations are created when you run the Reaper script with this license key.</small>
</div>
</div>`;
}
licenseStatusDisplay.innerHTML = html;
// Setup copy button handlers
const copyButtons = licenseStatusDisplay.querySelectorAll('.btn-copy-key');
copyButtons.forEach(function(btn) {
btn.addEventListener('click', function(e) {
e.stopPropagation();
const key = btn.getAttribute('data-key');
if (key) {
navigator.clipboard.writeText(key).then(function() {
btn.textContent = '✓';
setTimeout(function() {
btn.textContent = '📋';
}, 1500);
}).catch(function() {
btn.textContent = '✗';
setTimeout(function() {
btn.textContent = '📋';
}, 1500);
});
}
});
});
// Setup deactivate device button handlers
const deactivateButtons = licenseStatusDisplay.querySelectorAll('.btn-deactivate-device');
deactivateButtons.forEach(function(btn) {
btn.addEventListener('click', async function(e) {
e.stopPropagation();
const licenseKey = btn.getAttribute('data-license-key');
const deviceId = btn.getAttribute('data-device-id');
if (!confirm(`Are you sure you want to deactivate device "${deviceId}"?`)) {
return;
}
btn.disabled = true;
btn.textContent = 'Deactivating...';
try {
const result = await postJson('/api/device?action=deactivate', {
email: email,
licenseKey: licenseKey,
deviceId: deviceId,
action: 'deactivate'
});
if (result.ok) {
// Reload license info
loadLicenseInfo();
} else {
alert('Failed to deactivate device: ' + (result.error || 'Unknown error'));
btn.disabled = false;
btn.textContent = 'Deactivate';
}
} catch (err) {
alert('Error deactivating device: ' + (err.message || 'Unknown error'));
btn.disabled = false;
btn.textContent = 'Deactivate';
}
});
});
} catch (err) {
console.error('Failed to load license info:', err);
licenseStatusDisplay.innerHTML = `<div class="license-error">Error loading license information: ${err.message || 'Unknown error'}</div>`;
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function updateUserUI(user) {
currentUser = user || null;
const email = user?.email || '';
const hasUser = Boolean(user);
if (loginButton) {
loginButton.style.display = hasUser ? 'none' : 'inline-flex';
}
const currentUserMenu = getUserMenu();
// Store user menu HTML on first access if not already stored
if (currentUserMenu && userMenuHTML === null) {
userMenuHTML = currentUserMenu.outerHTML;
}
if (currentUserMenu) {
if (hasUser) {
// Show user menu if user is signed in
currentUserMenu.hidden = false;
} else {
// Remove user menu from DOM if user is not signed in
currentUserMenu.remove();
}
} else if (hasUser && userMenuHTML) {
// Recreate user menu if user signed in and it was removed
recreateUserMenu();
}
// Update user menu content if it exists
const menu = getUserMenu();
if (menu && hasUser) {
const menuPanel = getUserMenuPanel();
const emailDisplay = getUserEmailDisplay();
const emailFull = getUserEmailFull();
const avatar = getUserAvatar();
const avatarSmall = getUserAvatarSmall();
if (menuPanel) {
menuPanel.hidden = true;
}
if (emailDisplay) {
emailDisplay.textContent = email || '';
}
if (emailFull) {
emailFull.textContent = email || '';
}
const initials = userInitials(user);
if (avatar) avatar.textContent = initials;
if (avatarSmall) avatarSmall.textContent = initials;
}
updateLicenseUserText(user);
if (!hasUser) {
setBadge('inactive', 'Sign in to start a trial or check your license.');
}
if (!hasUser && authModal) {
hideAuthModal();
}
}
async function hydrateSession() {
if (!supabaseClient) return;
try {
const { data, error } = await supabaseClient.auth.getSession();
if (error) throw error;
updateUserUI(data?.session?.user || null);
if (data?.session?.user) {
refreshLicenseStatus({ targetMessage: licenseMessage });
}
} catch (err) {
console.error('Failed to get session:', err);
updateUserUI(null);
}
supabaseClient.auth.onAuthStateChange(function(_event, session) {
updateUserUI(session?.user || null);
if (session?.user) {
hideAuthModal();
refreshLicenseStatus({ targetMessage: licenseMessage });
}
});
}
function ensureSupabase() {
if (!supabaseClient) {
if (authMessage) {
authMessage.textContent = 'Supabase auth is not configured. Set data-supabase-url and data-supabase-anon-key on <body>.';
}
return false;
}
return true;
}
function setupAuthUI() {
supabaseClient = createSupabaseClient();
if (supabaseClient) {
hydrateSession();
} else {
updateUserUI(null);
}
if (loginButton) {
loginButton.addEventListener('click', function() {
openAuthModal();
});
}
if (closeAuthModal) {
closeAuthModal.addEventListener('click', hideAuthModal);
}
if (authModal) {
authModal.addEventListener('click', function(e) {
if (e.target === authModal) hideAuthModal();
});
}
authTabs.forEach(function(tab) {
tab.addEventListener('click', function() {
setAuthMode(tab.dataset.mode === 'signup' ? 'signup' : 'signin');
});
});
if (googleSignIn) {
googleSignIn.addEventListener('click', async function() {
if (!ensureSupabase()) return;
googleSignIn.disabled = true;
try {
const { error } = await supabaseClient.auth.signInWithOAuth({
provider: 'google',
options: { redirectTo: authConfig.redirectTo || window.location.href }
});
if (error) throw error;
if (authMessage) authMessage.textContent = 'Redirecting to Google...';
} catch (err) {
console.error('Google login failed:', err);
if (authMessage) authMessage.textContent = err.message || 'Unable to start Google login.';
} finally {
googleSignIn.disabled = false;
}
});
}
if (emailAuthForm) {
emailAuthForm.addEventListener('submit', async function(e) {
e.preventDefault();
if (!ensureSupabase()) return;
const email = (authEmailInput?.value || '').trim();
const password = authPasswordInput?.value || '';
const passwordConfirm = authPasswordConfirmInput?.value || '';
if (!email || !password) {
if (authMessage) authMessage.textContent = 'Email and password are required.';
return;
}
if (password.length < 6) {
if (authMessage) authMessage.textContent = 'Password must be at least 6 characters.';
return;
}
// Validate password confirmation for signup
if (authMode === 'signup') {
if (!passwordConfirm) {
if (authMessage) authMessage.textContent = 'Please confirm your password.';
return;
}
if (password !== passwordConfirm) {
if (authMessage) authMessage.textContent = 'Passwords do not match.';
return;
}
}
if (emailSubmit) {
emailSubmit.disabled = true;
emailSubmit.textContent = authMode === 'signup' ? 'Creating account...' : 'Logging in...';
}
if (authMessage) authMessage.textContent = '';
try {
if (authMode === 'signup') {
const { data, error } = await supabaseClient.auth.signUp({
email,
password,
options: { emailRedirectTo: authConfig.redirectTo || window.location.origin }
});
if (error) throw error;
updateUserUI(data?.user || null);
// Send custom verification email with "Start Trial" button
try {
const apiBase = (document.body && document.body.dataset.apiBase) || '';
await fetch((apiBase || '') + '/api/auth/send-verification-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email })
});
} catch (emailErr) {
console.error('Failed to send custom verification email:', emailErr);
// Don't fail the signup if custom email fails
}
if (authMessage) {
authMessage.innerHTML = 'Check your email to confirm your account and start your trial. <br><button type="button" id="resendConfirmationBtn" style="margin-top: 8px; background: transparent; border: 1px solid rgba(255,255,255,0.2); color: var(--primary); padding: 6px 12px; border-radius: 6px; cursor: pointer; font-size: 13px;">Resend confirmation email</button>';
const resendBtn = document.getElementById('resendConfirmationBtn');
if (resendBtn) {
resendBtn.addEventListener('click', async function() {
resendBtn.disabled = true;
resendBtn.textContent = 'Sending...';
try {
const { error: resendError } = await supabaseClient.auth.resend({
type: 'signup',
email: email
});
if (resendError) throw resendError;
resendBtn.textContent = 'Email sent!';
setTimeout(() => {
resendBtn.textContent = 'Resend confirmation email';
resendBtn.disabled = false;
}, 3000);
} catch (resendErr) {
console.error('Failed to resend confirmation:', resendErr);
resendBtn.textContent = 'Failed to send';
setTimeout(() => {
resendBtn.textContent = 'Resend confirmation email';
resendBtn.disabled = false;
}, 3000);
}
});
}
}
} else {
const { data, error } = await supabaseClient.auth.signInWithPassword({ email, password });
if (error) throw error;
updateUserUI(data?.user || data?.session?.user || null);
hideAuthModal();
}
} catch (err) {
console.error('Email auth error:', err);
console.error('Error details:', JSON.stringify(err, null, 2));
let errorMessage = err.message || 'Unable to authenticate.';
// Provide user-friendly messages for common error types
if (err.message) {
const lowerMessage = err.message.toLowerCase();
const errorCode = err.status || err.code || '';
// Supabase returns "Invalid login credentials" for unconfirmed emails
// Check for email not confirmed errors - Supabase error code 400 with specific messages
if (lowerMessage.includes('email not confirmed') ||
lowerMessage.includes('email_not_confirmed') ||
lowerMessage.includes('not confirmed') ||
lowerMessage.includes('confirm your email') ||
lowerMessage.includes('email address is not confirmed') ||
(err.status === 400 && (lowerMessage.includes('email') || lowerMessage.includes('invalid'))) ||
errorCode === 'email_not_confirmed') {
errorMessage = 'Please verify your email address before signing in. Check your inbox (and spam folder) for the confirmation email from Supabase.';
}
// Check for invalid credentials - but only if it's NOT an email confirmation issue
else if (lowerMessage.includes('invalid login') ||
lowerMessage.includes('invalid credentials') ||
lowerMessage.includes('wrong password') ||
lowerMessage.includes('incorrect password') ||
lowerMessage.includes('invalid login credentials')) {
// For signin attempts, "invalid credentials" might mean unconfirmed email
if (authMode === 'signin') {
errorMessage = 'Invalid email or password. If you just created an account, please verify your email first. Check your inbox (and spam folder) for the confirmation email from Supabase.';
} else {
errorMessage = 'Invalid email or password. Please check your credentials and try again.';
}
}
// Check for leaked password errors (various possible messages)
else if (lowerMessage.includes('breach') ||
lowerMessage.includes('pwned') ||
lowerMessage.includes('compromised') ||
lowerMessage.includes('leaked') ||
lowerMessage.includes('data breach')) {
errorMessage = 'This password has appeared in a data breach. Please choose a different, stronger password.';
}
// Check for weak password errors
else if (lowerMessage.includes('weak') || lowerMessage.includes('too common')) {
errorMessage = 'This password is too weak or commonly used. Please choose a stronger password.';
}
// Check for password policy violations
else if (lowerMessage.includes('password') && (lowerMessage.includes('invalid') || lowerMessage.includes('not allowed'))) {
errorMessage = 'This password does not meet security requirements. Please choose a different password.';
}
}
if (authMessage) {
authMessage.textContent = errorMessage;
// If it's a signin error, add a helpful note about email confirmation
if (authMode === 'signin' && (errorMessage.includes('verify') || errorMessage.includes('confirm'))) {
authMessage.innerHTML = errorMessage + '<br><small style="color: var(--text-muted); margin-top: 8px; display: block;">Tip: Look for an email from Supabase (not from us) with the subject "Confirm your signup"</small>';
}
}
} finally {
if (emailSubmit) {
emailSubmit.disabled = false;
emailSubmit.textContent = authMode === 'signup' ? 'Create account' : 'Log in';
}
}
});
}
// Setup user menu listeners (will be called on initial load and after recreation)
setupUserMenuListeners();
}
setupAuthUI();
// Set current year in footer
const yearEl = document.getElementById('year');
if (yearEl) yearEl.textContent = String(new Date().getFullYear());
// Handle Buy buttons via Payment Link (Stripe, Lemon Squeezy, Paddle, etc.)
function wireBuyButtons() {
const buttons = [
document.getElementById('buyButton'),
document.getElementById('buyNowTop')
].filter(Boolean);
buttons.forEach(function(btn) {
btn.addEventListener('click', function(e) {
e.preventDefault();
const paymentLink = btn.getAttribute('data-payment-link');
if (paymentLink && paymentLink.trim().length > 0) {
window.location.href = paymentLink;
} else {
// Fallback to PayPal buttons if no direct link is set
const paypalEl = document.getElementById('paypal-button-container');
if (paypalEl) {
paypalEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
return;
}
alert('Connect a checkout link first. Edit data-payment-link on the Buy buttons.');
}
});
});
}
wireBuyButtons();
// Scroll reveal for elements with [data-reveal] - Enhanced with stagger
function setupReveal() {
const els = Array.from(document.querySelectorAll('[data-reveal]'));
// Preload all carousel slides immediately (no lazy loading)
const carouselSlides = Array.from(document.querySelectorAll('.carousel-slide[data-reveal]'));
carouselSlides.forEach(function(slide) {
slide.classList.add('visible');
// Preload videos in carousel slides
const videos = slide.querySelectorAll('video');
videos.forEach(function(video) {
video.load(); // Force video to load metadata
video.preload = 'auto'; // Ensure preloading
});
});
// Filter out carousel slides from the regular reveal observer
const nonCarouselEls = els.filter(function(el) {
return !el.closest('.carousel-slide');
});
if (!('IntersectionObserver' in window)) {
nonCarouselEls.forEach(function(el) { el.classList.add('visible'); });
return;
}
// Use a more aggressive threshold and rootMargin for earlier triggering
const io = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
// Remove delay for immediate feedback, handle stagger in CSS
entry.target.classList.add('visible');
io.unobserve(entry.target);
}
});
}, {
threshold: 0.05, // Lower threshold
rootMargin: '0px 0px -50px 0px' // Trigger slightly before bottom
});
nonCarouselEls.forEach(function(el) { io.observe(el); });
}
setupReveal();
// Sends Header Scroll-Driven Animation
function setupSendsHeaderAnimation() {
const header = document.querySelector('.sends-header');
if (!header) return;
function updateAnimation() {
const rect = header.getBoundingClientRect();
const windowHeight = window.innerHeight;
// Calculate progress based on position
// Start: entering bottom of viewport (rect.top <= windowHeight)
// End: 30% from bottom (rect.top <= windowHeight * 0.7) - meaning it clears well before center
const startPoint = windowHeight;
const endPoint = windowHeight * 0.7; // 30% up from bottom
if (rect.top > startPoint) {
// Not visible yet
header.style.opacity = '0';
header.style.filter = 'blur(20px)';
header.style.transform = 'scale(0.9)';
} else if (rect.top < endPoint) {
// Fully visible
header.style.opacity = '1';
header.style.filter = 'blur(0px)';
header.style.transform = 'scale(1)';
} else {
// In between - interpolate
const range = startPoint - endPoint;
const current = startPoint - rect.top;
const progress = Math.min(Math.max(current / range, 0), 1);
// Ease the progress
const eased = progress < 0.5 ? 2 * progress * progress : -1 + (4 - 2 * progress) * progress;
header.style.opacity = progress.toFixed(2);
header.style.filter = `blur(${(20 * (1 - eased)).toFixed(1)}px)`;
header.style.transform = `scale(${0.9 + (0.1 * eased)})`;
}
}
// Update on scroll
window.addEventListener('scroll', function() {
window.requestAnimationFrame(updateAnimation);
}, { passive: true });
// Initial check
updateAnimation();
}
setupSendsHeaderAnimation();
// FX List Title Scroll-Driven Animation
function setupFXListTitleAnimation() {
const title = document.querySelector('.fx-list-title');
if (!title) return;
function updateAnimation() {
const rect = title.getBoundingClientRect();
const windowHeight = window.innerHeight;
// Calculate progress based on position
// Start: entering bottom of viewport (rect.top <= windowHeight)
// End: 30% from bottom (rect.top <= windowHeight * 0.7) - meaning it clears well before center
const startPoint = windowHeight;
const endPoint = windowHeight * 0.7; // 30% up from bottom
if (rect.top > startPoint) {
// Not visible yet
title.style.opacity = '0';
title.style.filter = 'blur(20px)';
title.style.transform = 'scale(0.9)';
} else if (rect.top < endPoint) {
// Fully visible
title.style.opacity = '1';
title.style.filter = 'blur(0px)';
title.style.transform = 'scale(1)';
} else {
// In between - interpolate
const range = startPoint - endPoint;
const current = startPoint - rect.top;
const progress = Math.min(Math.max(current / range, 0), 1);
// Ease the progress
const eased = progress < 0.5 ? 2 * progress * progress : -1 + (4 - 2 * progress) * progress;
title.style.opacity = progress.toFixed(2);
title.style.filter = `blur(${(20 * (1 - eased)).toFixed(1)}px)`;
title.style.transform = `scale(${0.9 + (0.1 * eased)})`;
}
}
// Update on scroll
window.addEventListener('scroll', function() {
window.requestAnimationFrame(updateAnimation);
}, { passive: true });
// Initial check
updateAnimation();
}
setupFXListTitleAnimation();
// Interactive feature effects
function setupFeatureInteractions() {
// Hero video - always play (if video exists)
const heroVideo = document.querySelector('.hero-video');
const heroBackground = document.querySelector('.hero-background');
if (heroVideo) {
// Update play icon visibility for hero video
function updateHeroPlayIcon() {
if (heroBackground) {
if (heroVideo.paused) {
heroBackground.classList.add('hero-video-paused');
} else {
heroBackground.classList.remove('hero-video-paused');
}
}
}
// Listen for play/pause events
heroVideo.addEventListener('play', updateHeroPlayIcon);
heroVideo.addEventListener('pause', updateHeroPlayIcon);
heroVideo.addEventListener('ended', updateHeroPlayIcon);
// Initial state
updateHeroPlayIcon();
// Make hero play icon clickable
if (heroBackground) {
heroBackground.addEventListener('click', function(e) {
// If video is paused, clicking anywhere on hero background (including play icon) should play
if (heroBackground.classList.contains('hero-video-paused') && heroVideo.paused) {
e.preventDefault();
e.stopPropagation();
heroVideo.play();
}
});
}
heroVideo.play().catch(function() {
// Ignore autoplay restrictions, will play on user interaction
});
// Ensure hero video keeps playing
heroVideo.addEventListener('pause', function() {
if (document.visibilityState === 'visible') {
heroVideo.play().catch(function() {});
}
});
// Play when page becomes visible
document.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'visible' && heroVideo.paused) {
heroVideo.play().catch(function() {});
}
});
}
// Feature videos - play on hover, but only if slide is active
const featureBlocks = document.querySelectorAll('.feature-block');
featureBlocks.forEach(function(featureBlock) {
const video = featureBlock.querySelector('video');
const wrapper = featureBlock.querySelector('.video-controls-wrapper');
if (!video) return;
// Update play icon visibility based on video state
function updatePlayIcon() {
if (wrapper) {
if (video.paused) {
wrapper.classList.add('video-paused');
} else {
wrapper.classList.remove('video-paused');
}
}
}
// Listen for play/pause events
video.addEventListener('play', updatePlayIcon);
video.addEventListener('pause', updatePlayIcon);
video.addEventListener('ended', updatePlayIcon);
// Initial state - videos start paused
video.pause();
updatePlayIcon();
// Helper function to check if the slide is active
function isSlideActive() {
const slide = featureBlock.closest('.carousel-slide');
return slide && slide.classList.contains('active');
}
// Play on hover, but only if the slide is active
featureBlock.addEventListener('mouseenter', function() {
if (isSlideActive()) {
video.play().catch(function() {
// Ignore autoplay restrictions
});
// Mark that video was playing
const slide = featureBlock.closest('.carousel-slide');
if (slide) {
slide.dataset.videoWasPlaying = 'true';
}
}
});
// Pause when mouse leaves (for inactive slides that might have been playing)
featureBlock.addEventListener('mouseleave', function() {
if (!isSlideActive() && !video.paused) {
video.pause();
const slide = featureBlock.closest('.carousel-slide');
if (slide) {
slide.dataset.videoWasPlaying = 'false';
}
}
});
});
// Parallax effect - Removed to prevent conflict with entrance animations
/*
const featureBlocks = document.querySelectorAll('.feature-block');
let ticking = false;
function updateParallax() {
...
}
window.addEventListener('scroll', updateParallax, { passive: true });
*/
}
setupFeatureInteractions();
// Custom Video Controls with Progress Bar (only for feature videos)
function setupVideoControls() {
const videoWrappers = document.querySelectorAll('.feature-media .video-controls-wrapper');
videoWrappers.forEach(function(wrapper) {
const video = wrapper.querySelector('video');
const progressBar = wrapper.querySelector('.video-progress-bar');
const progressFilled = wrapper.querySelector('.video-progress-filled');
const progressHandle = wrapper.querySelector('.video-progress-handle');
if (!video || !progressBar || !progressFilled || !progressHandle) return;
// Disable default controls to prevent dimming
video.controls = false;
video.setAttribute('controls', 'false');
let isDragging = false;