-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1216 lines (1052 loc) · 39.2 KB
/
script.js
File metadata and controls
1216 lines (1052 loc) · 39.2 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
// Configuration - live Stripe keys (backend must use matching sk_live_ in env)
const CONFIG = {
STRIPE_PUBLISHABLE_KEY: 'pk_live_51RgRBRG6ZGE2Rl3oAODxJMejteYv858nAPO5OkhMycDqT1zRIhnYnT47KAt4EaWAev2QKeQbIM6YVfXEpkJxXz7B0080qNWNbM',
DYNADOT_API_KEY: '8z9R6Z7D8i8JF84LE7P8g7j9J9W706n9R9F6YRa7E7X',
DYNADOT_API_URL: 'https://storefront457991568429.gdg.website',
BACKEND_URL: 'https://vibecodesspace.onrender.com/api',
COMMISSION_RATE: 0.15,
BASE_URL: 'https://vibecodes.space' // Stripe return_url and redirects
};
// Initialize Stripe dynamically
let stripe;
let stripeInitialized = false;
async function initStripe() {
if (stripeInitialized) return;
try {
const response = await fetch(`${CONFIG.BACKEND_URL}/config`);
if (response.ok) {
const data = await response.json();
if (data.stripePublishableKey) {
stripe = Stripe(data.stripePublishableKey);
stripeInitialized = true;
return;
}
}
} catch (e) {
console.warn('Failed to fetch dynamic Stripe config:', e);
}
// Fallback
try {
stripe = Stripe(CONFIG.STRIPE_PUBLISHABLE_KEY);
} catch (error) {
console.warn('Stripe fallback initialization failed:', error);
stripe = null;
}
stripeInitialized = true;
}
// Pricing configuration
const PRICING = {
basic: {
name: 'Basic Website',
price: 2500,
type: 'one-time'
},
professional: {
name: 'Professional Website',
price: 3500,
type: 'one-time'
},
premium: {
name: 'Premium Website',
price: 4500,
type: 'one-time'
},
'basic-maintenance': {
name: 'Basic Maintenance',
price: 150,
type: 'monthly'
},
'premium-maintenance': {
name: 'Premium Maintenance',
price: 300,
type: 'monthly'
}
};
// DOM Elements
const paymentModal = document.getElementById('paymentModal');
const domainModal = document.getElementById('domainModal');
const paymentForm = document.getElementById('paymentForm');
const domainResults = document.getElementById('domainResults');
const domainNameInput = document.getElementById('domainName');
const checkDomainBtn = document.getElementById('checkDomain');
// Inline domain search elements
const inlineDomainNameInput = document.getElementById('inlineDomainName');
const inlineCheckDomainBtn = document.getElementById('inlineCheckDomain');
const inlineDomainResults = document.getElementById('inlineDomainResults');
// Initialize the application
document.addEventListener('DOMContentLoaded', function () {
initializeNavigation();
initializePricingButtons();
initializeModals();
initializeDomainSearch();
initializeInlineDomainSearch();
initializePortfolioImages();
initializeCarousel();
initializeAiBuilder();
initScrollAnimations();
initOnboarding();
});
function initScrollAnimations() {
var els = document.querySelectorAll('.animate-on-scroll');
var observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
entry.target.classList.add('in-view');
var delay = entry.target.getAttribute('data-delay');
if (delay != null) {
entry.target.style.animationDelay = (parseInt(delay, 10) * 0.12) + 's';
}
}
});
}, { rootMargin: '0px 0px -40px 0px', threshold: 0.05 });
els.forEach(function (el) { return observer.observe(el); });
}
function initOnboarding() {
var overlay = document.getElementById('onboardingOverlay');
var steps = overlay ? overlay.querySelectorAll('.onboarding-step') : [];
var dotsContainer = overlay ? overlay.querySelector('.onboarding-dots') : null;
var backBtn = overlay ? overlay.querySelector('.onboarding-back') : null;
var nextBtn = overlay ? overlay.querySelector('.onboarding-next') : null;
var startBtn = overlay ? overlay.querySelector('.onboarding-start') : null;
var skipBtn = overlay ? overlay.querySelector('.onboarding-skip') : null;
if (!overlay || steps.length === 0) return;
try {
if (localStorage.getItem('onboarding_done') === '1') {
return;
}
} catch (e) {}
var total = steps.length;
var current = 0;
function showStep(i) {
current = i;
steps.forEach(function (el, idx) {
el.classList.toggle('active', idx === i);
});
if (dotsContainer) {
dotsContainer.querySelectorAll('button').forEach(function (btn, idx) {
btn.classList.toggle('active', idx === i);
});
}
if (backBtn) backBtn.style.display = i === 0 ? 'none' : 'inline-flex';
if (nextBtn) nextBtn.style.display = i === total - 1 ? 'none' : 'inline-flex';
if (startBtn) startBtn.style.display = i === total - 1 ? 'inline-flex' : 'none';
}
steps.forEach(function (_, i) {
var dot = document.createElement('button');
dot.type = 'button';
dot.setAttribute('aria-label', 'Step ' + (i + 1));
dot.addEventListener('click', function () { showStep(i); });
if (dotsContainer) dotsContainer.appendChild(dot);
});
function closeOnboarding() {
overlay.classList.remove('active');
document.body.style.overflow = '';
try {
localStorage.setItem('onboarding_done', '1');
} catch (e) {}
}
if (backBtn) backBtn.addEventListener('click', function () { showStep(Math.max(0, current - 1)); });
if (nextBtn) nextBtn.addEventListener('click', function () { showStep(Math.min(total - 1, current + 1)); });
if (startBtn) startBtn.addEventListener('click', closeOnboarding);
if (skipBtn) skipBtn.addEventListener('click', closeOnboarding);
overlay.querySelector('.onboarding-backdrop').addEventListener('click', closeOnboarding);
showStep(0);
overlay.classList.add('active');
document.body.style.overflow = 'hidden';
}
// Open domain modal
function openDomainModal() {
domainModal.style.display = 'block';
document.body.style.overflow = 'hidden';
}
// Initialize inline domain search
function initializeInlineDomainSearch() {
if (inlineCheckDomainBtn) {
inlineCheckDomainBtn.addEventListener('click', function () {
const domainName = inlineDomainNameInput.value.trim();
if (!domainName) {
alert('Please enter a domain name');
return;
}
// Validate domain format
const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]?\.[a-zA-Z]{2,}$/;
if (!domainRegex.test(domainName)) {
alert('Please enter a valid domain name (e.g., example.com)');
return;
}
checkInlineDomainAvailability(domainName);
});
}
// Allow Enter key to trigger domain check
if (inlineDomainNameInput) {
inlineDomainNameInput.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
inlineCheckDomainBtn.click();
}
});
}
}
// Check domain availability for inline search
async function checkInlineDomainAvailability(domainName) {
const resultsDiv = inlineDomainResults;
// Show loading state
resultsDiv.innerHTML = '<div class="domain-result-inline"><p><i class="fas fa-spinner fa-spin"></i> Checking domain availability...</p></div>';
try {
const response = await fetch(`${CONFIG.BACKEND_URL}/check-domain`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
domain: domainName,
apiKey: CONFIG.DYNADOT_API_KEY
})
});
const data = await response.json();
displayInlineDomainResults(data);
} catch (error) {
console.error('Error checking domain:', error);
resultsDiv.innerHTML = `
<div class="domain-result-inline unavailable">
<h4>❌ Error checking domain</h4>
<p>Error checking domain availability. Please try again.</p>
</div>
`;
}
}
// Display inline domain search results
function displayInlineDomainResults(data) {
const resultsDiv = inlineDomainResults;
if (data.available) {
const price = data.price || 'Contact for pricing';
resultsDiv.innerHTML = `
<div class="domain-result-inline available">
<h4>✅ ${data.domain} is available!</h4>
<div class="domain-details-inline">
<p><strong>Domain:</strong> ${data.domain}</p>
<p><strong>Price:</strong> <span class="price">$${price}</span> ${data.currency || 'USD'}</p>
<p><strong>Status:</strong> Available for registration</p>
</div>
<button class="btn btn-primary" onclick="purchaseDomain('${data.domain}', ${price})" style="margin-top: 1rem;">
<i class="fas fa-shopping-cart"></i> Purchase Domain
</button>
</div>
`;
} else {
resultsDiv.innerHTML = `
<div class="domain-result-inline unavailable">
<h4>❌ ${data.domain} is not available</h4>
<p>This domain is already registered. Try searching for a different domain name.</p>
</div>
`;
}
}
// Navigation functionality
function initializeNavigation() {
const hamburger = document.querySelector('.hamburger');
const navMenu = document.querySelector('.nav-menu');
hamburger.addEventListener('click', function () {
hamburger.classList.toggle('active');
navMenu.classList.toggle('active');
});
// Close mobile menu when clicking on a link
document.querySelectorAll('.nav-link').forEach(link => {
link.addEventListener('click', function () {
hamburger.classList.remove('active');
navMenu.classList.remove('active');
});
});
// Smooth scrolling for anchor links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
// Navbar background on scroll
window.addEventListener('scroll', function () {
const navbar = document.querySelector('.navbar');
if (window.scrollY > 100) {
navbar.style.background = 'rgba(255, 255, 255, 0.98)';
} else {
navbar.style.background = 'rgba(255, 255, 255, 0.95)';
}
});
}
// Pricing buttons functionality
function initializePricingButtons() {
document.querySelectorAll('.pricing-btn, .maintenance-btn').forEach(button => {
button.addEventListener('click', function () {
const plan = this.getAttribute('data-plan');
if (plan) {
openPaymentModal(plan);
}
});
});
}
// Modal functionality
function initializeModals() {
// Close modals when clicking the X
document.querySelectorAll('.close').forEach(closeBtn => {
closeBtn.addEventListener('click', function () {
const modal = this.closest('.modal');
modal.style.display = 'none';
});
});
// Close modals when clicking outside
window.addEventListener('click', function (e) {
if (e.target.classList.contains('modal')) {
e.target.style.display = 'none';
}
});
// Close modals with Escape key
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
document.querySelectorAll('.modal').forEach(modal => {
modal.style.display = 'none';
});
}
});
}
// Carousel (Recent work)
function initializeCarousel() {
const track = document.querySelector('.carousel-track');
const slides = document.querySelectorAll('.carousel-slide');
const prevBtn = document.querySelector('.carousel-prev');
const nextBtn = document.querySelector('.carousel-next');
const dotsContainer = document.querySelector('.carousel-dots');
if (!track || !slides.length) return;
let index = 0;
const total = slides.length;
function goTo(i) {
index = (i + total) % total;
track.style.transform = 'translateX(-' + index * 100 + '%)';
dotsContainer.querySelectorAll('button').forEach((btn, j) => {
btn.classList.toggle('active', j === index);
});
}
slides.forEach((_, i) => {
const dot = document.createElement('button');
dot.setAttribute('type', 'button');
dot.setAttribute('aria-label', 'Slide ' + (i + 1));
dot.addEventListener('click', () => goTo(i));
dotsContainer.appendChild(dot);
});
if (prevBtn) prevBtn.addEventListener('click', () => goTo(index - 1));
if (nextBtn) nextBtn.addEventListener('click', () => goTo(index + 1));
goTo(0);
}
// AI Site Builder: store description and redirect to builder
function initializeAiBuilder() {
const textarea = document.getElementById('aiDescription');
const btn = document.getElementById('aiBuildBtn');
if (!textarea || !btn) return;
btn.addEventListener('click', function () {
const description = textarea.value.trim();
if (description) {
try {
sessionStorage.setItem('aiSiteDescription', description);
} catch (e) {}
}
window.location.href = '/builder.html' + (description ? '?ai=1' : '');
});
}
// Portfolio images functionality
function initializePortfolioImages() {
const portfolioImages = document.querySelectorAll('.portfolio-image img');
const portfolioScreenshots = document.querySelectorAll('.portfolio-screenshot');
// Handle screenshot images
portfolioScreenshots.forEach(img => {
img.addEventListener('load', function () {
const fallback = this.nextElementSibling;
if (fallback && fallback.classList.contains('portfolio-fallback')) {
fallback.style.display = 'none';
}
});
img.addEventListener('error', function () {
this.style.display = 'none';
const fallback = this.nextElementSibling;
if (fallback && fallback.classList.contains('portfolio-fallback')) {
fallback.style.display = 'flex';
}
});
// Show fallback initially, hide when image loads
const fallback = img.nextElementSibling;
if (fallback && fallback.classList.contains('portfolio-fallback')) {
fallback.style.display = 'flex';
}
});
// Handle image fallbacks (for backward compatibility)
portfolioImages.forEach(img => {
// Check if image loads successfully
img.addEventListener('load', function () {
const fallback = this.nextElementSibling;
if (fallback && fallback.classList.contains('portfolio-fallback')) {
fallback.style.display = 'none';
}
});
img.addEventListener('error', function () {
this.style.display = 'none';
const fallback = this.nextElementSibling;
if (fallback && fallback.classList.contains('portfolio-fallback')) {
fallback.style.display = 'flex';
}
});
// If image src is empty or invalid, show fallback immediately
if (!img.src || img.src.includes('placeholder') || img.src.endsWith('.jpg')) {
img.style.display = 'none';
const fallback = img.nextElementSibling;
if (fallback && fallback.classList.contains('portfolio-fallback')) {
fallback.style.display = 'flex';
}
}
});
}
// Domain search functionality
function initializeDomainSearch() {
checkDomainBtn.addEventListener('click', function () {
const domainName = domainNameInput.value.trim();
if (!domainName) {
alert('Please enter a domain name');
return;
}
// Validate domain format
const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]?\.[a-zA-Z]{2,}$/;
if (!domainRegex.test(domainName)) {
alert('Please enter a valid domain name (e.g., example.com)');
return;
}
checkDomainAvailability(domainName);
});
// Allow Enter key to trigger domain check
domainNameInput.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
checkDomainBtn.click();
}
});
}
// Check domain availability using Dynadot API
async function checkDomainAvailability(domainName) {
const resultsDiv = domainResults;
resultsDiv.innerHTML = '<div class="loading">Checking availability...</div>';
try {
// Note: In a real implementation, you would make this call from your backend
// to keep your API key secure
const response = await fetch(`${CONFIG.BACKEND_URL}/check-domain`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
domain: domainName,
apiKey: CONFIG.DYNADOT_API_KEY
})
});
const data = await response.json();
displayDomainResults(data);
} catch (error) {
console.error('Error checking domain:', error);
resultsDiv.innerHTML = `
<div class="error">
<p>Error checking domain availability. Please try again.</p>
<p>Note: This is a demo. In production, you would need to set up a backend to handle the Dynadot API calls.</p>
</div>
`;
}
}
// Display domain search results
function displayDomainResults(data) {
const resultsDiv = domainResults;
if (data.available) {
const price = data.price || 12.99; // Default price if not provided
const commission = (price * CONFIG.COMMISSION_RATE).toFixed(2);
resultsDiv.innerHTML = `
<div class="domain-result available">
<h4>✅ ${data.domain} is available!</h4>
<div class="domain-details">
<p><strong>Price:</strong> $${price}/year</p>
<p><strong>Your Commission:</strong> $${commission}</p>
<p><strong>Total Cost:</strong> $${(parseFloat(price) + parseFloat(commission)).toFixed(2)}</p>
</div>
<button class="btn btn-primary" onclick="purchaseDomain('${data.domain}', ${price})">
Purchase Domain
</button>
</div>
`;
} else {
resultsDiv.innerHTML = `
<div class="domain-result unavailable">
<h4>❌ ${data.domain} is not available</h4>
<p>This domain is already registered. Try searching for a different domain name.</p>
</div>
`;
}
}
// Purchase domain
async function purchaseDomain(domainName, price) {
try {
// Close domain modal if it's open
if (domainModal && domainModal.style.display === 'block') {
domainModal.style.display = 'none';
document.body.style.overflow = 'auto';
// Small delay to ensure smooth transition
setTimeout(() => {
showDomainPaymentModal(domainName, price);
}, 100);
} else {
// Show payment modal immediately if no domain modal is open
showDomainPaymentModal(domainName, price);
}
} catch (error) {
console.error('Error purchasing domain:', error);
alert('Error purchasing domain. Please try again.');
}
}
// Show domain payment modal
function showDomainPaymentModal(domainName, price) {
// Update modal title and content
const modal = document.getElementById('paymentModal');
const modalTitle = modal.querySelector('h2');
const paymentForm = document.getElementById('paymentForm');
modalTitle.textContent = `Purchase Domain: ${domainName}`;
// Create domain payment form
paymentForm.innerHTML = `
<div class="domain-purchase-info">
<div class="purchase-item">
<h4>Domain Registration</h4>
<p><strong>Domain:</strong> ${domainName}</p>
<p><strong>Price:</strong> $${price}</p>
<p><strong>Commission (15%):</strong> $${(price * CONFIG.COMMISSION_RATE).toFixed(2)}</p>
<hr>
<p class="total-price"><strong>Total: $${(price + (price * CONFIG.COMMISSION_RATE)).toFixed(2)}</strong></p>
</div>
</div>
<div id="domainPaymentForm">
<!-- Stripe payment form will be loaded here -->
</div>
`;
// Show modal
modal.style.display = 'block';
document.body.style.overflow = 'hidden';
// Initialize Stripe payment for domain
initializeDomainPayment(domainName, price);
}
// Initialize domain payment with Stripe
async function initializeDomainPayment(domainName, price) {
try {
await initStripe();
if (!stripe) {
throw new Error('Stripe not initialized');
}
// Create payment intent for domain purchase
const response = await fetch(`${CONFIG.BACKEND_URL}/create-domain-payment`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
domain: domainName,
price: price,
currency: 'usd'
})
});
if (!response.ok) {
throw new Error('Failed to create payment intent');
}
const { clientSecret } = await response.json();
// Create Stripe Elements
const elements = stripe.elements({
clientSecret: clientSecret,
appearance: {
theme: 'stripe',
variables: {
colorPrimary: '#6366f1',
}
}
});
// Create payment element
const paymentElement = elements.create('payment');
paymentElement.mount('#domainPaymentForm');
// Handle form submission
const form = document.createElement('form');
form.id = 'domainPaymentFormElement';
form.innerHTML = `
<button type="submit" class="btn btn-primary" style="width: 100%; margin-top: 1rem;">
<i class="fas fa-credit-card"></i> Complete Purchase - $${(price + (price * CONFIG.COMMISSION_RATE)).toFixed(2)}
</button>
`;
document.getElementById('domainPaymentForm').appendChild(form);
form.addEventListener('submit', async (event) => {
event.preventDefault();
const submitButton = form.querySelector('button');
submitButton.disabled = true;
submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
try {
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: `${CONFIG.BASE_URL}/success.html?domain=${encodeURIComponent(domainName)}`,
},
});
if (error) {
console.error('Payment failed:', error);
alert(`Payment failed: ${error.message}`);
submitButton.disabled = false;
submitButton.innerHTML = '<i class="fas fa-credit-card"></i> Complete Purchase';
}
} catch (error) {
console.error('Payment error:', error);
alert('Payment error. Please try again.');
submitButton.disabled = false;
submitButton.innerHTML = '<i class="fas fa-credit-card"></i> Complete Purchase';
}
});
} catch (error) {
console.error('Error initializing domain payment:', error);
document.getElementById('domainPaymentForm').innerHTML = `
<div class="error-message">
<p><i class="fas fa-exclamation-triangle"></i> Error setting up payment. Please try again.</p>
<button class="btn btn-secondary" onclick="document.getElementById('paymentModal').style.display='none'">Close</button>
</div>
`;
}
}
// Open payment modal
function openPaymentModal(planKey) {
const plan = PRICING[planKey];
if (!plan) {
console.error('Invalid plan:', planKey);
return;
}
paymentModal.style.display = 'block';
// Create payment form based on plan type
if (plan.type === 'one-time') {
createOneTimePaymentForm(plan);
} else {
createSubscriptionForm(plan);
}
}
// Create one-time payment form
function createOneTimePaymentForm(plan) {
paymentForm.innerHTML = `
<div class="payment-plan-info">
<h3>${plan.name}</h3>
<div class="price-display">
<span class="currency">$</span>
<span class="amount">${plan.price.toLocaleString()}</span>
<span class="period">one-time</span>
</div>
</div>
<form id="payment-form">
<div class="form-group">
<label for="customer-name">Full Name</label>
<input type="text" id="customer-name" name="name" required>
</div>
<div class="form-group">
<label for="customer-email">Email</label>
<input type="email" id="customer-email" name="email" required>
</div>
<div class="form-group">
<label for="customer-phone">Phone Number</label>
<input type="tel" id="customer-phone" name="phone">
</div>
<div class="form-group">
<label for="project-details">Project Details</label>
<textarea id="project-details" name="projectDetails" rows="4"
placeholder="Tell me about your project requirements..."></textarea>
</div>
<div id="payment-element">
<!-- Stripe Elements will be inserted here -->
</div>
<button type="submit" id="submit-payment" class="btn btn-primary">
Pay $${plan.price.toLocaleString()}
</button>
</form>
`;
initializeStripeElements(plan);
}
// Create subscription form
function createSubscriptionForm(plan) {
paymentForm.innerHTML = `
<div class="payment-plan-info">
<h3>${plan.name}</h3>
<div class="price-display">
<span class="currency">$</span>
<span class="amount">${plan.price}</span>
<span class="period">/month</span>
</div>
</div>
<form id="subscription-form">
<div class="form-group">
<label for="customer-name">Full Name</label>
<input type="text" id="customer-name" name="name" required>
</div>
<div class="form-group">
<label for="customer-email">Email</label>
<input type="email" id="customer-email" name="email" required>
</div>
<div class="form-group">
<label for="customer-phone">Phone Number</label>
<input type="tel" id="customer-phone" name="phone">
</div>
<div class="form-group">
<label for="website-url">Website URL (if applicable)</label>
<input type="url" id="website-url" name="websiteUrl"
placeholder="https://yourwebsite.com">
</div>
<div id="payment-element">
<!-- Stripe Elements will be inserted here -->
</div>
<button type="submit" id="submit-subscription" class="btn btn-primary">
Subscribe for $${plan.price}/month
</button>
</form>
`;
initializeStripeSubscription(plan);
}
// Initialize Stripe Elements for one-time payments
async function initializeStripeElements(plan) {
try {
await initStripe();
// Check if Stripe is available
if (!stripe) {
throw new Error('Stripe not initialized');
}
// Create payment intent on your backend
const response = await fetch(`${CONFIG.BACKEND_URL}/create-payment-intent`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: plan.price * 100, // Convert to cents
currency: 'usd',
plan: plan.name
})
});
if (!response.ok) {
throw new Error('Failed to create payment intent');
}
const { clientSecret } = await response.json();
// Create Stripe Elements
const elements = stripe.elements({
clientSecret: clientSecret,
appearance: {
theme: 'stripe',
variables: {
colorPrimary: '#6366f1',
borderRadius: '8px',
fontFamily: 'Inter, sans-serif'
}
}
});
const paymentElement = elements.create('payment');
paymentElement.mount('#payment-element');
// Handle form submission
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const submitButton = document.getElementById('submit-payment');
submitButton.disabled = true;
submitButton.textContent = 'Processing...';
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: `${CONFIG.BASE_URL}/esign.html`,
},
});
if (error) {
console.error('Payment failed:', error);
alert('Payment failed. Please try again.');
submitButton.disabled = false;
submitButton.textContent = `Pay $${plan.price.toLocaleString()}`;
}
});
} catch (error) {
console.error('Error initializing payment:', error);
showPaymentError(plan, 'one-time', error);
}
}
// Show error when Stripe/live payment cannot be loaded (no demo form)
function showPaymentError(plan, type, err) {
if (err) console.error('Payment error:', err.message || err);
const paymentElement = document.getElementById('payment-element');
const isSubscription = type === 'subscription';
const subject = encodeURIComponent(isSubscription ? 'Subscribe: ' + plan.name : 'Pay: ' + plan.name);
paymentElement.innerHTML = `
<div class="payment-error-box">
<h4>Payment system temporarily unavailable</h4>
<p>We couldn't connect to secure checkout. This can happen if the payment server is starting up (try again in 30 seconds) or there's a connection issue.</p>
<p class="payment-error-contact">You can <a href="mailto:matty@vibecodes.space?subject=${subject}">email us</a> to complete your order.</p>
<button type="button" class="btn btn-primary" id="retry-payment-btn">Try again</button>
</div>
`;
document.getElementById('retry-payment-btn').addEventListener('click', () => {
paymentElement.innerHTML = '<div class="payment-loading">Loading checkout…</div>';
if (isSubscription) initializeStripeSubscription(plan);
else initializeStripeElements(plan);
});
}
// Initialize Stripe subscription
async function initializeStripeSubscription(plan) {
try {
await initStripe();
// Check if Stripe is available
if (!stripe) {
throw new Error('Stripe not initialized');
}
// Create subscription on your backend
const response = await fetch(`${CONFIG.BACKEND_URL}/create-subscription`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
price: plan.price * 100, // Convert to cents
currency: 'usd',
plan: plan.name
})
});
if (!response.ok) {
throw new Error('Failed to create subscription');
}
const { clientSecret } = await response.json();
// Create Stripe Elements
const elements = stripe.elements({
clientSecret: clientSecret,
appearance: {
theme: 'stripe',
variables: {
colorPrimary: '#6366f1',
borderRadius: '8px',
fontFamily: 'Inter, sans-serif'
}
}
});
const paymentElement = elements.create('payment');
paymentElement.mount('#payment-element');
// Handle form submission
const form = document.getElementById('subscription-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const submitButton = document.getElementById('submit-subscription');
submitButton.disabled = true;
submitButton.textContent = 'Processing...';
const { error } = await stripe.confirmSetup({
elements,
confirmParams: {
return_url: `${CONFIG.BASE_URL}/esign.html`,
},
});
if (error) {
console.error('Subscription failed:', error);
alert('Subscription failed. Please try again.');
submitButton.disabled = false;
submitButton.textContent = `Subscribe for $${plan.price}/month`;
}
});
} catch (error) {
console.error('Error initializing subscription:', error);
showPaymentError(plan, 'subscription', error);
}
}
// Close payment modal
function closePaymentModal() {
const modal = document.getElementById('paymentModal');
modal.style.display = 'none';
// Reset the form for next time
setTimeout(() => {
paymentForm.innerHTML = '';
}, 300);
}