-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
746 lines (658 loc) · 26.5 KB
/
Copy pathscript.js
File metadata and controls
746 lines (658 loc) · 26.5 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
/* =========================================================
Agentic Architect — Marketing site interactions
- Sticky CTA visibility after hero
- Scroll reveals
- Exit-intent modal (desktop) / scroll-tail trigger (mobile)
- Current year stamp
========================================================= */
(() => {
'use strict';
/* ---------- Cookie consent (site-wide, injected once) ---------- */
const COOKIE_KEY = 'aa_cookie_consent_v1';
const PREFS_KEY = 'aa_cookie_prefs_v1';
const GOOGLE_ADS_ID = 'AW-18295180192';
const pushUetConsent = (granted) => {
window.uetq = window.uetq || [];
window.uetq.push('consent', 'update', { ad_storage: granted ? 'granted' : 'denied' });
};
const syncUetConsent = (prefs) => {
pushUetConsent(!!prefs.marketing);
};
const loadGoogleAdsTag = () => {
if (window.__aaGoogleAdsLoaded) return;
window.__aaGoogleAdsLoaded = true;
const s = document.createElement('script');
s.async = true;
s.src = `https://www.googletagmanager.com/gtag/js?id=${GOOGLE_ADS_ID}`;
s.onload = () => {
gtag('js', new Date());
gtag('config', GOOGLE_ADS_ID);
document.dispatchEvent(new CustomEvent('aa:google-ads-ready'));
};
document.head.appendChild(s);
};
const pushGoogleAdsConsent = (granted) => {
window.gtag = window.gtag || function gtagStub() {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push(arguments);
};
gtag('consent', 'update', {
ad_storage: granted ? 'granted' : 'denied',
ad_user_data: granted ? 'granted' : 'denied',
ad_personalization: granted ? 'granted' : 'denied',
});
if (granted) loadGoogleAdsTag();
};
const syncGoogleAdsConsent = (prefs) => {
pushGoogleAdsConsent(!!prefs.marketing);
};
const sitePrefix = () => {
const path = window.location.pathname;
const marker = '/agentic-architect/';
const idx = path.indexOf(marker);
const rest = idx >= 0 ? path.slice(idx + marker.length) : path.replace(/^\//, '');
const depth = (rest.match(/\//g) || []).length;
return depth ? '../'.repeat(depth) : '';
};
const readPrefs = () => {
try {
const raw = localStorage.getItem(PREFS_KEY);
if (raw) return JSON.parse(raw);
} catch (_) { /* ignore corrupt prefs */ }
return { analytics: true, marketing: true };
};
const writePrefs = (prefs) => {
localStorage.setItem(PREFS_KEY, JSON.stringify(prefs));
};
const applyConsent = (choice, prefs) => {
localStorage.setItem(COOKIE_KEY, choice);
const resolved = prefs || readPrefs();
if (prefs) writePrefs(prefs);
document.documentElement.classList.add('cookie-consent-set');
syncUetConsent(resolved);
syncGoogleAdsConsent(resolved);
document.dispatchEvent(new CustomEvent('aa:cookie-consent', { detail: { choice, prefs: resolved } }));
};
const hideBar = (bar) => {
bar.classList.add('is-hidden');
bar.setAttribute('aria-hidden', 'true');
};
const prefix = sitePrefix();
const privacyHref = `${prefix}privacy-policy.html`;
const thirdPartyHref = `${prefix}index.html#faq`;
const infoIcon = '<svg class="cookie-consent-icon" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"/></svg>';
const mountCookieConsent = () => {
if (document.getElementById('cookie-consent')) return;
const bar = document.createElement('div');
bar.id = 'cookie-consent';
bar.setAttribute('role', 'region');
bar.setAttribute('aria-label', 'Cookie consent');
bar.innerHTML = `
<div class="cookie-consent-inner">
${infoIcon}
<div class="cookie-consent-body">
<p class="cookie-consent-text">
We use optional cookies for analytics (GoatCounter) and to improve the site, including newsletter forms (MailerLite).
You can accept, reject, or manage preferences.
See our <a href="${privacyHref}">Privacy statement</a> and
<a href="${thirdPartyHref}">Third-party cookies</a>.
</p>
<div class="cookie-consent-actions">
<button type="button" class="cookie-consent-btn cookie-consent-btn--accept" data-cookie-action="accept">Accept</button>
<button type="button" class="cookie-consent-btn cookie-consent-btn--reject" data-cookie-action="reject">Reject</button>
<button type="button" class="cookie-consent-btn cookie-consent-btn--manage" data-cookie-action="manage" aria-expanded="false" aria-controls="cookie-consent-panel">Manage cookies</button>
</div>
<div class="cookie-consent-panel" id="cookie-consent-panel">
<div class="cookie-pref-row">
<div class="cookie-pref-info">
<strong>Essential</strong>
<span>Required for the site to work. Always on.</span>
</div>
<label class="cookie-pref-toggle" aria-label="Essential cookies, always on">
<input type="checkbox" checked disabled>
<span class="cookie-pref-slider"></span>
</label>
</div>
<div class="cookie-pref-row">
<div class="cookie-pref-info">
<strong>Analytics</strong>
<span>GoatCounter, privacy-friendly page views. No ad tracking.</span>
</div>
<label class="cookie-pref-toggle" aria-label="Analytics cookies">
<input type="checkbox" id="cookie-pref-analytics" checked>
<span class="cookie-pref-slider"></span>
</label>
</div>
<div class="cookie-pref-row">
<div class="cookie-pref-info">
<strong>Marketing</strong>
<span>MailerLite signup forms, Microsoft Ads, and Google Ads conversion tracking.</span>
</div>
<label class="cookie-pref-toggle" aria-label="Marketing cookies">
<input type="checkbox" id="cookie-pref-marketing" checked>
<span class="cookie-pref-slider"></span>
</label>
</div>
<div class="cookie-consent-panel-actions">
<button type="button" class="cookie-consent-btn cookie-consent-btn--accept" data-cookie-action="save-prefs">Save preferences</button>
<button type="button" class="cookie-consent-btn cookie-consent-btn--reject" data-cookie-action="cancel-manage">Cancel</button>
</div>
</div>
</div>
</div>`;
const insertTarget = document.body.firstChild;
if (insertTarget) document.body.insertBefore(bar, insertTarget);
else document.body.appendChild(bar);
const manageBtn = bar.querySelector('[data-cookie-action="manage"]');
const analyticsInput = bar.querySelector('#cookie-pref-analytics');
const marketingInput = bar.querySelector('#cookie-pref-marketing');
const openManage = () => {
const prefs = readPrefs();
analyticsInput.checked = !!prefs.analytics;
marketingInput.checked = !!prefs.marketing;
bar.classList.add('is-managing');
manageBtn.setAttribute('aria-expanded', 'true');
};
const closeManage = () => {
bar.classList.remove('is-managing');
manageBtn.setAttribute('aria-expanded', 'false');
};
bar.addEventListener('click', (e) => {
const btn = e.target.closest('[data-cookie-action]');
if (!btn) return;
const action = btn.getAttribute('data-cookie-action');
if (action === 'accept') {
applyConsent('accepted', { analytics: true, marketing: true });
hideBar(bar);
return;
}
if (action === 'reject') {
applyConsent('rejected', { analytics: false, marketing: false });
hideBar(bar);
return;
}
if (action === 'manage') {
openManage();
return;
}
if (action === 'save-prefs') {
const prefs = {
analytics: analyticsInput.checked,
marketing: marketingInput.checked,
};
applyConsent('managed', prefs);
hideBar(bar);
return;
}
if (action === 'cancel-manage') closeManage();
});
return bar;
};
const storedConsent = localStorage.getItem(COOKIE_KEY);
if (storedConsent) {
document.documentElement.classList.add('cookie-consent-set');
const prefs = readPrefs();
syncUetConsent(prefs);
syncGoogleAdsConsent(prefs);
} else {
mountCookieConsent();
}
/* ---------- Year stamp ---------- */
const yearEl = document.getElementById('year');
if (yearEl) yearEl.textContent = new Date().getFullYear();
/* ---------- Shared site nav (links + CTAs + hamburger) ---------- */
const STRIPE_BUY =
'https://payhip.com/b/98aSq?utm_source=site&utm_medium=nav_buy&utm_campaign=paid_kit';
const BRAND_MARK =
'<span class="brand-mono" aria-hidden="true">' +
'<span class="brand-bracket">[</span>' +
'<span class="brand-name brand-full">agentic-architect</span>' +
'<span class="brand-name brand-short">aa</span>' +
'<span class="brand-bracket">]</span>' +
'</span>';
const getNavContext = () => {
const path = window.location.pathname.replace(/\\/g, '/');
const inBlog = /\/blog(\/|$)/.test(path);
const inHardware = /\/hardware(\/|$)/.test(path);
const inLearn = /\/learn(\/|$)/.test(path);
const inSubdir = inBlog || inHardware || inLearn;
const prefix = inSubdir ? '../' : '';
let section = 'root';
if (inBlog) section = 'blog';
else if (inHardware) section = 'hardware';
else if (inLearn) section = 'learn';
const hash = (id) => (inSubdir ? `${prefix}#${id}` : `#${id}`);
return {
section,
prefix,
brandHref: inSubdir ? '../' : '#top',
freeKitHref: inSubdir ? '../#free-kit-signup' : '#free-kit-signup',
blogHref: section === 'root' ? 'blog/' : inBlog ? './' : `${prefix}blog/`,
hardwareHref: section === 'root' ? 'hardware/' : inHardware ? './' : `${prefix}hardware/`,
learnHref: section === 'root' ? 'learn/' : inLearn ? './' : `${prefix}learn/`,
hash,
};
};
const mountSiteNav = () => {
const header = document.querySelector('header.nav');
if (!header || header.classList.contains('nav-skip-inject')) return;
const mount = header.querySelector('[data-site-nav]') || header.querySelector('.nav-inner');
if (!mount) return;
const ctx = getNavContext();
const link = (href, label, current) =>
`<a href="${href}"${current ? ' aria-current="page"' : ''}>${label}</a>`;
const links = [
link(ctx.hash('problem'), 'The Problem', false),
link(ctx.hash('kit'), "What's Inside", false),
link(ctx.hash('proof'), 'Proof', false),
link(ctx.hash('pricing'), 'Pricing', false),
link(ctx.hash('faq'), 'FAQ', false),
link(ctx.blogHref, 'Blog', ctx.section === 'blog'),
link(ctx.hardwareHref, 'Hardware', ctx.section === 'hardware'),
link(ctx.learnHref, 'Quick Fixes', ctx.section === 'learn'),
link(ctx.hash('resources'), 'Guides', false),
].join('\n ');
mount.innerHTML =
`<a href="${ctx.brandHref}" class="brand" aria-label="Agentic Architect home">` +
BRAND_MARK + '</a>' +
`<nav id="navMenu" class="nav-links nav-links-panel" aria-label="Primary">
${links}
<div class="nav-menu-ctas">
<a href="${ctx.freeKitHref}" class="btn btn-ghost btn-sm">Get the free kit</a>
<a href="${STRIPE_BUY}" class="btn btn-primary btn-sm" target="_blank" rel="noopener">Buy now</a>
</div>
</nav>` +
`<div class="nav-ctas">
<a href="${ctx.freeKitHref}" class="btn btn-ghost btn-sm nav-cta-free">Get the free kit</a>
<a href="${STRIPE_BUY}" class="btn btn-primary btn-sm nav-cta-buy" target="_blank" rel="noopener">Buy now</a>
</div>` +
'<button type="button" class="nav-toggle" aria-expanded="false" aria-controls="navMenu" aria-label="Open menu">' +
'<span class="nav-toggle-icon" aria-hidden="true"><span></span><span></span><span></span></span></button>';
};
mountSiteNav();
/* ---------- Mobile nav (overlay panel + auto-close) ---------- */
const navToggle = document.querySelector('.nav-toggle');
const navPanel = document.querySelector('.nav-links-panel');
if (navToggle && navPanel) {
let backdrop = document.querySelector('.nav-backdrop');
if (!backdrop) {
backdrop = document.createElement('div');
backdrop.className = 'nav-backdrop';
backdrop.setAttribute('aria-hidden', 'true');
document.body.appendChild(backdrop);
}
const closeNav = () => {
navToggle.setAttribute('aria-expanded', 'false');
navToggle.setAttribute('aria-label', 'Open menu');
navPanel.classList.remove('open');
backdrop.classList.remove('open');
document.body.classList.remove('nav-open');
};
const openNav = () => {
navToggle.setAttribute('aria-expanded', 'true');
navToggle.setAttribute('aria-label', 'Close menu');
navPanel.classList.add('open');
backdrop.classList.add('open');
document.body.classList.add('nav-open');
};
navToggle.addEventListener('click', () => {
const isOpen = navToggle.getAttribute('aria-expanded') === 'true';
if (isOpen) closeNav();
else openNav();
});
backdrop.addEventListener('click', closeNav);
navPanel.querySelectorAll('a').forEach((link) => {
link.addEventListener('click', () => closeNav());
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && navPanel.classList.contains('open')) closeNav();
});
const desktopMQ = window.matchMedia('(min-width: 821px)');
const onDesktop = (e) => { if (e.matches) closeNav(); };
if (desktopMQ.addEventListener) desktopMQ.addEventListener('change', onDesktop);
else desktopMQ.addListener(onDesktop);
}
/* ---------- Hash scroll: align section title just under sticky nav ---------- */
const ANCHOR_GAP_PX = 12;
const prefersReducedMotion = () =>
window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const samePageHash = (anchor) => {
if (!anchor || !anchor.getAttribute) return null;
const href = anchor.getAttribute('href');
if (!href || href.indexOf('#') === -1) return null;
let url;
try {
url = new URL(anchor.href, window.location.href);
} catch (_) {
return null;
}
const norm = (p) => {
let s = (p || '/').replace(/\\/g, '/');
if (s.endsWith('/index.html')) s = s.slice(0, -10) || '/';
if (s.length > 1 && s.endsWith('/')) s = s.slice(0, -1);
return s || '/';
};
if (norm(url.pathname) !== norm(window.location.pathname)) return null;
if (!url.hash || url.hash === '#') return null;
return url.hash;
};
const headingForHash = (hash) => {
const id = (hash || '').replace(/^#/, '');
if (!id) return null;
const section = document.getElementById(id);
if (!section) return null;
return (
section.querySelector('.section-head h2') ||
section.querySelector('h2') ||
section.querySelector('.section-head') ||
section
);
};
const scrollToHash = (hash, behavior) => {
const heading = headingForHash(hash);
if (!heading) return false;
// Settle reveal transforms before measuring. .reveal uses translateY(14px)
// with a 0.5s transition — disable transition so layout is final immediately.
const settleReveal = (el) => {
if (!el || !el.classList.contains('reveal')) return;
el.style.transition = 'none';
el.classList.add('in');
void el.offsetWidth;
};
const section = document.getElementById((hash || '').replace(/^#/, ''));
if (section) settleReveal(section.querySelector('.section-head'));
settleReveal(heading.classList && heading.classList.contains('section-head') ? heading : null);
settleReveal(heading.closest && heading.closest('.section-head'));
const nav = document.querySelector('header.nav');
const navH = nav ? nav.getBoundingClientRect().height : 0;
const top = Math.max(
0,
heading.getBoundingClientRect().top + window.scrollY - navH - ANCHOR_GAP_PX
);
const b = behavior || (prefersReducedMotion() ? 'auto' : 'smooth');
window.scrollTo({ top, behavior: b });
return true;
};
document.addEventListener('click', (e) => {
const anchor = e.target.closest && e.target.closest('a[href*="#"]');
if (!anchor) return;
const hash = samePageHash(anchor);
if (!hash) return;
if (hash === '#top') {
e.preventDefault();
window.scrollTo({ top: 0, behavior: prefersReducedMotion() ? 'auto' : 'smooth' });
if (history.pushState) history.pushState(null, '', '#top');
else window.location.hash = 'top';
return;
}
if (!headingForHash(hash)) return;
e.preventDefault();
if (history.pushState) history.pushState(null, '', hash);
else window.location.hash = hash.slice(1);
scrollToHash(hash);
});
window.addEventListener('hashchange', () => {
if (location.hash && headingForHash(location.hash)) {
scrollToHash(location.hash);
}
});
if (location.hash && headingForHash(location.hash)) {
// Override the browser's un-offset jump after layout settles
const apply = () => scrollToHash(location.hash, 'auto');
requestAnimationFrame(() => requestAnimationFrame(apply));
window.addEventListener('load', apply, { once: true });
}
/* ---------- Sticky CTA visibility ---------- */
const sticky = document.getElementById('stickyCTA');
const hero = document.querySelector('.hero');
if (sticky && hero) {
const io = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) sticky.classList.add('visible');
else sticky.classList.remove('visible');
});
},
{ threshold: 0, rootMargin: '-200px 0px 0px 0px' }
);
io.observe(hero);
}
/* ---------- Scroll reveals ---------- */
const revealTargets = document.querySelectorAll(
'.section-head, .pain-card, .ba-col, .kit-card, .step, .quote, .two-col-card, .pricing-card, .bonus-stack, .math-grid, .final-cta, .trust-strip, .hero-details-inner, .example-card, .related-card'
);
revealTargets.forEach((el) => el.classList.add('reveal'));
const revealIO = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('in');
revealIO.unobserve(entry.target);
}
});
},
{ threshold: 0.12 }
);
revealTargets.forEach((el) => revealIO.observe(el));
/* ---------- Exit intent modal ---------- */
const modal = document.getElementById('exitModal');
if (modal) {
const SHOWN_KEY = 'aa_exit_shown_v1';
const open = () => {
if (sessionStorage.getItem(SHOWN_KEY)) return;
sessionStorage.setItem(SHOWN_KEY, '1');
modal.classList.add('open');
modal.setAttribute('aria-hidden', 'false');
document.body.style.overflow = 'hidden';
};
const close = () => {
modal.classList.remove('open');
modal.setAttribute('aria-hidden', 'true');
document.body.style.overflow = '';
};
modal.querySelectorAll('[data-close]').forEach((el) => el.addEventListener('click', close));
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && modal.classList.contains('open')) close();
});
const isTouch = window.matchMedia('(hover: none)').matches || 'ontouchstart' in window;
if (!isTouch) {
let armed = false;
setTimeout(() => { armed = true; }, 8000); // arm after 8s so it isn't annoying
document.addEventListener('mouseout', (e) => {
if (!armed) return;
if (!e.relatedTarget && e.clientY <= 4) open();
});
} else {
// Mobile fallback: trigger near the FAQ scroll position once
let triggered = false;
const onScroll = () => {
if (triggered) return;
const scrolled = window.scrollY + window.innerHeight;
const total = document.documentElement.scrollHeight;
if (scrolled / total > 0.75) {
triggered = true;
open();
window.removeEventListener('scroll', onScroll);
}
};
window.addEventListener('scroll', onScroll, { passive: true });
}
}
/* ---------- Free kit signup UX (MailerLite embed) ---------- */
const mountFreeKitSignup = () => {
const section = document.getElementById('free-kit-signup');
if (!section) return;
const box = section.querySelector('.ml-capture-box');
const successPanel = section.querySelector('#ml-capture-success');
const successBody = section.querySelector('#ml-capture-success-body');
if (!box || !successPanel || !successBody) return;
const SESSION_KEY = 'aa_free_kit_signup_v4';
let submitAttempted = false;
let pollTimer = null;
let resetTimer = null;
const isVisible = (el) => {
if (!el) return false;
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') return false;
return el.getClientRects().length > 0;
};
const getEmail = () => {
const input = box.querySelector('input[type="email"]');
return input?.value?.trim() || '';
};
const captureMailerLiteMessage = () => {
const selectors = [
'.ml-form-successBody .ml-form-successContent',
'.row-success .ml-form-successContent',
'.ml-form-successBody',
'.row-success',
];
for (const sel of selectors) {
const el = box.querySelector(sel);
if (isVisible(el)) {
return el.innerHTML.trim();
}
}
return '';
};
const mailerLiteSucceeded = () => {
if (!submitAttempted) return false;
const successEl = box.querySelector('.ml-form-successBody, .row-success');
return isVisible(successEl);
};
const mailerLiteFailed = () => {
if (!submitAttempted) return false;
return !!box.querySelector('.ml-form-fieldRow .ml-error, .ml-form-fieldRow .invalid-feedback, .ml-form-embedContainer .error');
};
const kitReadyMessage = (email) =>
`<p><strong>You're in — grab the kit now.</strong></p>` +
`<p>Three Cursor rules, LEARNING_LOG template, 3-minute install. No need to wait for email.</p>` +
`<p style="margin:16px 0 0"><a class="btn btn-accent btn-lg" href="thank-you-free.html?utm_source=site&utm_medium=signup_success&utm_campaign=free_kit">Download free starter kit</a></p>` +
(email
? `<p style="font-size:0.85rem;color:var(--text-muted);margin:12px 0 0">We also emailed <strong>${email}</strong> a backup link.</p>`
: '');
const fallbackMessage = (email) => kitReadyMessage(email);
const clearPoll = () => {
if (pollTimer) {
window.clearInterval(pollTimer);
pollTimer = null;
}
if (resetTimer) {
window.clearTimeout(resetTimer);
resetTimer = null;
}
};
const showSuccess = (email, messageHtml, fromSession = false) => {
clearPoll();
box.classList.remove('is-submitting');
box.classList.add('is-submitted');
const nativeHtml = captureMailerLiteMessage();
const html = messageHtml || kitReadyMessage(email) || nativeHtml;
/* Prefer our download CTA over MailerLite's generic "check your inbox" copy */
const useNative = false;
box.classList.toggle('ml-native-success', useNative);
box.classList.toggle('use-custom-success', !useNative);
const btn = box.querySelector('button[type="submit"], button.primary');
if (btn) {
btn.classList.remove('is-loading');
btn.removeAttribute('aria-busy');
}
if (useNative) {
successPanel.hidden = true;
} else {
successBody.innerHTML = html;
successPanel.hidden = false;
}
try {
sessionStorage.setItem(
SESSION_KEY,
JSON.stringify({
email: email || '',
messageHtml: html,
useNative,
at: Date.now(),
})
);
} catch (_) { /* private mode */ }
};
const setSubmitting = (on) => {
box.classList.toggle('is-submitting', on);
const btn = box.querySelector('button[type="submit"], button.primary');
if (!btn) return;
if (on) {
if (!btn.dataset.aaOriginalLabel) {
btn.dataset.aaOriginalLabel = btn.textContent.trim();
}
btn.textContent = 'Sending…';
btn.classList.add('is-loading');
btn.setAttribute('aria-busy', 'true');
} else if (!box.classList.contains('is-submitted')) {
btn.textContent = btn.dataset.aaOriginalLabel || 'Submit';
btn.classList.remove('is-loading');
btn.removeAttribute('aria-busy');
}
};
const watchForOutcome = () => {
clearPoll();
pollTimer = window.setInterval(() => {
if (mailerLiteSucceeded()) {
showSuccess(getEmail());
return;
}
if (mailerLiteFailed()) {
submitAttempted = false;
setSubmitting(false);
clearPoll();
}
}, 200);
resetTimer = window.setTimeout(() => {
if (!box.classList.contains('is-submitted')) {
submitAttempted = false;
setSubmitting(false);
}
clearPoll();
}, 30000);
};
const markSubmitStarted = () => {
if (box.classList.contains('is-submitted') || box.classList.contains('is-submitting')) {
return false;
}
submitAttempted = true;
setSubmitting(true);
watchForOutcome();
return true;
};
try {
const saved = sessionStorage.getItem(SESSION_KEY);
if (saved) {
const { email, messageHtml, useNative } = JSON.parse(saved);
submitAttempted = true;
showSuccess(email, messageHtml, true);
box.classList.toggle('ml-native-success', !!useNative);
box.classList.toggle('use-custom-success', !useNative);
return;
}
} catch (_) { /* ignore */ }
/* Bubble phase only — never block MailerLite's own click/submit handlers */
box.addEventListener('submit', (e) => {
if (box.classList.contains('is-submitted')) {
e.preventDefault();
return;
}
markSubmitStarted();
});
const observer = new MutationObserver(() => {
if (box.classList.contains('is-submitted')) return;
if (mailerLiteSucceeded()) {
showSuccess(getEmail());
}
});
observer.observe(box, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['style', 'class'],
});
};
mountFreeKitSignup();
})();